Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 18, 2022 05:38 am GMT

Client side PDF generator

Well wonder How client side PDF's are generated and you have tried coulpe and felt nouthing much you can do?. I have used diffrent libray in diffrent projects and well they have their limitations.

In this article I will explain How i used html2Canvas and jsPdf and what all issue i faced and what i found after a long resurch and after taking dousens of pdf and comparing with diffrent solutions we see online.

Hear is my problem statment started with one of the environment my pdf was generating partial image. after digging through a lot i thought it was issue with the package versions, well it didn't work and if you ever face such a issue always try fresh installation of node and/or npm this should be your first stop if it works on one machine and don't on other.

The real issue begins when your image in pdf looks streched but your UI its looking great.

so what i tried, well as you guessed start with fitting to predifined width.

Did it work no. sorry if i have disappointed you. wait a little longer you will see the magic.

you might have come accross below listed solutions and if didnt work scroll to last i will explain how i could atleast achive a better solution if not exact.

1. How to set image to fit width of the page using jsPDF?

var doc = new jsPDF("p", "mm", "a4");var width = doc.internal.pageSize.getWidth();var height = doc.internal.pageSize.getHeight();

2. get width 100% of PDF file and auto height

html2canvas(input)      .then((canvas) => {        const imgData = canvas.toDataURL('image/png');        const pdf = new jsPDF({          orientation: 'landscape',        });        const imgProps= pdf.getImageProperties(imgData);        const pdfWidth = pdf.internal.pageSize.getWidth();        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);        pdf.save('download.pdf');      });

3. fit a web page into the pdf document, without losing the aspect ratio.

var divHeight = $('#div_id').height();var divWidth = $('#div_id').width();var ratio = divHeight / divWidth;html2canvas(document.getElementById("div_id"), {     height: divHeight,     width: divWidth,     onrendered: function(canvas) {          var image = canvas.toDataURL("image/jpeg");          var doc = new jsPDF(); // using defaults: orientation=portrait, unit=mm, size=A4          var width = doc.internal.pageSize.getWidth();              var height = doc.internal.pageSize.getHeight();          height = ratio * width;          doc.addImage(image, 'JPEG', 0, 0, width-20, height-10);          doc.save('myPage.pdf'); //Download the rendered PDF.     }});

4. dynamic sized image

let width = doc.internal.pageSize.getWidth()let height = doc.internal.pageSize.getHeight()let widthRatio = width / canvas.widthlet heightRatio = height / canvas.heightlet ratio = widthRatio > heightRatio ? heightRatio : widthRatiodoc.addImage(  canvas.toDataURL('image/jpeg', 1.0),  'JPEG',  0,  0,  canvas.width * ratio,  canvas.height * ratio,)

5. Solution for all screen sizes and dynamic orientation:

 html2canvas(Component).then((canvas) => {    const componentWidth = Component.offsetWidth    const componentHeight = Component.offsetHeight    const orientation = componentWidth >= componentHeight ? 'l' : 'p'    const imgData = canvas.toDataURL('image/png')    const pdf = new jsPDF({    orientation,    unit: 'px'  })    pdf.internal.pageSize.width = componentWidth    pdf.internal.pageSize.height = componentHeight    pdf.addImage(imgData, 'PNG', 0, 0, componentWidth, componentHeight)    pdf.save('download.pdf')  })

6. doc width/height

var myCanvas = document.getElementById("exportToPDF");    html2canvas(myCanvas, {      onrendered: function(canvas) {        var imgData = canvas.toDataURL(          'image/jpeg', 1.0);        //Get the original size of canvas/image        var img_w = canvas.width;        var img_h = canvas.height;        //Convert to mm        var doc_w = ExportModule.pxTomm(img_w);        var doc_h = ExportModule.pxTomm(img_h);        //Set doc size        var doc = new jsPDF('l', 'mm', [doc_w, doc_h]);        //set image height similar to doc size        doc.addImage(imgData, 'JPG', 0, 0, doc_w, doc_h);        var currentTime = new Date();        doc.save('Dashboard_' + currentTime + '.pdf');      }    });

7. calculate aspect ratio dynamicaly

Well if you made till hear and still didn't find the best solution, don't be disappointed there is no better solution each has a diffren problem and we have a varity of solutions. hear is my solution.

const domElement = document.getElementById("divToPrint");    const width = domElement.clientWidth;    const height = domElement.clientHeight;

will help to capture and generate image ecactly to the client device and using scall to get a better image

html2canvas(domElement,       {         scale: width / height      }).then(function (canvas) {      const img = canvas.toDataURL("image/png", 2.0);      const pdf = new jsPdf("l", "mm", [297, 210]);      pdf.addImage(img, "png", 10, 10, 260, 160, "alias", "FAST");       pdf.save(name);    });

bonus if you wand to add aditional imfo to the pdf

pdf.setDisplayMode("fullpage");      pdf.setProperties({          title: name,           subject: "subject"       });      pdf.setDisplayMode("fullpage");

resources
JsPdf


Original Link: https://dev.to/mallikarjunht/client-side-pdf-generator-2n83

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To