Search code examples
javascriptjspdf

Unable to save SVG to PDF using jsPDF


I'm trying to download PDF with SVG content using jsPDF library, it is able to download the file, but there is no content inside it, it is empty PDF.

This is my code:

const downloadPDF = (goJSDiagram) => {
  const svg = goJSDiagram.makeSvg({scale: 1, background: "white"});
  const svgStr = new XMLSerializer().serializeToString(svg);
  const pdfDoc = new jsPDF();
  pdfDoc.addSvgAsImage(svgStr, 0, 0, pdfDoc.internal.pageSize.width, pdfDoc.internal.pageSize.height)
  pdfDoc.save(props.model[0].cName?.split(" (")[0] + ".pdf");
}

When I do console.log(svgStr), I can see the SVG XML string. What changes should I make to render the content inside PDF?


Solution

  • After lot of searching, I found the right way to do this, though the content rendered is little blurred.

      const waitForImage = imgElem => new Promise(resolve => imgElem.complete ? resolve() : imgElem.onload = imgElem.onerror = resolve);
    
      const downloadPDF = async (goJSDiagram) => {
        const svg = goJSDiagram.makeSvg({scale: 1, background: "white"});
        const svgStr = new XMLSerializer().serializeToString(svg);
        const img = document.createElement('img');
        img.src = 'data:image/svg+xml;base64,' + window.btoa(svgStr);
    
        waitForImage(img)
          .then(_ => {
            const canvas = document.createElement('canvas');
            canvas.width = 500;
            canvas.height = 500;
            canvas.getContext('2d').drawImage(img, 0, 0, 500, 500);
            const pdfDoc = new jsPDF('p', 'pt', 'a4');
            pdfDoc.addImage(canvas.toDataURL('image/png', 1.0), 0, 200, 500, 500);
            pdfDoc.save(props.model[0].cName?.split(" (")[0] + ".pdf");
          });
      }