I am creating .docx
files from a template using PHPWord
. It works fine but now I want to convert the generated file to PDF
.
First I tried using tcpdf
in combination with PHPWord
$wordPdf = \PhpOffice\PhpWord\IOFactory::load($filename.".docx");
\PhpOffice\PhpWord\Settings::setPdfRendererPath(dirname(__FILE__)."/../../Office/tcpdf");
\PhpOffice\PhpWord\Settings::setPdfRendererName('TCPDF');
$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordPdf , 'PDF');
if (file_exists($filename.".pdf")) unlink($filename.".pdf");
$pdfWriter->save($filename.".pdf");
but when I try to load the file to convert it to PDF
I get the following exception while loading the file
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Cannot add PreserveText in Section.'
After some research I found that some others also have this bug (phpWord - Cannot add PreserveText in Section)
EDIT
After trying around some more I found out, that the
Exception
only occurs when I have somemail merge fields
in my document. Once I removed them theException
does not come up anymore, but the converted
I thought about using another way to generate the PDF, but I could only find 4 ways:
PHPWord
and tcpdf
, but still not usable as images are missing, and most (not all!) of the stylesIs there a 5th way to generate the PDF? Or is there any solution to make the generated PDF documents look nice?
Drag and drop a Microsoft Word document (DOCX or DOC) to convert to PDF. Select a Microsoft Word document (DOCX or DOC) to convert to PDF. Drag and drop a Microsoft Word document (DOCX or DOC) to convert to PDF. Your file will be uploaded to Adobe cloud storage.
Drag and drop docx file if you have previously downloaded to your computer or mobile. If the docx file you want to open is stored in the cloud, click on Dropbox or Google Drive option, and import docx file from there. The docx file will automatically start to convert to PDF, as soon as you import it.
I used Gears/pdf to convert the docx file generated by phpword to PDF:
$success = Gears\Pdf::convert(
'file_path/file_name.docx',
'file_path/file_name.pdf');
You're trying to unlink the PDF file before saving it, and you have also to unlink the DOCX document, not the PDF one.
Try this.
$pdfWriter = \PhpOffice\PhpWord\IOFactory::createWriter($wordPdf , 'PDF');
$pdfWriter->save($filename.".pdf");
unlink($wordPdf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With