tsayen / dom-to-image

Generates an image from a DOM node using HTML5 canvas
Other
10.21k stars 1.68k forks source link

Why additional space is appears in right side of pdf #447

Open joeyy-c opened 1 year ago

joeyy-c commented 1 year ago

Issue:

Additional space appears on every page of the pdf, but the canvasImageWidth and pdfWidth are same, by right the content should fit the pdf width exactly. I am generating this PDF is A5 size. How to remove those spaces?

Screenshot:

Log:

image

PDF:

Screenshot_226

My Code:

// const margin = 15;
const margin = 0;
const htmlWidth = 419.52755906 - (margin * 2); // a5 size in pt
const ratio = document.getElementById('article-body').offsetWidth / htmlWidth;
const htmlHeight = document.getElementById('article-body').offsetHeight / ratio;

let pdfWidth = 419.52755906; // a5 size in pt
let pdfHeight = 595.27559055; // a5 size in pt

const totalPDFPages = Math.ceil(htmlHeight / pdfHeight) - 1;
const data = this.document.getElementById('article-body');

const canvasImageWidth = htmlWidth;
const canvasImageHeight = htmlHeight;

console.log("canvasImageWidth : " + canvasImageWidth );
console.log("pdfWidth: " + pdfWidth);

domtoimage.toJpeg(data, { quality: 0.95, bgcolor: "#ffffff" }).then (function (dataUrl) {
    let pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
    pdf.addImage(dataUrl, 'png', margin, margin, canvasImageWidth, canvasImageHeight);

    for (let i = 1; i <= totalPDFPages; i++) {
        pdf.addPage([pdfWidth, pdfHeight], 'p');
        pdf.addImage(dataUrl, 'png', margin, - (pdfHeight * i) + margin, canvasImageWidth, canvasImageHeight);
    }

    pdf.save("<?php echo $this->item->alias; ?>" + '.pdf');
})
.catch(function (error) {
    console.error('oops, something went wrong!', error);
});