Created
March 22, 2023 13:51
-
-
Save tonypartridge/becf1821ec3500ff5254f1cf0566ff89 to your computer and use it in GitHub Desktop.
Convert Apex Charts to Image and to end of a PDF Document in a new page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function generatePDF() { | |
var canvas = document.querySelector("#PDF"); | |
screenWidth = parseFloat(window.getComputedStyle(canvas).width); | |
var charts = document.querySelectorAll('.filament-widgets-container'); | |
var images = []; | |
charts.forEach(function (el) { | |
html2canvas(el, { | |
scale: 2480 / screenWidth // 2480px - size for A4 paper, 300 dpi | |
}).then(function (canvas) { | |
var img = new Image(); | |
img.src = canvas.toDataURL("image/jpeg"); | |
images.push(img); | |
if (images.length === charts.length) { | |
generatePdfWithImages(images); | |
} | |
}); | |
}); | |
} | |
function generatePdfWithImages(images) { | |
window.jsPDF = window.jspdf.jsPDF; | |
var doc = new jsPDF({orientation: "landscape", unit: "mm", format: "a4"}); | |
var elementHTML = document.querySelector("#PDF"); | |
doc.html(elementHTML, { | |
callback: function (doc) { | |
var img = images[0]; | |
var aspectRatio = img.width / img.height; | |
var newWidth = doc.internal.pageSize.width - 20; // subtracting 20 to leave some margin | |
var newHeight = newWidth / aspectRatio; | |
doc.addPage(); // Add a new page before adding the image | |
doc.addImage(img, 'JPEG', 10, 10, newWidth, newHeight); // Add the image to the new page | |
for (var i = 1; i < images.length; i++) { | |
img = images[i]; | |
aspectRatio = img.width / img.height; | |
newWidth = doc.internal.pageSize.width - 20; // subtracting 20 to leave some margin | |
newHeight = newWidth / aspectRatio; | |
doc.addPage(); // Add a new page before adding the image | |
doc.addImage(img, 'JPEG', 10, 10, newWidth, newHeight); // Add the image to the new page | |
} | |
doc.save('report-{{$this->startYear}}-{{$this->endYear}}.pdf'); | |
}, | |
showHead: "everyPage", | |
autoPaging: 'text', | |
margin: [5, 5, 5, 5], | |
x: 0, | |
y: 0, | |
width: 280, //target width in the PDF document | |
windowWidth: 1300, //window width in CSS pixels | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment