Php: Import pdf in Tcpdf
Problem
I want to import existing PDF files into this Pdf I'm generating.
Environment
- tecnickcom/tcpdf: 6.2.*
- setasign/fpdi-tcpdf: 1.6.*
Solution
Use FPDI library besides TCPDF. So composer.json
has to contain something like this:
"require": { ... "setasign/fpdi-tcpdf": "1.6.*", "tecnickcom/tcpdf": "6.2.*", ... },
Make sure the PDF is of max version PDF-1.4. Or else (PDF-1.5) you need the commercial FPDI PDF-Parser addon.
The alternative is to convert the PDF to Acrobat PDF version 1.4 manually using this ghostscript command (from: http://superuser.com/questions/184288/how-to-convert-a-pdf-document-to-an-older-version):
$ gs -sDEVICE=pdfwrite -dNOPAUSE -dBATCH -dSAFER \ -dCompatibilityLevel=1.4 -sOutputFile=output.pdf input.pdf
Instead of using TCPDF directly, you now need to use the FPDI() class, which uses TCPDF indirectly (from: https://manuals.setasign.com/fpdi-manual/installation/#index-2-2):
- "1.2.2 Usage with TCPDF
FPDI can also be used with TCPDF. To manage this we use an intermediate class that is created at runtime and will extend FPDF or TCPDF depending on which class is available (fpdi_bridge.php). If you'd installed FPDI and TCPDF individually via Composer you will need to trigger the autoloader of Composer before you use FPDI. This ensures that TCPDF will get loaded and FPDI will map the intermediate class in a proper way"
class_exists('TCPDF', true); // trigger Composers autoloader to load the TCPDF class $pdf = new FPDI();
Use the PHP-code below to import multiple existing PDF files into the FPDI/TCPDF object ($pdf):
function renderAttachments() { $files = array('file1.pdf', 'file2.pdf'); foreach ($files as $file) { $numPages = $this->pdf->setSourceFile($file); for ($i = 1; $i <= $numPages; $i++) { $tplIdx = $pdf->importPage($i); $pdf->SetPrintHeader(false); $pdf->SetPrintFooter(false); $pdf->AddPage(); $pdf->useTemplate( $tplIdx, $x = null, $y = null, $w = 0, $h = 0, $adjustPageSize = true ); } } }
Journal
20151208
I tried to import an existing PDF file using the IMPORT_TCPDF class like this:
$pdf = new TCPDF_IMPORT(); $pdf->importPDF('file1.pdf');
But this returns me a php array in the browser:
- Array ( [0] => Array ( [xref] => Array ( [1_0] => 308574 [2_0] => 354802 [3_0] => 308078 [4_0] => 295490 [5_0] => 15 [6_0] => 2499 [7_0] => 308640 [8_0] => 308701 [9_0] => 311898 [10_0] => 323281 [11_0] => 334766 [12_0] => 324886 [13_0] => 343893 [14_0] => 311930 [15_0] => 311974 [16_0] => 312019 [17_0] => 312049 [18_0] => 312101 [19_0] => 295705 [20_0] => 2519 [21_0] => 4368 [22_0] => 312144 [23_0] => 325778 [24_0] => 347576 [25_0] => 321403 [26_0] => 328804 [27_0] => 312215 [28_0] => 312245 [29_0] => 312299 [30_0]
because of the debug print_r
in tcpdf_import.php
:
print_r($data); // DEBUG
Looks like the comment in the source code "!!! THIS CLASS IS UNDER DEVELOPMENT !!!" is right.