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.
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);
});
}
});
}