[PHP] dompdf 使用記錄


# 安裝字體,解決中文亂碼
參考: https://blog.51cto.com/lampzxr/1916038
```
首先下載composer

curl -sS https://getcomposer.org/installer | php

下載dompdf包

php composer require dompdf/dompdf



下載load_font.php,此文件的功能是安裝中文字體

1.git clone https://github.com/dompdf/utils.git

2. 復制 load_font.php到 dompdf目錄中,與lib 和 src 目錄同級。



下載中文字體,推薦下載 Droid Sans Fallback 字體,也可用雅黑字體,【雅黑字體會導致導出文檔過大】

下載鏈接【http://www.17ziti.com/info/71250.html】



安裝字體,將字體傳到服務器目錄下,運行load_font.php

php load_font.php 'Droid' /data/DroidSansFallback.ttf。

運行后,若沒報錯,則在 vendor/dompdf/dompdf/lib/fonts/下生了 Droid.ttf,Droid.ufm 這兩個文件。



在PHP代碼中設置中文字體
<?php
require 'vendor/autoload.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$html=
<<<HTML
<html>
<head>
</head>
<body>
<!-- font-family:yahei; china-->
<div style="font-family:Droid; color: #f00;font-size: 14px"> 中文123 </div>
</body>
</html>
HTML;
$html = iconv('gb2312','utf-8',$html);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream();
注意 CSS 樣式中的 font-family 設置為 之前運行load_font.php中設置的字體名。
```


# 解決中文換行問題
修改文件: dompdf/dompdf/src/FrameReflower/Text.php
找到關鍵字: // split the text into words
```php
$words = preg_split('/([\s-]+)/u', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$wc = count($words);
```
修改為
```php
preg_match_all('/./u', $text, $array);
$words = $array[0];
$wc = count($words);
```


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM