I'm looking to convert some simple HTML into a PDF. It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF.
The issue I'm getting is that I have both a background image and inline image in my HTML but neither are showing in the PDF once converted. I've created a Codepen here: https://codepen.io/adamboother/pen/NWGeqom
Here's my js that does the conversion:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate')).then(canvas => {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
});
}
Has anyone found a fix for this?
I am using useCORS: true to your code and it works, assuming your image is in the server. Besides you can follow below code:
function convertToPdf()
{
html2canvas(document.querySelector('#certificate'), {useCORS: true}).then(function(canvas) {
let img = new Image();
img.src = canvas.toDataURL('image/png');
img.onload = function () {
let pdf = new jsPDF('landscape', 'mm', 'a4');
pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
pdf.save('certificate.pdf');
};
});
}
Yes, @shoma 's answer works for me. this is my code HTML and Image bind to the PDF
pdf.html(htmlContent, {
html2canvas: { scale: 0.8 },
pagesplit: true,
callback: () => {
html2canvas(SELECTOR_HERE, {
useCORS: true
}).then((canvas) => {
const img = new Image();
img.src = canvas.toDataURL('image/png');
img.onload = () => {
pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, 200);
pdf.save(`download-${genarateFileName}.pdf`);
};
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With