dmikester1
dmikester1

Reputation: 1362

How to add an overlay/stamp to a PDF file in PHP?

Does anyone know how to programmatically add a overlay or stamp to a PDF file in PHP? So far the best I've come up with is calling the PDFTK library with the exec command. I'd prefer an actual PHP method if one exists.

Upvotes: 2

Views: 7877

Answers (1)

Andrea Falzetti
Andrea Falzetti

Reputation: 360

This is an old question but I hope to help someone looking for this answer.

I have successfully used FPDF (http://www.fpdf.org), a free PHP library.

I have cut this code from a big function, please pay attenction to the missing variables that I couldn't include here.

        $pdf = new FPDI();

        // Number of pages of the PDF
        $pagecount = $pdf->setSourceFile($source."/".$pdfList[$i]);

        // Loop the PDF's pages
        for($page_index=0; $page_index < $pagecount; $page_index++)
        {

            $tplidx = $pdf->importPage(($page_index+1), '/MediaBox');
            $pdf->addPage();
            $pdf->useTemplate($tplidx);

            // Do I need to stamp this page? This is a boolean flag calculated from the settings for each page.
            $stampThis = false;

            if($settings->pages == 'all') 
            {
                $stampThis = true;
            }
            else if($settings->pages == 'last')
            {
                if($pagecount == $page_index+1)
                {
                    $stampThis = true;
                }
            }
            else if($settings->pages == 'first')
            {
                if($page_index == 0)
                {
                    $stampThis = true;
                }
            }
            else if($settings->pages == 'odd')
            {
                if($page_index%2 == 0)
                {
                    $stampThis = true;
                }
            }
            else if($settings->pages == 'even')
            {
                if($page_index%2 != 0)
                {
                    $stampThis = true;
                }
            }           

            // Stamp the PDF, in case the flag is true
            if($stampThis)
            {
                // Custom stamp
                if(!empty($settings->imageURL)) {

                    $pdf->Image($settings->imageURL, 
                                $settings->stamp_coord_x,
                                $settings->stamp_coord_y);
                }

            } // stamp if end

        } // pages loop end

      $pdf->Output($destination.'/'.$pdfList[$i], 'F');

Upvotes: 5

Related Questions