2012-09-20 149 views
6

我在我的服務器上有一組pdf,它在下載時需要將文本附加到每個頁面上。我正在使用fpdf來嘗試打開文件,將文本追加到每個頁面,關閉文件並提供給瀏覽器。使用fpdf修改php中的現有pdf

$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); 

在分這只是嘗試把一些文字上的任何地方的PDF並保存它,但我得到的錯誤

FPDF error: You have to add a page first! 

如果我能得到它這樣做然後我需要它來追加文本的每一頁文檔,而不是僅僅1中,不知道如何做到這一點在閱讀下面的文檔

回答

9

嘗試

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

$pdf =& new FPDI(); 
$pdf->AddPage(); 

使用此頁面爲模板,然後

$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); 

讓我知道如果您有任何錯誤

+2

只爲我在$ x&$ y中使用空值而工作 '$ outPdf-> useTemplate($ outPdf-> importPage($ i),null,null,0,0,true);'。否則它將頁面切割爲A4。 – juanmf

5

既然你希望所有與文本的頁面,這樣做是把代碼在一個循環的一種方式。

像這樣:

// 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"); 
}