I'm currently using d3.js version 5 and was wondering if there is an actual way for me to export my charts to PDF? For example in the screenshot provided below, there is a button for me to use or an option for me to export that specific chart to PDF
I'm currently using d3.js version 5 and was wondering if there is an actual way for me to export my charts to PDF? For example in the screenshot provided below, there is a button for me to use or an option for me to export that specific chart to PDF
Share Improve this question asked May 14, 2020 at 14:47 Elijah LeisElijah Leis 4152 gold badges11 silver badges24 bronze badges 1-
Do you need the conversion to happen on client side (
jsPDF
) or running it server side (wkhtmltopdf
) will be alright? – timur Commented May 18, 2020 at 3:39
1 Answer
Reset to default 7 +50You can use PDFKIT library to achieve this, this snippet is inspired by the example they provided in the live demo, I just extended it by adding the D3.js
example along javascript to retrieve the HTML text.
Update: I added custom implementation to allow custom file name for the downloaded PDF, basically I create <a>
tag, append it to body, then assign download
attribute to it, and the href
attribute contains the blob
object URL we created.
NOTE: this will not work in the snippet since its a sandbox, it should work fine in your local machine and production.
const svgToPdfExample = (svg) => {
const doc = new window.PDFDocument();
const chunks = [];
const stream = doc.pipe({
// writable stream implementation
write: (chunk) => chunks.push(chunk),
end: () => {
const pdfBlob = new Blob(chunks, {
type: "application/octet-stream",
});
var blobUrl = URL.createObjectURL(pdfBlob);
//window.open(`${blobUrl}?customfilename.pdf`);
/* custom file name download */
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = blobUrl;
a.download = "test.pdf"; // <----