備忘錄_20160105(定位) 修改 回首頁

程式 2024-03-22 23:18:42 1711120722 100
php 產生可用 utf-8 文字的 pdf

php 產生可用 utf-8 文字的 pdf

以 fpdf 為骨幹,以 tfpdf 為實際使用。
可以自訂紙張大小,決定直印、橫印!
可以有頁碼,頁數。
可以正確輸出 utf-8 的中文字。(使用 *.ttf)
使用純粹的 php 語言。

注意,把中文字型 *.ttf 放在 [path to tFPDF]/font/unifont/ 裡面,
一呼叫 $pdf->AddFont 時,會自動產生許多附加檔案,字型別名 就被鎖定了。
若把附加檔案刪除,重新呼叫 $pdf->AddFont 時,可以有不同別名。


觀看結果

<?php
  
  require('tfpdf/tfpdf.php');

  class newPDF extends tFPDF
  {
    function Footer()
    {
        // Go to 1.5 cm from bottom
        $this->SetY(-15);
        // Select Arial italic 8
        $this->SetFont('Arial', 'I', 8);
        // Print centered page number
        $this->Write(8,'Page '.$this->PageNo() . '/{nb}');
        //$this->Cell(0, 10, 'Page '.$this->PageNo() . '/{nb}', 0, 0, 'C');
    }
  }

  $pdf = new newPDF('Portrait', 'mm', array(130,130));
  $pdf->AliasNbPages();
  
  $pdf->AddFont('中文','','NotoSansTC-Regular.ttf',true);
  
  $pdf->AddPage();
  $pdf->SetFont('中文','',14);
  $txt = '您好,許蓋功氷!hello, world!';
  $pdf->Write(8,$txt);

  $pdf->AddPage();
  $pdf->SetFont('中文','',16);
  $txt = '這是第二頁囉!';
  $pdf->Write(8,$txt);
  
  $pdf->Output();
  
?>