1. 程式人生 > >php 轉換成pdf且下載,並帶懸浮圖片 Tcpdf

php 轉換成pdf且下載,並帶懸浮圖片 Tcpdf

專案需要把html頁面轉換成pdf,並帶圖片。

網上試了好幾種,發現tcpdf這個方法,很管用。

其中主要問題有html頁面帶css樣式展示出來,圖片也附帶,下載不顯示檔名等


檔案下載:TCPDF 《======下載 ,放到自己的專案裡。

原始碼:

require APP_ROOT_PATH."/system/utils/Tcpdf/tcpdf.php";
//例項化
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

// 設定文件資訊

$pdf->SetCreator('Victor');

$pdf->SetAuthor('Victor');

$pdf->SetTitle('xxx');

$pdf->SetSubject('');

$pdf->SetKeywords('');

//設定頁首資訊 引數分別是LOGO地址,LOGO大小,兩行標題,標題顏色,分割線顏色。。顏色是RGB

$pdf->SetHeaderData('', 30, '', '', array(0,0,0), array(0,0,0));

//設定頁尾資訊

$pdf->setFooterData(array(0,0,0), array(0,0,0));

// 設定頁首和頁尾字型

$pdf->setHeaderFont(Array('stsongstdlight', '', '12'));

$pdf->setFooterFont(Array('helvetica', '', '8'));

//設定預設等寬字型

$pdf->SetDefaultMonospacedFont('courier');

//設定間距

$pdf->SetMargins(15, 27, 15);

$pdf->SetHeaderMargin(5);

$pdf->SetFooterMargin(10);

//設定分頁

$pdf->SetAutoPageBreak(TRUE, 15);

//設定圖片比例

$pdf->setImageScale(1.25);

//將頁首頁尾的資訊輸出出來。

$pdf->AddPage();

//設定字型 - 正文標題的哦。B是加粗,15是大小

$pdf->SetFont('stsongstdlight', 'B', 15);

$pdf->Write(20, '', '', 0, 'C', true, 0, false, false, 0);

//設定字型 - 正文內容的哦。B是加粗,15是大小

$pdf->SetFont('stsongstdlight', '', 10);

ob_end_clean();

$pdf->writeHTMLCell(0, 0, '', '', 輸出模板(我用的TP,所以用的fetch), 0, 1, 0, true, '', true);

//40:x軸,95:y軸,40:圖片大小
$pdf->Image('/xxx/xxx/xxx.png', 40, 95, 40, '', '', '', '', false, 100); 
//輸出PDF。第二個引數預設是I,是瀏覽器預覽。D是下載
$name="xxx.pdf";
$pdf->Output($name,'D');  
如果下載發現檔名不顯示,去tcpdf.php中的方法Output的7565行左右,把這段遮蔽了:

if ($dest[0] != 'F') {
	$name = preg_replace('/[\s]+/', '_', $name);
	$name = preg_replace('/[^a-zA-Z0-9_\.-]/', '', $name);
}
就可以顯示了