想在網頁上實作「匯出 PDF」,jsPDF 的推薦度很高,可惜預設不支援中文。最後找到 pdfmake,這個問題迎刃而解。可以先到 https://pdfmake.org/playground.html 看看效果。不過實作時會發現,插入圖片比想像中麻煩一些。
• pdfmake 的基本用法
• 中文顯示的解法
• 用圖片路徑插入圖片
引入兩個檔案:
<script src="build/pdfmake.min.js"></script> <script src="build/vfs_fonts.js"></script>
接著宣告一個 document-definition 物件(這是 pdfmake 的術語),最簡單的形式就是至少帶一個 content 屬性:
<script type="text/javascript">
// 建立 document-definition
var dd = {
content: [
'One paragraph',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
]
};
// 匯出 PDF
pdfMake.createPdf(dd).download();
</script>
執行後就會看到下載提示。完整功能請參考 pdfmake 專案文件。
pdfmake 需要把字型檔打包進 vfs_fonts.js 才能輸出非拉丁字元,步驟如下。
1. 產生新的 vfs_fonts.js
下載 pdfmake 專案,把字型檔(例如微軟雅黑.ttf)放進 examples/fonts 目錄,再執行 grunt dump_dir 重新產生 vfs_fonts.js。這個命令會把 fonts 目錄底下的檔案全部打包,所以請不要把用不到的檔案丟進去。若沒用過 grunt,建議先花點時間了解這個建置工具。
2. 宣告字型
pdfMake.fonts = {
Roboto: {
normal: 'Roboto-Regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'Roboto-Italic.ttf',
bolditalics: 'Roboto-Italic.ttf'
},
微軟雅黑: {
normal: '微軟雅黑.ttf',
bold: '微軟雅黑.ttf',
italics: '微軟雅黑.ttf',
bolditalics: '微軟雅黑.ttf'
}
};
3. 在文件中指定預設字型
var dd = {
content: [
'中英文測試',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
],
defaultStyle: { font: '微軟雅黑' }
};
完整可執行範例:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>my first export PDF</title>
<script src="build/pdfmake.min.js"></script>
<script src="build/vfs_fonts.js"></script>
<script>
function down() {
var dd = {
content: [
'中英文測試',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
],
defaultStyle: { font: '微軟雅黑' }
};
pdfMake.fonts = {
Roboto: {
normal: 'Roboto-Regular.ttf',
bold: 'Roboto-Medium.ttf',
italics: 'Roboto-Italic.ttf',
bolditalics: 'Roboto-Italic.ttf'
},
微軟雅黑: {
normal: '微軟雅黑.ttf',
bold: '微軟雅黑.ttf',
italics: '微軟雅黑.ttf',
bolditalics: '微軟雅黑.ttf'
}
};
pdfMake.createPdf(dd).download();
}
</script>
</head>
<body>
<button onclick="down()">下載</button>
</body>
</html>
jsPDF 要求先把圖片轉成 Data URL;pdfmake 看起來允許直接指定路徑,但前提是節點伺服器為 node.js,或把圖片也塞進 vfs_fonts.js。實務上還是得先轉成 Data URL。
為了解決這件事,我寫了一個 ImageDataURL 函式,可接受多個圖片路徑。全部載入完成後會觸發 ImageDataURL.oncomplete,在回呼中從 this.imgdata 取出各圖的 Data URL,依 pdfmake 的格式組裝即可。原理是透過 HTML5 的 canvas 把圖片畫上去,再用 toDataURL 取出資料,因此要注意瀏覽器相容性。
以下範例依序寫入 sampleImage.jpg、samplage.jpg、sampleImage.jpg,其中 samplage.jpg 故意不存在,pdfmake 會直接略過。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>my second export PDF</title>
<script src="build/pdfmake.min.js"></script>
<script src="build/vfs_fonts.js"></script>
<script>
function down() {
var x = new ImageDataURL(["sampleImage.jpg", "samplage.jpg", "sampleImage.jpg"]);
x.oncomplete = function () {
var imgs = new Array();
console.log("complete");
for (key in this.imgdata) {
if (this.imgdata[key] == this.emptyobj) continue; // 略過不存在的圖片
imgs.push({ image: this.imgdata[key] }); // pdfmake 的圖片格式
}
var dd = { content: ['Title', imgs] };
pdfMake.createPdf(dd).download();
};
}
</script>
</head>
<body>
<button onclick="down()">下載</button>
<script>
// urls 可以是字串或字串陣列
function ImageDataURL(urls) {
this.completenum = 0;
this.totalnum = 0;
this.imgdata = new Array();
this.emptyobj = new Object();
this.oncomplete = function () {};
this.getDataURL = function (url, index) {
var c = document.createElement("canvas");
var cxt = c.getContext("2d");
var img = new Image();
var p = this;
img.src = url;
img.onload = function () {
var i;
var maxwidth = 500;
var scale = 1.0;
if (img.width > maxwidth) {
scale = maxwidth / img.width;
c.width = maxwidth;
c.height = Math.floor(img.height * scale);
} else {
c.width = img.width;
c.height = img.height;
}
cxt.drawImage(img, 0, 0, c.width, c.height);
p.imgdata[index] = c.toDataURL('image/jpeg');
for (i = 0; i < p.totalnum; ++i) {
if (p.imgdata[i] == null) break;
}
if (i == p.totalnum) p.oncomplete();
};
img.onerror = function () {
p.imgdata[index] = p.emptyobj;
for (i = 0; i < p.totalnum; ++i) {
if (p.imgdata[i] == null) break;
}
if (i == p.totalnum) p.oncomplete();
};
};
if (urls instanceof Array) {
this.totalnum = urls.length;
this.imgdata = new Array(this.totalnum);
for (key in urls) {
this.getDataURL(urls[key], key);
}
} else {
this.imgdata = new Array(1);
this.totalnum = 1;
this.getDataURL(urls, 0);
}
}
</script>
</body>
</html>
canvas 取圖會受同源政策限制:若圖片來自考外網域且伺服器未回傳適當的 CORS 標頭,toDataURL 會丟出安全性錯誤。這類圖片需要由後端代理抓取,或請對方開放跨來源存取。
另外,字型檔直接內嵌會讓 vfs_fonts.js 體積可觀(中文字型動輒數 MB),首屏載入成本要納入評估;條件允許時,把字型檔獨立拆分、只在需要匯出時才載入會更理想。