Create new PDF from template with PHP

Viewed 80543

I have a docx document file set up with formating and layout, which I saved as a PDF file. I want to use this pdf file as a template for creating new pdf files pre-filled with user data.

I have seen FPDF, FPDI, tcPDF, domPDF, Zend PDF, http://koivi.com/fill-pdf-form-fields/ (Justin Koivisto), a few convertion tools like HTML2PDF and a few command line tools mentioned here on stackoverflow. With the exception of FPDI, none of them offer an example using a PDF template to either search-and-replace custom tags with actual data (usually from a database) or add data without specifying a bunch of values like x, y, postion, font, font-formating etc.

Creating a PDF from scratch seems like too much work. I have not yet considered using a HTML2PDF converter as the results appear to vary greatly, and then there is the issue with styling. Some tools allow CSS, but often with limits like no float support.

Are there no easy way of using a template like there is for Excel with PHPExcel ?

My need is:

  • Free
  • Load and use a template
  • Search-and-replace custom tags
  • Add data (text, image, font, formating etc)
  • Custom header and footer
  • Must work with shared hosting
  • Allow download, save/store to server and attach to email (preferable without having to save it first) of final generated PDF
11 Answers

I was needing that for a project so I've created a fast tool for that. You can check it and feel free to contribute here

If your server has OpenOffice installed you can use soffice in headless mode to convert RTF-Files (Rich Text Format) to PDF.

  1. Create RTF with template brackets inside Text like "Dear, {{{name}}}, how are you?"

  2. Open the file and load the content with $content=file_get_contents('path_to_file');

  3. Replace the text as you wish: $content=str_replace('{{{name}}}', 'Bruce Wanye', $content);

  4. Save the content to a new file: file_put_contents('path_to_file2', $content);

  5. Now convert to PDF: excec("soffice --headless --convert-to pdf 'path_to_file2' --outdir 'target_directory'");

Related