使用fpdf修改php中的现有pdf

Ste*_*ith 7 php pdf fpdf

我的服务器上有一组pdfs,下载时需要在每页上附加文字.我正在使用fpdf尝试打开文件,将文本附加到每个页面,关闭文件并提供给浏览器.

$pdf = new FPDI();

$pdf->setSourceFile($filename); 
// import page 1 
$tplIdx = $pdf->importPage(1); 
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page 
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); 

// now write some text above the imported page 
$pdf->SetFont('Arial', '', '13'); 
$pdf->SetTextColor(0,0,0);
//set position in pdf document
$pdf->SetXY(20, 20);
//first parameter defines the line height
$pdf->Write(0, 'gift code');
//force the browser to download the output
$pdf->Output('gift_coupon_generated.pdf', 'D');

header("location: ".$filename);
Run Code Online (Sandbox Code Playgroud)

在这一刻,这只是试图在pdf上的任何地方放置一些文本并保存它但我收到错误

FPDF error: You have to add a page first!
Run Code Online (Sandbox Code Playgroud)

如果我能做到这一点,那么我需要它将文本附加到文档中的每个页面而不仅仅是1,不知道如何阅读文档后如何做到这一点

GBD*_*GBD 11

试试以下

require_once('fpdf.php');
require_once('fpdi.php');

$pdf =& new FPDI();
$pdf->AddPage();
Run Code Online (Sandbox Code Playgroud)

然后使用此页面作为模板

$pdf->setSourceFile($filename); 
// import page 1 
$tplIdx = $pdf->importPage(1); 
//use the imported page and place it at point 0,0; calculate width and height
//automaticallay and ajust the page size to the size of the imported page 
$pdf->useTemplate($tplIdx, 0, 0, 0, 0, true); 
Run Code Online (Sandbox Code Playgroud)

如果您有任何错误,请告诉我

  • 我只在$ x和$ y中使用Nulls $ $ outPdf-> useTemplate($ outPdf-> importPage($ i),null,null,0,0,true);`.否则它将页面切换为A4. (2认同)

Flá*_*ira 6

由于您希望所有页面都包含文本,因此一种方法是将代码放在循环中.

像这样:

// Get total of the pages
$pages_count = $pdf->setSourceFile('your_file.pdf'); 

for($i = 1; $i <= $pages_count; $i++)
{
    $pdf->AddPage(); 

    $tplIdx = $pdf->importPage($i);

    $pdf->useTemplate($tplIdx, 0, 0); 


    $pdf->SetFont('Arial'); 
    $pdf->SetTextColor(255,0,0); 
    $pdf->SetXY(25, 25); 
    $pdf->Write(0, "This is just a simple text"); 
}
Run Code Online (Sandbox Code Playgroud)