Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to send pdf generated from screen shot in JavaScript

Objective – Take a screenshot of the page, then make pdf of that and send that pdf to the spring boot backend.

I have implemented the functionality to take the screenshot and convert it into pdf using html2canvas and pdfmake JavaScript libraries.

Issue – I don’t know how to send the generated pdf to the backend. I got to know about base64 encode but I am still confused.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Code

function takeSS() {
    html2canvas(document.body, {
        onrendered: function(canvas) {
            var data = canvas.toDataURL();
            var docDefinition = {
                content: [{
                    image: data,
                    width: 900,
                }]
            };
            pdfMake.createPdf(docDefinition).download("test.pdf"); // to download
        }
    });
}

The above code is taking the screenshot of the page converting it to pdf and downloading it.
Instead of downloading it, how can I send this pdf to backend?
Do I need to base64 encode canvas.toDataURL()?

>Solution :

According to the docs of pdfmake you’re able to get the generated PDF as a Blob with the getBlob method. The Blob will be a binary representation of your PDF which you can send to your server.

Blobs need to be wrapped inside a FormData object before they can be sent.

function takeSS() {
  html2canvas(document.body, {
    onrendered: function(canvas) {
      var data = canvas.toDataURL();
      var docDefinition = {
        content: [{
          image: data,
          width: 900,
        }]
      };

      const pdfDocGenerator = pdfMake.createPdf(docDefinition);
      pdfDocGenerator.getBlob((blob) => {
        const formData = new FormData();
        formData.append('pdf', blob, 'test.pdf');

        fetch('your-url', {
          method: 'POST',
          body: formData
        }).then(response => {
          if (!response.ok) {
            throw new Error('POST request failed');
          }

          return response.text();
        })
        .then(console.log)
        .catch(console.error);
      });
    }
  });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading