TCPDF and FPDI with multiple pages

前端 未结 4 422
情话喂你
情话喂你 2020-12-09 23:45

This looks like the simplest thing but I can\'t get it to work.

I need to add text to the first page of a multi-page pdf (could be any number of pages)

Using

4条回答
  •  难免孤独
    2020-12-10 00:41

    Solved my problem...

    // Original file with multiple pages 
    $fullPathToFile = 'full/path/to/file.pdf';
    
    class PDF extends FPDI {
    
        var $_tplIdx;
    
        function Header() {
    
            global $fullPathToFile;
    
            if (is_null($this->_tplIdx)) {
    
                // THIS IS WHERE YOU GET THE NUMBER OF PAGES
                $this->numPages = $this->setSourceFile($fullPathToFile);
                $this->_tplIdx = $this->importPage(1);
    
            }
            $this->useTemplate($this->_tplIdx);
    
        }
    
        function Footer() {}
    
    }
    
    // initiate PDF
    $pdf = new PDF();
    $pdf->setFontSubsetting(true);
    
    
    // add a page
    $pdf->AddPage();
    
    // The new content
    $pdf->SetFont("helvetica", "B", 14);
    $pdf->Text(10,10,'Some text here');
    
    // THIS PUTS THE REMAINDER OF THE PAGES IN
    if($pdf->numPages>1) {
        for($i=2;$i<=$pdf->numPages;$i++) {
            $pdf->endPage();
            $pdf->_tplIdx = $pdf->importPage($i);
            $pdf->AddPage();
        }
    }
    
    // Output the file as forced download
    $pdf->Output('theNewFile.pdf', 'D');
    

    You get the number of pages by adding the first part of this line

    $this->numPages = $this->setSourceFile($fullPathToFile);
    

    And see the second last block of code - the for loop adds the remainder of the pages.

    Don't know if this is how it should be done? I read in a few places that it wasn't even possible to achieve this, also the code is not supplied in the docs. However, this works, hope it helps someone.

提交回复
热议问题