最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - D3.js version 5 chart to PDF - Stack Overflow

programmeradmin6浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 7 +50

You 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"; // <---- 
发布评论

评论列表(0)

  1. 暂无评论