使用jsPDF生成PDF文件

使用兩個開源項目,這是他們的地址

jsPDF:https://github.com/MrRio/jsPDF
jsPDF-AutoTable:https://github.com/simonbengtsson/jsPDF-AutoTable

項目引入,我使用的版本是jsPDF(1.5.3)、jsPDF-AutoTable(3.2.4)

<script src="libs/jspdf.debug.js"></script>
<script src="libs/jspdf.plugin.autotable.js"></script>

js設置

//初始化
const doc = new jsPDF();
//設置生成的內容(html:表格的ID)
doc.autoTable({html: '#table'});
//導出
doc.save('table.pdf');

運行

第一次生成的效果,中文亂碼

問題

jsPDF默認是不支持中文顯示,所以顯示的都是一些亂碼。我翻閱了很多的一些資料。能找到一些有用的信息。

官網有那麼一段說明。

The 14 standard fonts in PDF are limited to the ASCII-codepage. If you want to use UTF-8 you have to to integrate a custom font, which provides the needed glyphs. jsPDF supports .ttf-files. So if you want to have for example chinese text in your pdf, your font has to have the necessary chinese glyphs. So check if your font supports the wanted glyphs or else it will show a blank space instead of the text.

To add the font to jsPDF use our fontconverter in /fontconverter/fontconverter.html . The fontconverter will create a js-file with the content of the provided ttf-file as base64 encoded string and additional code for jsPDF. You just have to add this generated js-File to your project. You are then ready to go to use setFont-method in your code and write your UTF-8 encoded text.

用翻譯軟件翻譯一下,這裏不確保翻譯的正確性,大致上看懂就行。

PDF中的14種標準字體僅限於ASCII代碼頁。如果要使用UTF-8,則必須集成自定義字體,該字體提供所需的字形。jsPDF支持.ttf文件。因此,如果您希望在pdf中使用中文文本,則您的字體必須具有必要的中文字形。因此,請檢查您的字體是否支持所需的字形,否則它將顯示空白而不是文本。

要將字體添加到jsPDF,請在/fontconverter/fontconverter.html中使用我們的fontconverter。fontconverter將創建一個js文件,其中包含提供的ttf文件的內容作爲base64編碼的字符串和jsPDF的附加代碼。您只需將生成的js-File添加到項目中即可。然後,您就可以在代碼中使用setFont-method並編寫UTF-8編碼文本。

這段話能得到幾個信息:

  • 如果要使用中文,必須要集成自定義字體(必須是.ttf後綴的文件。我之前一直用win10自帶的字體,結果一直有異常。win10的有些字體後綴是.ttc)
  • 使用fontconverter生成字體的js文件,並引入到項目中(clone下jsPDF的項目,項目下/fontconverter/fontconverter.html能把字體文件轉成js文件)
  • 設置setFont

現在變成了這樣,這裏我使用的是微軟雅黑字體,你們自行百度下載

<script src="libs/jspdf.debug.js"></script>
<script src="libs/jspdf.plugin.autotable.js"></script>
//重點引入這個自定義字體
<script src="msyh-normal.js"></script>
//初始化
const doc = new jsPDF();
//設置字體
doc.setFont('msyh');
//設置內容
doc.autoTable({html: '#table'});
//導出
doc.save('table.pdf');

第二次運行

第二次生成的效果,和第一次無差別
這和第一次的效果沒任何區別。我在別人的博客中找到了解決的方法,下面是地址

https://www.hangge.com/blog/cache/detail_2213.html

重點看這裏
引用代碼
根據他的提示我修改了js

doc.autoTable({
    html: '#table',
    styles: {
        font: "msyh"
    }
});

第三次運行

第三次生成的效果,標題還存在亂碼
可以看到表格的區域已經解決了亂碼的問題,但是標題欄還是一樣還是亂碼。這裏我找了另一個人的博客,下面是地址

https://juejin.im/post/5c1bb46a5188252dcb310f9f

重點看這裏
引用別人分析的標題欄亂碼的問題
他的想法是修改源碼以達到效果,但是我並沒有這樣做,我去了jsPDF-AutoTable官網找了有沒有相關可以設置的接口,還真讓我找到了,在樣式設置一欄中,找到了可以設置fontStyle
在這裏插入圖片描述
根據上面的提示在js中加入以下代碼

doc.autoTable({
    html: '#table',
    styles: {
        font: "msyh",
        //這裏設置字體樣式
        fontStyle: "normal"
    }
});

最終效果

解決中文亂碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章