使用FPDI获取PDF内容的方式
FPDI内部使用了StreamReader类,它使用低级函数,如fread()或ftell()来与流交互。
流读取器类提供了通过特定输入类型创建实例的静态方法。它的构造函数允许你传递任何可查找的开放流资源:
//资源流获取
$fh = fopen(ROOT_PATH.'public/test.pdf', 'rb');
$pdf->setSourceFile(new StreamReader($fh));
//等同于 $pdf->setSourceFile($fh);
fclose($fh);
//文件路径获取
$path = ROOT_PATH.'public/test.pdf';
$pdf->setSourceFile(StreamReader::createByFile($path));
//等同于 $pdf->setSourceFile($path);
//使用字符串方式获取
$pdfString = '%%PDF-1.4...';
//$pdfString = file_get_contents(ROOT_PATH.'public/test.pdf');
$pdf->setSourceFile(StreamReader::createByString($pdfString));
例子
<?php
use \setasign\Fpdi\Fpdi;
require_once('fpdf/fpdf.php');
require_once('fpdi2/src/autoload.php');
$pdf = new Fpdi();
$pdf->AddPage();
//设置要导入的文件
$pdf->setSourceFile("Fantastic-Speaker.pdf");
//导入第一页
$tplIdx = $pdf->importPage(1);
//使用模板
$pdf->useImportedPage($tplIdx, 10, 10, 100);
$pdf->SetFont('Helvetica');
$pdf->SetTextColor(255, 0, 0);
$pdf->SetXY(30, 30);
$pdf->Write(0, 'This is just a simple text');
$pdf->Output();