如何使用jsPDF创建pdf输出,'确切地说'正如window.print()命令发出的那样

How can jsPDF be used to create pdf of output, 'exactly' as window.print() command gives out?

本文关键字:window print 命令 正如 pdf 创建 jsPDF 何使用 输出      更新时间:2023-09-26

如何使用jsPDF创建输出的pdf,"完全"如window.print()命令所示?

我必须创建一个"div"元素的pdf,我尝试使用jsPDF。但我得到的输出有很多额外的项目符号和混乱的编号。但我在屏幕上看到的是格式良好的"div",我可以通过我们的window.print().完全打印它

我唯一的抱怨是,我希望为那些无法将打印中的选项更改为"保存为pdf"的用户提供另一个将输出保存为pdf的选项。

    var pdf = new jsPDF('p', 'pt', 'letter');
    var source = $('#content')[0]; //content has the survey with lot of linked list elements and various formatted text
    //I tried all kind of formatting on 'source' to make it right... but its not possible to keep the form as it is what it looks on screen
    margins = {
        top: 80,
        bottom: 60,
        left: 40,
        width: 522
    };
    pdf.fromHTML(
            source, // HTML string or DOM elem ref.
            margins.left, // x coord
            margins.top, {// y coord
                'width': margins.width, // max width of content on PDF
                //'elementHandlers': specialElementHandlers
            },
    function (dispose) {
        // dispose: object with X, Y of the last line add to the PDF 
        //          this allow the insertion of new lines after html
        pdf.save('Disclosure' + '@DateTime.Now' + '.pdf');
    }
    , margins);

那么,有没有一种方法可以在window.print()之后将输出保存为PDF?

尝试一下:

var pdf = new jsPDF('p', 'pt', 'letter');
var source = $('#content')[0];
var options = { background: '#fff' };
pdf.addHTML(source, options, function()
{
     pdf.save('Disclosure' + '@DateTime.Now' + '.pdf');
});

(如果您处理的是单个元素,如前面提到的div,则需要使用background选项,否则您将获得透明/黑色背景)

还要注意,你需要html2canvas才能工作。