Search code examples
phppdffpdf

Setting pdf path in FPDF


I am trying to set the pdf path from

$pageCount = $pdf->setSourceFile("doc.pdf");

(doc.pdf is present in the same directory as the php script)

to a pdf that is uploaded on some other server (http://www.example.com/xyz.pdf)

I tried this : $pageCount = $pdf->setSourceFile("http://www.example.com/xyz.pdf"); but it didn't work.

I am new to programming. Help would be appreciated


Solution

  • FPDI 1.x

    FPDI uses filesystem functions to navigate through the PDF document (e.g. fseek()). This requires that the stream that is opened is seekable which isn't the case if an http wrapper is used. You will need a local copy of the document or implement an individual stream wrapper that would allow you to read from e.g. a variable.

    FPDI 2.x

    In FPDI 2 you don't need to use a stream wrapper anymore but you can read from a variable by using an instance of the StreamReader class, which can be created and passed like this:

    // use a resource
    $fh = fopen('a/path/to/a.pdf', 'rb');
    $pdf->setSourceFile(new StreamReader($fh));
    // same as
    $pdf->setSourceFile($fh);
    // don't forget to call fclose($fh);
    
    // use a path
    $path = 'a/path/to/a.pdf';
    $pdf->setSourceFile(StreamReader::createByFile($path));
    // same as
    $pdf->setSourceFile($path);
    
    // use a string
    $pdfString = '%%PDF-1.4...';
    $pdf->setSourceFile(StreamReader::createByString($pdfString));