Generate PDF from HTML/CSS/PHP in Symfony 1.4 - php

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();
}

Related

Force download html to pdf using php

I try to make force download html-file to pdf and use the code below
<?php
header('Content-disposition: attachment; filename=\''. basename($file) .'\'.pdf');
header("Content-type: application/pdf");
echo file_get_contents($_SERVER['DOCUMENT_ROOT'].'/index-1.html');
?>
I get some file with .pdf extention but when I try to open it, i get an error `not PDF or corrupted'. What's wrong and how to make it work?
Telling the browser that some data is a PDF will not magically transform the data into a PDF.
You'll need to do that yourself, e.g. using the PHP PDF library or Prince.
You have to create a properly PDF file. You can do this using some PHP classes like HTML2PDF or wkhtmltopdf.
You can't just put html in a pet file and expect it to work you need to use something like dompdf to convert html to a pdf file: https://code.google.com/p/dompdf/
For even better results and support for floats I would use the following library. I got extremely good results with it. The reason why this one is working so well is because they use the WebKit browser rendering engine to render the html before converting it to pdf giving you almost 1 on 1 results when comparing it to the browser.
https://code.google.com/p/wkhtmltopdf/

Save PDF file using PHPPdf

I'm using PHPPdf library to generate PDFs on the fly in my Symfony2 app. However I could not find a way to dump/write/save PDF raw data to a file.
From Symfony controller I tried this:
$content = $this->render('AcmeBundle:PDF:template.xml.twig');
file_put_contents('documents/123.pdf', $content);
but as it seems I get rendered HTML and not PDF binary data. When I add #Pdf annotation all output is being routed to PDF document and into browser but I need to save raw data instead for later retrieval.
I looked into FacadeBuilder but coudln't find anything useful.
Any help would be much appreciated...
Take a look at this, I think you should use $content = $facade->render($xml); like in the example action.

Webpage convert to PDF button

I have a website now and I want to create a button on it to convert this page to PDF.
Is there any code to make this happen? I cannot find it on the internet.
So I want to have a button and when I press on it it converts the page to a .PDF file.
I do not want to use a third party website to generate the PDF's. I want to use it for internal purposes to generate files with PHP. So I need the code what can make a PDF for each page.
I use wkhtmltopdf - works very well - http://code.google.com/p/wkhtmltopdf/ there is a PHP wrapper
Updated based on comments below on usage :
How to use the integration class:
require_once('wkhtmltopdf/wkhtmltopdf.php'); // Ensure this path is correct !
$html = file_get_contents("http://www.google.com");
$pdf = new WKPDF();
$pdf->set_html($html);
$pdf->render();
$pdf->output(WKPDF::$PDF_EMBEDDED,'sample.pdf');
Use FPDF. It's a well-respected PDF-generating library for PHP that is written in pure PHP (so installing it should be dead simple for you).
Try this:
http://www.macronimous.com/resources/Converting_HTML2PDF_using_PHP.asp
It will convert HTML to a PDF using FPDF and HTML2PDF class.
Also found this:
http://www.phpclasses.org/package/3168-PHP-Generate-PDF-documents-from-HTML-pages.html

Open a pdf with PHP and place text in it

I have a PDF which has an image on it (a logo)
I want to open it with PHP and write some text over it and save it back to the file system.
I've done this with the Zend framework before but this project is using code igniter so I need either a standalone lib or a code igniter plugin.
thanks
Zend_Pdf is a standalone lib.
Zend Framework is deliberately designed with a Use-At-Will architecture, so you can use most components with no (or very little) dependencies on other components in the framework.
To use Zend_PDF in Code Igniter, place the Zend/Pdf folder into your CI project's include path, so it is accessible. Then include it with
// Load Zend_Pdf class
require_once('Zend/Pdf.php');
See this (general) tutorial:
http://devzone.zend.com/article/2525
In my esperience, the first question you should ask is: where the original pdf come from?
Do you want to create the pdf from php, as a template, and then insert the text on it in a second time?
Or you create the pdf in other ways, and then fulfill it via php?
In the first case, go with zend pdf, and write down your class to handle it.
In the second case, you may want to take a look to pdftk, that allow you to merge an fdf file with a PDF file.
Here an example with a forms (and the createFDF.php file), but the behavior can be applyed in many other ways...
Its quite simple:
<?php
require_once('createFDF.php');
$data = array(
'field_1' => 'Text 1',
'Field_2' => 'Text 2
);
$FDF_file = 'myfile.fdf';
$PDF_file = 'mypdf.pdf';
$PDF_source = 'your-pdf-original-file.pdf';
$fdf_data = createFDF($PDF_source, $data);
$fh = fopen($FDF_file, 'w');
fwrite($fh, $fdf_data);
fclose($fh);
?>
<h2>File FDF created.</h2>
<?php
passthru("pdftk $PDF_source fill_form $FDF_file output $PDF_file flatten");
?>
<h2>Pdf merged.</h2>
but, you will need to create the original pdf file with forms within by hand (or, as far as i know, there is no tools to create it via php)
You can try to set the following header:
<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');
// The PDF source is in original.pdf
readfile(base_url($pdf->URL));
?>

Add 1 Page to each PDF in folder

I have a folder with 100s of PDF versions of PPT presentations. I also have a one page PDF file that I want to add to the beginning of each PDF file. Is there a way I can do this with PHP? Could I maybe use the Zend Framework?
It certainly can be done by Zend_Framework!
$pdf = Zend_Pdf::load($fileName);
$frontPdf = Zend_Pdf::load('/path/to/template.pdf');
$frontPage = $frontPdf->pages[0];
//prepend our template front page to PDF
array_unshift($pdf->pages, $frontPage);
//update original document
$pdf->save($fileName, true);
I haven't tested the code here but we have an application working on the same principle.
Check the documentation for pages within Zend_Pdf if you have any problems.

Categories