前端生成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

5.然后在 build 文件中可以找到vfs_fonts.js文件。

由於字體打包文件較大,建議examples/fonts中的.ttf文件只放置一個字體文件。

 


免責聲明!

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



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