Skip to content

Instantly share code, notes, and snippets.

@lancechentw
Last active August 18, 2022 05:04
Show Gist options
  • Save lancechentw/7c0ee2d51d1754783d7d90e6e47c57f9 to your computer and use it in GitHub Desktop.
Save lancechentw/7c0ee2d51d1754783d7d90e6e47c57f9 to your computer and use it in GitHub Desktop.
// Change the viewport temporarily, use browser's developer console to
// decide what width would fit your content to a A4 size pdf better.
// You will probably need to redesign the layout of your website under this breakpoint.
document.querySelector("meta[name=viewport]").setAttribute("content", "width=1000px");
// I have 2 Chart.js objects on my website, and they work bad under
// this viewport, so I am resizing them. You could probably do similar
// thing to your images here.
if (temperatureChart && pressureChart) {
temperatureChart.resize(640, 320);
pressureChart.resize(640, 320);
}
html2canvas(document.body, {
width: 1000,
windowWidth: 1000,
scale: 2,
}).then(function (canvas) {
const img = canvas.toDataURL("image/png");
const imgWidth = 210;
const pageHeight = 295;
const imgHeight = (canvas.height * imgWidth) / canvas.width;
let heightLeft = imgHeight;
const doc = new jsPDF("p", "mm", "a4", true);
// slice the `img` into multiple A4-height images, and add them into each page
// your image is cut through here, so you have to design your layout to avoid this from happening
// the first page
let position = 0;
doc.addImage(img, "PNG", 0, position, imgWidth, imgHeight, undefined, "FAST");
heightLeft -= pageHeight;
// the rest of the pages
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, "PNG", 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
doc.save(`test.pdf`);
document
.querySelector("meta[name=viewport]")
.setAttribute("content", "width=device-width, initial-scale=1");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment