Search code examples
phppdfpdf-generationtcpdffpdf

Combining PDFs with PHP from Encoded PDFs - Error: "Template does not exist!"


I am building a simple web service that needs to join two PDFs into one PDF file. I can pass both PDFs as text(base encode 64) with a POST to the service and the service needs to spit out the combined PDF as encoded text, The client will then re-encode and make the PDF.

I found this question here which got me started: Can TCPDF / FPDI accept PDF as string?

I found some sample code and the multiple libraries:

Here is an encoded PDF single page simple.(Post data) http://pastebin.com/zLXmCNJt

Here's my code:

<?php

require_once($_SERVER['DOCUMENT_ROOT'].'/FPDF/tcpdf/tcpdf.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/FPDF/tcpdf/tcpdi.php');


class ConcatPdf extends TCPDI 
{
    public $files = array();

    public function setFiles($files)
    {
        $this->files = $files;
    }

    public function concat()
    {
        foreach($this->files AS $file) {
            //$pageCount = $this->setSourceFile($file);
            $pageCount = $this->setSourceData($file);//i modified this
            for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
                 $tplIdx = $this->ImportPage($pageNo);
                 $s = $this->getTemplatesize($tplIdx);
                 $this->AddPage($s['w'] > $s['h'] ? 'L' : 'P', array($s['w'], $s['h']));
                 $this->useTemplate($tplIdx); //error here
            }
        }
    }
}


$pdf641 = $_POST['pdf1'];
$pdf642 = $_POST['pdf2'];

$pdf = new ConcatPdf();
$pdf->setFiles(array(base64_decode($pdf641), base64_decode($pdf642) ));
$pdf->concat(); //!!error here!!
echo base64_encode($pdf->Output('concat.pdf', 'S'));

?>

Here is the error log from the server: http://pastebin.com/q2vzZfft

What's going wrong here? How do I fix this?


Solution

  • Note: This issue has been resolved via the Github issue tracker for TCPDI; I'm answering here as well for the benefit of anyone who comes across this SO question.

    As per the TCPDI installation instructions, TCPDI is not currently compatible with the version of FPDF_TPL bundled with recent versions of FPDF.

    Attempting to use the bundled version of FPDF_TPL can result in the "template does not exist" error; using the standalone version (FPDF_TPL 1.2.3) should resolve this issue. If you continue to get error messages when using FPDF_TPL 1.2.3, please log a Github issue against either TCPDI or TCPDI_PARSER (as appropriate), and provide a sample PDF which triggers your issue.