Insert a new page to an existing PDF dynamically with PHP

This is a quick solution I found for one of the issues I got while developing a web portal which allows PDF downloads. However these PDF documents had to be preceded with a dynamically generated page which should be inserted at the time of downloading the PDF.

After few hours of trying I came up with this solution which worked well in my case. Just thought of sharing my solution for someone who might have the same issue.

This can be easily done using mPDF. Please download mPDF and follow the instructions on the mPDF documentation to get it working with your PHP application. I use Yii for my projects and mPDF is available for Yii as an extension (yii-pdf) which you can find here.

mPDF allows importing pages from another PDF into the one you create on the fly. We use this feature for importing all the pages of the source PDF file and create a new PDF inserting a dynamically generated page at start.

A plain PHP example:

include("../mpdf.php");

$pdf = new mPDF();
$pdf->AddPage();
$pdf->WriteHTML('Some HTML content for the first page');

$pdf->SetImportUse();
$pageCount = $pdf->SetSourceFile($model->getFile());
for($i = 1; $i <= $pageCount; $i++) {
$pdf->AddPage();
$tpl = $pdf->ImportPage($i);
$pdf->UseTemplate($tpl);
}

// output as a file
$pdf->Output();
exit;

Same block of code in Yii compatible way. Please note that you need to setup yii-pdf extension as described in Yii extension page for yii-pdf.

$pdf = Yii::app()->mpdf->mpdf();
$pdf->AddPage();

$pdf->WriteHTML('Some HTML content for the first page');

$pdf->SetImportUse();
$pageCount = $pdf->SetSourceFile($model->getFile());
for($i = 1; $i <= $pageCount; $i++) {
$pdf->AddPage();
$tpl = $pdf->ImportPage($i);
$pdf->UseTemplate($tpl);
}

// output as a file
$pdf->Output();
Yii::app()->end();


NOTE: This might not be the best way to do this. If you know a better method please leave a comment and let me know how did you do that :)

Saranga
Saranga A web developer and highly passionate about research and development of web technologies around PHP, HTML, JavaScript and CSS.
comments powered by Disqus