2

On my react web application the user can submit a form and results will show.

To display my results I'm using material-table. More specifically, I'm using the detail component found here: https://material-table.com/#/docs/features/detail-panel

So when a user search, sometimes there are 5 results, sometimes there are 200 results and with the ability to open the panel for more information for each result, the height can widely vary.

What I'm trying to do is allow the user to print their search results. I'm doing this using jsPDF and html2canvas.

Here is my current problems:

  • If my search results div (#printThis) is shorter than a full page, then for some reason it will almost center the image on the PDF instead of always starting at the top.
  • No matter how long my search results div is, it will never display more than like 20% on the second page. So let's say the search results div (#printThis) has a table with 180 results it should be about 5-6 pages in PDF form, but it will always create a max of 2 pages and the second page will only have like 20% of the data there. So it seems like the addImage is not grabbing the whole image.

So what I'm trying to accomplish is to be able to print a PDF with all my results. The width will always be the same, but the height will always be dynamic, and there will be multiple pages at times.

I was also using this as reference, but now I'm stuck: How to set image to fit width of the page using jsPDF?

Here is my code:

let input = document.getElementById('printThis');

html2canvas(input)
.then((canvas) => {
    var imgData = canvas.toDataURL('image/png');
    var pdf = new jsPDF();
    var imgProps= pdf.getImageProperties(imgData);
    var pdfWidth = pdf.internal.pageSize.getWidth();
    var pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
    var heightLeft = pdfHeight;
    var position = 10; // give some top padding to first page

    pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
    heightLeft -= pdfHeight;

    //Create additional pagess if needed
    while (heightLeft >= 0) {
        position += heightLeft - pdfHeight; // top padding for other pages
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, pdfHeight);
        heightLeft -= pdfHeight;
    }           

    pdf.save('download.pdf');
}).catch(
    e=>console.log('error', e) 
); 
hisusu32
  • 437
  • 7
  • 22

0 Answers0