【问题标题】:add margins in html2canvas/jspdf在 html2canvas/jspdf 中添加边距
【发布时间】:2021-09-08 20:41:35
【问题描述】:

我使用html2canvas和jspdf将多页网页导出为pdf。但是,生成的 pdf 中没有边距。如何使用 html2canvas 或 jspdf 添加边距。

html2canvas(document.body, {
    scale: 0.8,
    logging: true,
    allowTaint: false,
    backgroundColor: null
}).then(function(canvas) {
    // Export the canvas to its data URI representation
    var base64image = canvas.toDataURL("image/jpeg");
    console.log('Report Image URL: ' + base64image);

    var imgWidth = 295; 
    var pageHeight = 210;  
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var heightLeft = imgHeight;    
    var doc = new jsPDF("l", "mm", "a4"); // landscape
    var position = 0;

    var width = doc.internal.pageSize.getWidth();
    var height = doc.internal.pageSize.getHeight();    
    doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(base64image,'JPEG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
    }

    doc.save('test.pdf');
});

【问题讨论】:

  • 请问我的回答有帮助吗?

标签: html2canvas


【解决方案1】:

如果是多个页面,它不起作用。 2页之间没有间隙。以下是我修改后的代码:

html2canvas(document.body, {
    scale: 0.8,
    logging: true,
    allowTaint: false,
    backgroundColor: null
}).then(function(canvas) {
    // Export the canvas to its data URI representation
    var base64image = canvas.toDataURL("image/jpeg");
    console.log('Report Image URL: ' + base64image);

    var imgWidth = 295; 
    var pageHeight = 210;  
    var imgHeight = canvas.height * imgWidth / canvas.width;
    var heightLeft = imgHeight;    
    var doc = new jsPDF("l", "mm", "a4"); // landscape
    var position = 0;

    /* addImage explained below:
        param 1 -> image in code format
        param 2 -> type of the image. SVG not supported. needs to be either PNG or JPEG.
        all params are specified in integer
        param 3 -> X axis margin from left
        param 4 -> Y axis margin from top
        param 5 -> width of the image
        param 6 -> height of the image
    */   

    var width = doc.internal.pageSize.getWidth();
    var height = doc.internal.pageSize.getHeight();    
    doc.addImage(base64image,'JPEG', 10, 10, imgWidth-17, imgHeight);
    heightLeft -= pageHeight;

    while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(base64image,'JPEG', 10, position, imgWidth-17, imgHeight);
        heightLeft -= pageHeight;
    }

    doc.save('test.pdf');
});

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 2019-04-30
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多