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 some mail merge fields in my document. Once I removed them the Exception does not come up anymore, but the converted PDF files look horrible. All style information are gone and I can't use the result, so the need for an alternative stays.
I thought about using another way to generate the PDF, but I could only find 4 ways:
Using OpenOffice - Impossible as I cannot install any software on the Server. Also going the way mentioned here did not work either as my hoster (Strato) uses SunOS as the OS and this needs Linux
Using phpdocx - I do not have any budget to pay for it and the demo cannot create PDF
Using PHPLiveDocx - This works, but has the limitation of 250 documents per day and 20 per hour and I have to convert arround 300 documents at once, maybe even multiple times a day
Using PHP-Digital-Format-Convert - The output looks better than with PHPWord and tcpdf, but still not usable as images are missing, and most (not all!) of the styles
Is there a 5th way to generate the PDF? Or is there any solution to make the generated PDF documents look nice?
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);
I don't think I'm correct..
You save the document as HTML content
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'HTML');
After than you read the HTML file content and write the content as PDF file with the help of mPDF or tcPdf or fpdf.
Try this:
// get the name of the input PDF
$inputFile = "C:\\PHP\\Test1.docx";
// get the name of the output MS-WORD file
$outputFile = "C:\\PHP\\Test1.pdf";
try
{
$oLoader = new COM("easyPDF.Loader.8");
$oPrinter = $oLoader->LoadObject("easyPDF.Printer.8");
$oPrintJob = $oPrinter->PrintJob;
$oPrintJob->PrintOut ($inputFile, $outputFile);
print "Success";
}
catch(com_exception $e)
{
Print "error code".$e->getcode(). "\n";
print $e->getMessage();
}
Related
I have a series of base64 PDF Files that I would like to merge together. Currently I am using file_get_contents() and with PHPMailer can attach each of them separately.
$woFile = file_get_contents($url);
$invoiceFile = file_get_contents($invPDF64);
$tsFile = file_get_contents($tsPDF64);
...
$mail->AddStringAttachment($woFile, "1.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($invoiceFile, "2.pdf", "base64", "application/pdf");
$mail->AddStringAttachment($tsFile, "3.pdf", "base64", "application/pdf");
All the examples I've seen online such as FPDF require the file to be locally downloaded, at least from what I saw. Is there a way to append each of these PDF files into one, and then have that attached to the email?
Thanks in advance!
I'm not sure if you specifically need to merge the PDFs into one PDF, or if you just want one file. Here are options for both:
If you want to merge all PDFs into a single PDF file, then this is a duplicate question. You mention not wanting to have a local file, but this may be an unreasonable constraint (e.g., memory issues with large PDFs). Use temporary files as appropriate and clean up after yourself.
If you just want a single file, consider putting the files into a ZIP archive and sending that. You might also like the ZipStream library for this purpose. Here's some minimal code using the native library:
$attachmentArchiveFilename = tempnam('tmp', 'zip');
$zip = new ZipArchve();
# omitting error checking here; don't do it in production
$zip->open($attachmentArchiveFilename, ZipArchve::OVERWRITE);
$zip->addFromString('PDFs/first.pdf', $woFile);
$zip->addFromString('PDFs/second.pdf', $invoiceFile);
$zip->addFromString('PDFs/third.pdf', $tsFile);
$zip->close();
$mail->addAttachment($attachmentArchiveFilename, 'InvoicePDFs.zip');
# be sure to unlink/delete/remove your temporary file
unlink( $attachmentArchiveFilename );
I am working on a Symfony 1.4 project. I need to make a PDF download link for a (yet to be) generated voucher and I have to say, I am a bit confused. I already have the HTML/CSS for the voucher, I created the download button in the right view, but I don't know where to go from there.
Use Mpdf to create the pdf file
http://www.mpdf1.com/
+1 with wkhtmltopdf
I'd even recommand the snappy library.
If you use composer, you can even get the wkhtmltopdf binaries automatically
Having used wkhtmltopdf for a while I've moved off it as 1) it has some serious bugs and 2) ongoing development has slowed down. I moved over to PhantomJS which is proving to be much better in terms of functionality and effectiveness.
Once you've got something like wkhtmltopdf or PhantomJS on your machine you need to generate the HTML page and pass that along to it. I'll give you an example assuming you use PhantomJS.
Initially set what every request parameters you need to for the template.
$this->getRequest->setParamater([some parameter],[some value]);
Then call the function getPresentation() to generate the HTML from a template. This will return the resulting HTML for a specific module and action.
$html = sfContext::getInstance()->getController()->getPresentation([module],[action]);
You'll need to replace the relative CSS paths with a absolute CSS path in the HTML file. For example by running preg_replace.
$html_replaced = preg_replace('/"\/css/','"'.sfConfig('sf_web_dir').'/css',$html);
Now write the HTML page to file and convert to a PDF.
$fp = fopen('export.html','w+');
fwrite($fp,$html_replaced);
fclose($fp)
exec('/path/to/phantomjs/bin/phantomjs /path/to/phantomjs/examples/rasterize.js /path/to/export.html /path/to/export.pdf "A3");
Now send the PDF to the user:
$this->getResponse()->clearHttpHeaders();
$this->getResponse()->setHttpHeader('Content-Description','File Transfer');
$this->getResponse()->setHttpHeader('Cache-Control','public, must-revalidate, max-age=0');
$this->getResponse()->setHttpHeader('Pragma: public',true);
$this->getResponse()->setHttpHeader('Content-Transfer-Encoding','binary');
$this->getResponse()->setHttpHeader('Content-length',filesize('/path/to/export.pdf'));
$this->getResponse()->setContentType('application/pdf');
$this->getResponse()->setHttpHeader('Content-Disposition','attachment; filename=export.pdf');
$this->getResponse()->setContent(readfile('/path/to/export.pdf'));
$this->getResponse()->sendContent();
You do need to set the headers otherwise the browser does odd things. The filename for the generated HTML file and export should be unique to avoid the situation of two people generating PDF vouchers at the same time clashing. You can use something like sha1(time()) to add a randomised hash to a standard name e.g. 'export_'.sha1(time());
Use wkhtmltopdf, if possible. It is by far the best html2pdf converter a php coder can use.
And then do something like this (not tested, but should be pretty close):
public function executeGeneratePdf(sfWebRequest $request)
{
$this->getContext()->getResponse()->clearHttpHeaders();
$html = '*your html content*';
$pdf = new WKPDF();
$pdf->set_html($html);
$pdf->render();
$pdf->output(WKPDF::$PDF_EMBEDDED, 'whatever_name.pdf');
throw new sfStopException();
}
I can convert html page to pdf and send it via email with out any problem, but I am facing trouble with converting php file to pdf.
is it possible to convert php file to pdf using mpdf or do I need to use some other php class for this?
Thanks!
The option seems to be like, first convert the output of the php file to html file, save it and pass that file to mpdf.
Thought my solution may seem other way round but it worked well for me.
Or otherwise this Link
<?php
$file = '/home/user/Desktop/myfile.html';
$result = file_get_contents("url/of/ur/page");
echo $result; //view source now
file_put_contents($file, $result);
?>
now u can pass this file to mpdf. Realie sorie bt i havnt used mpdf till date. May be this solution works for you.
Also, other option is curl.
I'm trying to create a PDF file, under a Magento phtml file, this is my code :
$pdf = new Zend_Pdf();
$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
$page=$pdf->pages[0]; // this will get reference to the first page.
$style = new Zend_Pdf_Style();
$style->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$style->setFont($font,12);
$page->setStyle($style);
$page->drawText('example text here',100,($page->getHeight()-100));
$pdf->render();
$pdf->save('test.pdf','true');
My PDF file is created, but I can't open it with acrobat reader.
When I open it with a text editor and compare it with another simple pdf files, I noticed that in the first line was missing in my generated pdf file. it contains "%PDF-1.4"
How can I add this line programmatically with zend_pdf in my pdf file ?
Thanks for help.
According to the zend manual the second save parameter is only for updating files that already exist. In this case you are creating a new file so don't use that option.
$pdf->save('test.pdf');
PS. This answer is technically an RTM statement.
I need to find a certain key in a pdf file. As far as I know the only way to do that is to interpret a pdf as txt file. I want to do this in PHP without installing a addon/framework/etc.
Thanks
You can certainly open a PDF file as text. PDF file format is actually a collection of objects. There is a header in the first line that tells you the version. You would then go to the bottom to find the offset to the start of the xref table that tells where all the objects are located. The contents of individual objects in the file, like graphics, are often binary and compressed. The 1.7 specification can be found here.
I found this function, hope it helps.
http://community.livejournal.com/php/295413.html
You can't just open the file as it is a binary dump of objects used to create the PDF display, including encoding, fonts, text, images. I wrote an blog post explaining how text is stored at http://pdf.jpedal.org/java-pdf-blog/bid/27187/Understanding-the-PDF-file-format-text-streams
Thank you all for your help. I owe you this piece of code:
// Proceed if file exists
if(file_exists($sourcePath)){
$pdfFile = fopen($sourcePath,"rb");
$data = fread($pdfFile, filesize($sourcePath));
fclose($pdfFile);
// Check if file is encrypted or not
if(stripos($data,$searchFor)){ // $searchFor = "/Encrypt"
$counterEncrypted++;
}else{
$counterNotEncrpyted++;
}
}else{
$counterNotExisting++;
}