使用HTML2Canvas和JSPDF将html转换为pdf时的设计问题

时间:2019-09-20 06:52:23

标签: javascript html5-canvas jspdf

我已经使用HTML2Canvas和JSPDF库将html设计转换为PDF,但是第二页出现了问题。首先,我使用了mpdf库,但是它破坏了我的整个设计,这就是为什么我使用HTML2Canvas和JSPDF库的原因。

这是此代码的演示URL。 https://thecvsystem.com/test/

这是我的代码:

    async function getPDF(){

    var custom_value = parseInt(200);

    var HTML_Width = $(".canvas_div_pdf").width();
    var HTML_Height = $(".canvas_div_pdf").height() - custom_value;
    var top_left_margin = 15;
    //var PDF_Width = 800;
    //var PDF_Height = 3508;
    var PDF_Width = HTML_Width+(top_left_margin*2);
    var PDF_Height = (PDF_Width*1.5)+(top_left_margin*2);
    var canvas_image_width = HTML_Width;
    var canvas_image_height = parseInt(HTML_Height);

    var totalPDFPages = Math.ceil(HTML_Height/PDF_Height)-1;

    await html2canvas($(".canvas_div_pdf")[0],{
        //windowWidth: $(".canvas_div_pdf")[0].scrollWidth,
        //windowHeight: $(".canvas_div_pdf")[0].scrollHeight,
        scale: 2,
        dpi: 600,
        allowTaint: true,
        letterRendering: 1,
        logging: true,
        imageTimeout: 0,
        removeContainer: false,
        y: 0
    }).then(function(canvas) {
        //document.body.appendChild(canvas);



        canvas.getContext('2d');

        var imgData = canvas.toDataURL("image/jpeg", 1.0);

        console.log('html', HTML_Width, HTML_Height, 'pdf', PDF_Width, PDF_Height, 'canvas',  canvas.width, canvas.height, 'canvas image',  canvas_image_width, canvas_image_height, 'total pages', totalPDFPages);

        var pdf = new jsPDF({
            unit: "px",
        });
        pdf.addImage(imgData, 'JPG', 0, 0,canvas_image_width*.60,canvas_image_height*.60);

        //'PNG', 20, 40, (width*.62), (height*.62));
        //pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height);


        for (var i = 1; i <= totalPDFPages; i++) { 
            pdf.addPage("A4");
            console.log('yposition', PDF_Height, i, top_left_margin, ((PDF_Height*i)+(top_left_margin*4))*.60);
            //pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height*i)+(top_left_margin*4),canvas_image_width,canvas_image_height); backup
            pdf.addImage(imgData, 'JPG', 0, -636,canvas_image_width*.60,canvas_image_height*.60, '', 'none');
            //pdf.addPage(footer());

        }

        pdf.save("resume.pdf");



    });
};

0 个答案:

没有答案