yWorks/svg2pdf.js

How to convert svg to pdf with multiple pages?

Mertakus opened this issue · 4 comments

I have the following problem:
I want to create a multi-page pdf from some svg elements. Here is my codesandbox displaying my problem.

I expected this to happen:

Basically I have 2 elements that I'd like to display on seperate pages, so something like this:

const page1 = `
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 595.28 841.89"
    >
      <text x="10" y="20" fill="black">page1</text>
    </svg>
  `;
    const page2 = `
    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 595.28 841.89"
    >
      <text x="10" y="20" fill="black">page2</text>
    </svg>
  `;

I tried this:

I then tried to create an svg element with javascript and set the innerHTML to page1 and page2:

    const node = document.createElement("svg");
    node.setAttribute("viewBox", "0 0 595.28 841.89");
    node.innerHTML += page1;
    node.innerHTML += page2;

    doc
      .svg(node, {
        x: 0,
        y: 0,
        width: 595.28,
        height: 841.89
      })
      .then(() => {
        // save the created pdf
        doc.save("myPDF.pdf");
      });

But this is what happened instead:

Instead of creating a multi-page pdf, it just overlaps the 2 svg's together on page1. See image below:

svg2pdf on top of eachother

yGuy commented

That is absolutely expected because your single SVG looks exactly like in your picture. Just because you name the temporary variable "page1" and "page" doesn't separate them onto two different pages.

Instead you need to use the jspdf API to put the SVGs onto two separate pages:

http://raw.githack.com/MrRio/jsPDF/master/docs/jsPDF.html#addPage

Hi @yGuy , thanks for the reply. I do not understand your answer though. Obviously I get that just naming something "page1" and "page2" is not magically going to create 2 pages.

You say "Instead you need to use the jspdf API to put the SVGs onto two separate pages", but how is that even possible? I cannot use the jsPDF html function with svg, that is the reason this library was created.

Correct me if I am wrong, but you're telling me something like this should work:

    const node1 = document.createElement("svg");
    const node2 = document.createElement("svg");
    node1.innerHTML = page1;
    node2.innerHTML = page2;

    doc.svg(node1, {
      x: 0,
      y: 0,
      width: 595.28,
      height: 841.89
    });
    doc.addPage();
    doc.svg(node2, {
      x: 0,
      y: 0,
      width: 595.28,
      height: 841.89
    });
    doc.save("myPdf.pdf");

Except it doesn't obviously, because I am missing the callback on both de doc.svg function calls. So could you please eloborate on your answer? This is a new codesandbox with the above code: reproduction.

yGuy commented

You should make yourself familiar with the Promise API.

https://codesandbox.io/s/frosty-einstein-ffh73h

Well, that makes sense. Thanks for the help, Cheers!