php – 使用 dompdf/dompdf 轉換繁體中文可支援的 PDF

參考

下載 dompdf/dompdf

composer require dompdf/dompdf

這邊提到,7.0以後要使用自訂的字型,必須要使用 dompdf/utils,目前已經獨立出來項目,不再包含在 dompdf 其中。

下載 dompdf/utils

前往 https://github.com/dompdf/utils.git 複製 load_font.php 到根目錄中,準備透過 comand line 執行。接著修改 load_font.php 自動載入類別的方式

// require_once "autoload.inc.php"; <-- 舊版的寫法,目前 load_forn.php 尚未修正
require_once "vendor/autoload.php"; <-- 使用 composer 的方法

下載中文字體 .ttf

參考有提到支援的格式,所以我們使用 .ttf 的中文字型。前往這裡可以找到繁體字體 https://briian.com/290/ ,例如我使用 王漢宗細黑體(wt011.ttf),字體名稱是 wt011.ttf。複製到自訂路徑,例如我們在根目錄新開一個路徑 /fonts。

安裝自訂的字體到 dompdf

Command line 運行

php load_font.php 'wt011'  fonts/wt011.ttf

說明:自訂名稱是 wt011、剛剛複製的字體路徑是 fonts/wt011.ttf。運行後就會在

vendor/dompdf/dompdf/lib/fonts/

出現自動產生的 wt011.ttf 和 wt011.ufm,並在 dompdf_font_family_cache.php 自動加入類似這樣的陣列

'wt011' => array(
  'normal' => $fontDir . '/wt011',
  'bold' => $fontDir . '/wt011',
  'italic' => $fontDir . '/wt011',
  'bold_italic' => $fontDir . '/wt011',
),

測試

<?php 
require_once 'vendor/autoload.php';

use Dompdf\Dompdf;

$dompdf = new Dompdf();
$dompdf->loadHtml('
    <style>
    .font-zh {
        font-family: "wt011"
    }
    </style>

    <p>English / <span class="font-zh">正體中文 123 Chinese</span>
');

$dompdf->setPaper('A4', 'landscape');
$dompdf->set_option('defaultFont', 'Courier'); // 預設字型(僅支援英文)
$dompdf->render();

// Attachment: 0 直接顯示, 1 強制下載
$dompdf->stream(null, ['Attachment' => 0]);

中文的部分,須要使用 CSS 的 font-family:中文字型 包圍才能正常顯示。沒有被包圍的部分使用英文字體,所以你會看到 HTML 的編碼會這樣

<style>
.font-zh {
    font-family: "wt011" /*我們自訂的字型名稱*/
}
</style>

<p>English / <span class="font-zh">正體中文 123 Chinese</span>

如果是下面這種寫法會出現亂碼

<p>English / 正體中文 123 Chinese</span>
<!-- 顯示 English / ???? 123 Chinese -->

 

Comments

  1. 照著做還是失敗了~

    ‘\’wt011\” => array(
    ‘normal’ => $fontDir . ‘/wt011’,
    ‘bold’ => $fontDir . ‘/wt011’,
    ‘italic’ => $fontDir . ‘/wt011’,
    ‘bold_italic’ => $fontDir . ‘/wt011’,
    ),

    自動加入這個,有確認過裡面有檔案。蠻奇怪的

    • 您好喔
      我今天開新專案測試這些步驟,目前沒有問題也能如範例正常顯示。
      您是在已存在的專案中執行嗎?或許先嘗試在空白的專案嘗試 : )
      感謝您的回報歐

  2. 今天試作成功了!謝謝!

發表迴響