在 Angularjs 中使用 pdfMake 从 HTML 生成 PDF [英] Generate PDF from HTML using pdfMake in Angularjs

查看:42
本文介绍了在 Angularjs 中使用 pdfMake 从 HTML 生成 PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 pdfMakeAngular 从我的 HTML 创建一个 PDF(我也尝试过 jsPDF代码>,也无法让它工作).我尝试在我的 Angular 控制器中使用以下代码:

var blob = new Blob([document.getElementById('exportable').innerHTML])var docDefinition = {内容:[斑点]}pdfMake.createPdf(docDefinition).open();

但我收到以下错误:

<块引用>

无法识别的文档结构:{"_margin":null}".

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

如果有人知道此问题的解决方案,或从 Angular 将 HTML 转换为 PDF 的其他方法,请提供帮助.

非常感谢任何帮助!

解决方案

好的,我想通了.

  1. 您将需要 html2canvaspdfmake.你不需要在你的 app.js 中做任何注入,只需包含在你的脚本标签中

  2. 在要为其创建 PDF 的 div 上,添加如下 ID 名称:

     

  3. 在您的 Angular 控制器中,在您对 html2canvas 的调用中使用 div 的 ID:

  4. 使用 toDataURL() 将画布更改为图像

  5. 然后在 pdfmake 的 docDefinition 中将图像分配给内容.

  6. 控制器中完成的代码如下所示:

     html2canvas(document.getElementById('exportthis'), {onrendered:函数(画布){var data = canvas.toDataURL();var docDefinition = {内容: [{图像:数据,宽度:500,}]};pdfMake.createPdf(docDefinition).download("Score_Details.pdf");}});

我希望这对其他人有帮助.快乐编码!

I am trying to create a PDF from my HTML using pdfMake and Angular (I've also tried jsPDF and couldn't get it to work either). I tried using the following code in my Angular controller:

var blob = new Blob([document.getElementById('exportable').innerHTML])
var docDefinition = {
    content: [blob]
}
pdfMake.createPdf(docDefinition).open();

but I receive the following error:

Unrecognized document structure: {"_margin":null}".

My HTML consists of two simple tables in a div exportable.

If anyone knows a solution to this issue, or another way to get the HTML into a PDF from Angular, PLEASE help.

Any assistance is GREATLY appreciated!

解决方案

Okay, I figured this out.

  1. You will need html2canvas and pdfmake. You do NOT need to do any injection in your app.js to either, just include in your script tags

  2. On the div that you want to create the PDF of, add an ID name like below:

     <div id="exportthis">
    

  3. In your Angular controller use the id of the div in your call to html2canvas:

  4. change the canvas to an image using toDataURL()

  5. Then in your docDefinition for pdfmake assign the image to the content.

  6. The completed code in your controller will look like this:

           html2canvas(document.getElementById('exportthis'), {
                onrendered: function (canvas) {
                    var data = canvas.toDataURL();
                    var docDefinition = {
                        content: [{
                            image: data,
                            width: 500,
                        }]
                    };
                    pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
                }
            });
    

I hope this helps someone else. Happy coding!

这篇关于在 Angularjs 中使用 pdfMake 从 HTML 生成 PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆