首页 > 解决方案 > 在 html2canvas/jspdf 中添加边距

问题描述

我使用 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

解决方案


如果它是多个页面,它不起作用。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');
});

推荐阅读