公司项目在需要将页面的文本导出成DPF,和支持打印时,一直没有做过这样的功能,花了一点时间将其做了出来,并且本着开源的思想和技术分享的目的,将自己的编码经验分享给大家,希望对大家有用。
现在是有一个文本在我的div的代码块中。
1 <h3 id="tatemplatecode"> </h3> 3 <div class="publishinfo"> 4 <span id="publisher"></span><span id="publishtime"></span> 5 </div> 6 <div id="templatecontent"> 7 </div>
我需要将id为tatemplatecode的东西和id为publisher和id=templatecontent的内容获得并导出pdf中。所有了所有的js插件,我选择使用了pdfmake.js。具体他的优先我就不说了,大家可以去看他的github地址,查看他的源码和简介。github
这里我是将自己的开发经验结合源码分析写下来。
导出pdf的解决代码:
1 $("#export").click(function(){ 2 var tatemplatecode = $("#tatemplatecode").html(); 3 var publishtime = $("#publishtime").html(); 4 var templatecontent =$("#templatecontent").html().replace(/ /g," ").replace(/<p>/g,"").replace(/<\/p>/g,"").split("<br>"); 5 var dd = { 6 content: [ 7 tatemplatecode, 8 publishtime, 9 templatecontent 10 ], 11 defaultStyle: { 12 font: '微软雅黑' 13 } 14 }; 15 pdfMake.createPdf(dd).download("三方协议"); 16 });
这里我们只使用了build中的pdfmake.js和vfs_fronts.js,pdfmake.js是我们的主要js插件,vfs_fronts.js里面使我们需要支持的字体,如果你需要支持什么字体比如‘微软雅黑’,就从网上下一个,打包到vfs_fronts.js中。
支持打印的解决代码:
1 $("#print").click(function(){ 2 debugger; 3 var tatemplatecode = $("#tatemplatecode").html(); 4 var publishtime = $("#publishtime").html(); 5 var templatecontent =$("#templatecontent").html().replace(/ /g," ").replace(/<p>/g,"").replace(/<\/p>/g,"").split("<br>"); 6 var dd = { 7 content: [ 8 tatemplatecode, 9 publishtime, 10 templatecontent 11 ], 12 defaultStyle: { 13 font: '微软雅黑' 14 } 15 }; 16 pdfMake.createPdf(dd).print(); 17 });
我们现在已经解决掉导出和打印的功能,但是为了我们进一步了解pdfmake,我们就这二个功能简单分析一下源码。
pdfmake的createPdf函数
1 module.exports = { 2 createPdf: function (docDefinition) { 3 if (!canCreatePdf()) { 4 throw 'Your browser does not provide the level of support needed'; 5 } 6 return new Document(docDefinition, global.pdfMake.tableLayouts, global.pdfMake.fonts, global.pdfMake.vfs); 7 } 8 };
查看pdfmake.js的download函数。
1 Document.prototype.download = function (defaultFileName, cb, options) { 2 if (typeof defaultFileName === 'function') { 3 cb = defaultFileName; 4 defaultFileName = null; 5 } 6 7 defaultFileName = defaultFileName || 'file.pdf'; 8 this.getBlob(function (result) { 9 saveAs(result, defaultFileName); 10 11 if (typeof cb === 'function') { 12 cb(); 13 } 14 }, options); 15 };
Document是pdfmake.js的函数。现在就是通过prototype给document的原型加上一个属性函数,定义一个download的函数。因为js是弱关系语言所有你发现这个函数有三个参数但是你却可以无餐直接使用它。因为他不知道你是如何调用他的所以的函数非常巧妙,值得我们学习。
typeof 来检测defaultFileName参数的形式,因为根据顺序来指定参数第一个应该是默认文件名称,第二个成功返回时触发的函数,第三个是设置导出pdf的设置属性。前面几行都是在判断和设置参数,下面就开始真正运行函数。
1 Document.prototype.getBlob = function (cb, options) { 2 if (!cb) { 3 throw 'getBlob is an async method and needs a callback argument'; 4 } 5 var that = this; 6 this.getBuffer(function (result) { 7 var blob = that._bufferToBlob(result); 8 cb(blob); 9 }, options); 10 };
这是讲dd的内容根据原函数的设置变成blob,saveAs讲blob变成filename的pdf。
惊喜红包等你拿