1. 程式人生 > >前端生成pdf檔案之pdfmake.js

前端生成pdf檔案之pdfmake.js

 轉載:點選檢視原文

pdfmake.js是一個簡單的生成pdf檔案的外掛。

pdfmake.js     https://files.cnblogs.com/files/s313139232/pdfmake.min.js

程式碼也很簡單:

html檔案:

複製程式碼
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <title>my first export PDF</title>
    <script src="pdfmake.min.js"></script>
    <script src="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: 'FZYTK.TTF',
                    bold: 'FZYTK.TTF',
                    italics: 'FZYTK.TTF',
                    bolditalics: 'FZYTK.TTF',
                }
            };
            pdfMake.createPdf(dd).download();
        }
    </script>
</head>
<body>
<button onclick="down()">下載</button>
</body>
</html>
複製程式碼

程式碼中會引用兩個技術,pdfmake.min.js   vfs_fonts.js

  其中pdfmake.min.js是pdfmake的支援檔案,而vfs_fonts.js是字型檔案(.ttf)打包成的js檔案。

 

content中pdf的內容拼接:
  內容拼接類似於html+css,但是寫法為pdfmake外掛自帶,可以去pdfmake的github首頁介紹中檢視。

 

字型檔案(.ttf)打包可以通過pdfmake的github上的原始檔進行打包製作。

下面是兩種字型的vfs_fonts.js檔案:

方正姚體  https://files.cnblogs.com/files/s313139232/方正姚體vfs_fonts.js

Roboto-Itali   https://files.cnblogs.com/files/s313139232/Roboto-Italivfs_fonts.js

 

注意:中文的字型檔案較大,打包出來多數都在10M以上,推薦方正姚體等ttf檔案較小的字型進行打包。

打包教程:http://www.cnblogs.com/xrab/p/7210588.html

打包步驟:

1.在https://github.com/bpampuch/pdfmake下載pdfmake的原始檔

2.在目錄用 npm 安裝 gulp

npm install gulp --save-dev

3.安裝pdfmake依賴包

npm install

4.在cmd執行打包examples/fonts中的.ttf檔案的命令。

gulp buildFonts

如果執行上面的命令後,報 什麼  apply 什麼的  一個錯誤, 就 npm i gulp-cli -g  一下 ,應該就好了。

 

5.然後在 build 檔案中可以找到vfs_fonts.js檔案。

由於字型打包檔案較大,建議examples/fonts中的.ttf檔案只放置一個字型檔案。