html2canvas、jsPDF - 如何为“合法信函”PDF 页面缩放/调整页面大小?

Don*_*mmy 6 html javascript canvas html2canvas jspdf

我用整个创建PDF document.body,把它变成一个画布,并传递一个到jsPDF。但是图像/画布太宽了。我想为页面缩放它,但jsPDF没有像素大小作为度量。

选项是:ptmmcm。我如何正确调整大小?如果需要,我如何缩放我的图像?

我应该使用该addImage函数进行缩放,还是通过使用 canvas.getContect("2d") 并在新画布上绘图?

html2canvas(
    document.body,
    {
        //When the canvas is created, our callback
        onrendered: function(canvas)
        {         
            //Create jsPDF with what measurements?
            var doc = new jsPDF('p', 'pt');

            /*
             * Put image on page. Are these measurements
             * in pts? How does that compare to pixels?
             *
             * Is the x/y (the 10, 10) the x and y in the image?
             * Or in the page where the image is printed?
             * 
             * Should I be using this to scale, or scale by
             * using canvas.getContect( "2d" ) and drawing on
             * to a new canvas?
             */
            doc.addImage(canvas, 'PNG', 10, 10, 1024, 1000);

            //Save
            doc.save('sample-file.pdf');
    }
});
Run Code Online (Sandbox Code Playgroud)

小智 0

这需要更多的调整,但这是迄今为止达到的最佳解决方案。也许更多的人可以为它的完美做出贡献。该解决方案正在抓取formReactJS 应用程序的一个元素。它正在创建一个大表单的 PDF。需要html2canvaswindowWidth是因为类似的 jsPDF 设置表明它不会影响媒体查询。

toPdf = (callback) => {
    const capture = document.querySelector('form')
    const pdf = jsPDF({orientation: 'p', format: 'letter'})

    pdf.html(capture, {
        callback: function (doc) {
            if (!callback) {
                return
            }

            callback(doc)
        },
        x: 0,
        y: 0,
        margin: [4, 4, 4, 4], // mm
        width: 208, // 216 = letter paper width in mm, 208 = less the 8mm margin
        windowWidth: 786,  // 816 = letter paper pixel width at 96dpi (web), 786 = less the 30px margin
        html2canvas: {
            logging: false,
            windowWidth: 786 // 816 = letter paper pixel width at 96dpi (web), 786 = less the 30px margin
        }
    })
}
Run Code Online (Sandbox Code Playgroud)

jsPDF.html(...) 文档