使用Angularjs中的pdfMake从HTML生成PDF

我想创建一个PDF使用我的HTML pdfMake和Angular(我也试了jsPDF,不能让它无论是工作)。我尝试在Angular控制器中使用以下代码:


var blob = new Blob([document.getElementById('exportable').innerHTML])

var docDefinition = {

    content: [blob]

}

pdfMake.createPdf(docDefinition).open();

但是我收到以下错误:


无法识别的文档结构:{“_ margin”:null}“。


我的HTML由div中的两个简单表组成exportable。


如果有人知道这个问题的解决方案,或者从Angular获取HTML到PDF的其他方法,请帮助。


任何帮助都非常感谢!


红颜莎娜
浏览 1505回答 3
3回答

温温酱

好的,我想出来了。1.你需要html2canvas和pdfmake。您不需要在app.js中进行任何注入,只需包含在脚本标记中在要创建PDF的div上,添加如下ID ID:&nbsp;<div id="exportthis">在Angular控制器中,在调用html2canvas时使用div的id:使用toDataURL()将画布更改为图像然后在pdfmake的docDefinition中将图像分配给内容。控制器中完成的代码如下所示:&nbsp; &nbsp; &nbsp; &nbsp;html2canvas(document.getElementById('exportthis'), {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onrendered: function (canvas) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var data = canvas.toDataURL();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var docDefinition = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; content: [{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image: data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; width: 500,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; pdfMake.createPdf(docDefinition).download("Score_Details.pdf");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; });我希望这有助于其他人。快乐的编码!

繁星coding

这是它对我有用的我正在使用Angular2应用程序中的html2pdf,所以我在控制器中引用了这个函数var html2pdf = (function(html2canvas, jsPDF) {在html2pdf.js中声明。所以我在我的angular-controller声明中添加了这个声明:declare function html2pdf(html2canvas, jsPDF): any;那么,从我的角度控制器的方法我调用这个函数:generate_pdf(){&nbsp; &nbsp; this.someService.loadContent().subscribe(&nbsp; &nbsp; &nbsp; pdfContent => {&nbsp; &nbsp; &nbsp; &nbsp; html2pdf(pdfContent, {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; margin:&nbsp; &nbsp; &nbsp; &nbsp;1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; filename:&nbsp; &nbsp; &nbsp;'myfile.pdf',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image:&nbsp; &nbsp; &nbsp; &nbsp; { type: 'jpeg', quality: 0.98 },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; html2canvas:&nbsp; { dpi: 192, letterRendering: true },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; jsPDF:&nbsp; &nbsp; &nbsp; &nbsp; { unit: 'in', format: 'A4', orientation: 'portrait' }&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; );&nbsp; }希望能帮助到你
打开App,查看更多内容
随时随地看视频慕课网APP