Search code examples
pdfmergepdf-generationoverlaydompdf

DOMPDF - How to write text on top of another PDF file (PHP)


Say for example I wanted to load an already existing PDF file, and then transpose text on top of that PDF file and save it again as a new PDF file. Essentially merging the two, with one being transposed on the other.

I don't want the PDF acting as the background to become an image as to lose quality, so that everything retains it's original vectored format.

How would I go about doing this merge?

I don't want to use software, maybe there's a script that does this?


Solution

  • dompdf itself is unable to perform this kind of action. You would need to generate your PDF documents independently then use a third-party library to merge the two documents.

    Since you're using dompdf I'm guessing you might be looking for a PHP-based solution. Take a look at FPDI. After generating your PDF documents with dompdf you could then use FPDI to combine them.

    I think this will work, but I haven't tested it:

    <?php
    // generate pdf documents
    require_once('dompdf/autoload.inc.php');
    
    $dompdf = new Dompdf();
    $dompdf->loadHtml('<p>Hello</p>');
    $dompdf->render();
    file_put_contents('doc1.pdf', $dompdf->output());
    
    unset($dompdf);
    
    $dompdf = new Dompdf();
    $dompdf->loadHtml('<p>&nbsp;</p><p>Hello</p>');
    $dompdf->render();
    file_put_contents('doc2.pdf', $dompdf->output());
    
    
    // combine pdf documents
    require_once('fpdf.php');
    require_once('fpdi.php');
    
    // initiate FPDI
    $pdf = new FPDI('L');
    // add a page
    $pdf->AddPage();
    // set the source file to doc1.pdf and import a page
    $pdf->setSourceFile("doc1.pdf");
    $tplIdx = $pdf->importPage(1);
    // use the imported page and place it at point 10,10 with a width of 210 mm
    $pdf->useTemplate($tplIdx, 10, 10, 210);
    // set the source file to doc2.pdf and import a page
    $pdf->setSourceFile("doc2.pdf");
    $tplIdx = $pdf->importPage(1);
    // use the imported page and place it at point 100,10 with a width of 210 mm
    $pdf->useTemplate($tplIdx, 100, 10, 210);
    
    $pdf->Output();