How to fit an image in the center of a page using jsPDF?
Asked Answered
C

2

9

Using html2canvas & jsPDF, I'm trying to print an entire DIV I have on my screen and I've gotten this far:

const printAsPdf = () => {
  html2canvas(pageElement.current, {
    useCORS: true,
    allowTaint: true,
    scrollY: -window.scrollY,
  }).then(canvas => {
    const image = canvas.toDataURL('image/jpeg', 1.0);
    const doc = new jsPDF('p', 'px', 'a4');
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();

    const widthRatio = pageWidth / canvas.width;
    const heightRatio = pageHeight / canvas.height;
    const ratio = widthRatio > heightRatio ? heightRatio : widthRatio;

    const canvasWidth = canvas.width * ratio;
    const canvasHeight = canvas.height * ratio;

    doc.addImage(image, 'JPEG', 0, 0, canvasWidth, canvasHeight);
    doc.output('dataurlnewwindow');
  });
};

This fills up the page with the image/canvas of my choosing. But I am not able to align the image dead center on the page.

Capitulary answered 31/3, 2020 at 14:31 Comment(0)
C
28

This problem required some old-school CSS tricks. I recalled how we used to center images back in the day with position: absolute; where we would calculate the image width, and canvas width, negate it and divide it by half. Using the same technique here worked like a charm!

const marginX = (pageWidth - canvasWidth) / 2;
const marginY = (pageHeight - canvasHeight) / 2;

So, the complete function looks like this:

const printAsPdf = () => {
  html2canvas(pageElement.current, {
    useCORS: true,
    allowTaint: true,
    scrollY: -window.scrollY,
  }).then(canvas => {
    const image = canvas.toDataURL('image/jpeg', 1.0);
    const doc = new jsPDF('p', 'px', 'a4');
    const pageWidth = doc.internal.pageSize.getWidth();
    const pageHeight = doc.internal.pageSize.getHeight();

    const widthRatio = pageWidth / canvas.width;
    const heightRatio = pageHeight / canvas.height;
    const ratio = widthRatio > heightRatio ? heightRatio : widthRatio;

    const canvasWidth = canvas.width * ratio;
    const canvasHeight = canvas.height * ratio;

    const marginX = (pageWidth - canvasWidth) / 2;
    const marginY = (pageHeight - canvasHeight) / 2;

    doc.addImage(image, 'JPEG', marginX, marginY, canvasWidth, canvasHeight);
    doc.output('dataurlnewwindow');
  });
};
Capitulary answered 31/3, 2020 at 14:31 Comment(1)
what should i do if i want margin from both sides in x-axis ??Erythrism
H
0
const pageWidth = doc.internal.pageSize.width;
const pageHeight = doc.internal.pageSize.height;

is a alternative for an update that modifies the function "getWidth()".

Hanshansard answered 29/7, 2022 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.