6

I'm creating a PDF by using the entire document.body, turning it into a canvas and passing that to jsPDF. But the image/canvas is too wide. I want to scale it for the page, but jsPDF doesn't have pixel size as a measurement.

The options are: pt, mm, cm. How do I properly size for that? And how do I scale my image if needed?

Should I be using the addImage function to scale, or scale by using canvas.getContect( "2d" ) and drawing on to a new canvas?

html2canvas(
    document.body,
    {
        //When the canvas is created, our callback
        onrendered: function(canvas)
        {         
            //Create jsPDF with what measurements?
            var doc = new jsPDF('p', 'pt');

            /*
             * Put image on page. Are these measurements
             * in pts? How does that compare to pixels?
             *
             * Is the x/y (the 10, 10) the x and y in the image?
             * Or in the page where the image is printed?
             * 
             * Should I be using this to scale, or scale by
             * using canvas.getContect( "2d" ) and drawing on
             * to a new canvas?
             */
            doc.addImage(canvas, 'PNG', 10, 10, 1024, 1000);

            //Save
            doc.save('sample-file.pdf');
    }
});
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

1 Answers1

0

This needs a bit more tweaking but is the best solution arrived at thus far. Perhaps more can contribute to get it perfect. This solution is grabbing a form element of a ReactJS application. It is creating a PDF of a large form. The html2canvas windowWidth is needed because the similar jsPDF setting states it does not affect media queries.

toPdf = (callback) => {
    const capture = document.querySelector('form')
    const pdf = jsPDF({orientation: 'p', format: 'letter'})

    pdf.html(capture, {
        callback: function (doc) {
            if (!callback) {
                return
            }

            callback(doc)
        },
        x: 0,
        y: 0,
        margin: [4, 4, 4, 4], // mm
        width: 208, // 216 = letter paper width in mm, 208 = less the 8mm margin
        windowWidth: 786,  // 816 = letter paper pixel width at 96dpi (web), 786 = less the 30px margin
        html2canvas: {
            logging: false,
            windowWidth: 786 // 816 = letter paper pixel width at 96dpi (web), 786 = less the 30px margin
        }
    })
}

jsPDF.html(...) documentation

Mason
  • 11
  • 2