html2pdf.js
html2pdf.js copied to clipboard
Cropped svg in downloading pdf ?
svg it is rendered perfectly in HTML, but when I download it is not rendering properly. why?
in html
in pdf
code used:
function saveAsPDF() {
var element = document.getElementById('printableArea');
var opt = {
margin: 0.3,
filename: 'download.pdf',
image: {type: 'jpeg', quality: 1},
html2canvas: {scale: 4, dpi: 72, letterRendering: true},
jsPDF: {unit: 'in', format: 'A2'},
html2canvas: {
onclone: (element) => {
const svgElements = Array.from(element.querySelectorAll('svg'));
svgElements.forEach(s => {
const bBox = s.getBBox();
s.setAttribute("x", bBox.x);
s.setAttribute("y", bBox.y);
s.setAttribute("width", bBox.width);
s.setAttribute("height", bBox.height);
})
}
}
};
html2pdf().set(opt).from(element).save();
}
html2pdf copies the container node, resize it to match with your desired pdf size minus the left and right margin. So, the container width = 16.5 (A2) - 0.3 (left margin) - 0.3 (right margin) (unit: in).
But at the same time, the copied svg has different width (which should be equal to your window width), and this is far less than the container's, that why the svg was not exported in full size.
To fix that, before calling .save()
, set your #printableArea width to the future container width:
function saveAsPDF() {
var element = document.getElementById('printableArea');
element.style.width = `${16.5 - 0.3 - 0.3}in`;
var opt = {
margin: 0.3,
filename: 'download.pdf',
image: {type: 'jpeg', quality: 1},
html2canvas: {scale: 4, dpi: 72, letterRendering: true},
jsPDF: {unit: 'in', format: 'A2'},
html2canvas: {
onclone: (element) => {
const svgElements = Array.from(element.querySelectorAll('svg'));
svgElements.forEach(s => {
const bBox = s.getBBox();
s.setAttribute("x", bBox.x);
s.setAttribute("y", bBox.y);
s.setAttribute("width", bBox.width);
s.setAttribute("height", bBox.height);
})
}
}
};
html2pdf().set(opt).from(element).save().then(function () { element.style.width = 'auto' });
}
Don't forget to reset element width after exporting.