html2canvas image to jsPDF renders element sizes differently between browsers

40 Views Asked by At

I'm using html2canvas and jsPDF libraries to generate a PDF export. For lack of a better term, Safari and Chrome respectively are "seeing" the size of elements differently. Safari vs Chrome render size console messages

Another clue is that the SVGs are oversized in Safari.

SVG render difference in pdfs

So despite having set page, window, and canvas sizes manually, the rendered sizes differ. Is there a parameter I'm missing to force resolution or something else so this behaves consistently no matter what browser runs this? (dpi setting doesn't appear to do anything. scale setting doesn't "resize", just makes img blurry if less than 1.)

export async function downloadPDFScorecard(printContent, fileName) {
  // const jsPDF = require('jspdf');
  console.info("download scorecard!");
  const imgWidth = 1142; 
  const pageHeight = 800;  
  const pageWidth = 1142;
  const marginY = 80;
  
  const jsPDFOpt = {
    orientation: 'l',
    unit: 'px',
    //[595.28, 841.89] is a4
    format: [pageHeight, pageWidth], 
    // putOnlyUsedFonts:true,
    compress: false,
    floatPrecision: 16 // or "smart", default is 16
   }

  const html2canvasOpt = {
    dpi: 300, // Set to 300 DPI
    scale: 1.2, // Adjusts your resolution
    width: 1142,
    height: 1256,
    windowWidth: 1142,
    windowHeight: 1256,
    x: 0,
    y: 0,
    logging: true,
    allowTaint: true,
    useCORS: true,
    removeContainer: true
  }

  await html2canvas(printContent, html2canvasOpt).then( (canvas) => {
      const imgHeight = canvas.height * imgWidth / canvas.width;
      let heightLeft = imgHeight;
      const positionX = 70;
      let positionY = 40;
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF(jsPDFOpt);
      // (inner) addImage(imageData, format, x, y, width, height, alias, compression, rotation)
      console.log("pg 1", {positionX, positionY, imgWidth, imgHeight})
      doc.addImage(img, 'JPEG', positionX, positionY, imgWidth, imgHeight, 'NONE', 0);

      heightLeft -= pageHeight;
      positionY = -730;
      console.log("pg 2", {positionX, positionY, imgWidth, imgHeight})
      doc.addPage().addImage(img, 'JPEG', positionX, positionY, imgWidth, imgHeight);

      doc.save(`${fileName}.pdf`);
  });

}
0

There are 0 best solutions below