pdfmake icon indicating copy to clipboard operation
pdfmake copied to clipboard

handle svg as string or DOM element

Open mbcgit opened this issue 4 years ago • 5 comments

Hello,

I would like to add an SVG Element from the containing HTML page to the generated pdf. In order to use also the existing styling, it is necessary to transfer the SVG Element to svg-to-pdf and not only SVG as text.

When the changes of this commit, it is possible to do so by calling:

const docDefinition = ... const svgElement: Node = document.getElementById("mySVG"); const svgdoc = { svg: svgElement, width: 400, options: { useCSS: true } }; docDefinition.content.push(svgdoc);

pdfMake.createPdf(docDefinition)

I think this is useful for other users, too, and would therefore ask you to integrate this pull request.

Cheers Markus

mbcgit avatar Jul 14 '21 17:07 mbcgit

This is exactly what I need. I was just about to make similar changes and do a PR myself.

Any way of getting this merged? Haven't tested of checked out the PR in great detail but willing to do so.

bertvh avatar Jan 05 '22 16:01 bertvh

I don't believe any changes are needed. Call outerHTML() upon your svg element to create a string, then use that string to build your layout.

adamwong246 avatar Jul 26 '22 20:07 adamwong246

I'm a bit "out" of this but if I recall correctly, that doesn't work well since outerHTML() doesn't include the css from parent nodes or imported stylesheets in the page. So, this only works if all of the svg styling is done inside the svg.

<html>
  <head>
    <style ... />  <!-- not applied in the PDF -->
    <link rel="stylesheet" ... /> <!-- not applied in the PDF -->
  </head>
  <body style="..."> <!-- not applied in the PDF -->
  <svg> <!-- outerHTML() here -->
    <g>
      <path d="M28.44......." style="fill: black;"/> <!-- Only this style is applied in the PDF -->
    </g>
  </svg>
</html>

bertvh avatar Jul 28 '22 08:07 bertvh

That is true but such a feature would not really be the purview of this library. You'll need to capture that css and combine it with the svg, and then pass that as content to pdfmake. I would recommend something like this: https://www.npmjs.com/package/html-inline-external.

adamwong246 avatar Jul 28 '22 17:07 adamwong246

That seems like a good solution to me. Thanks. Maybe worth mentioning in the docs?

bertvh avatar Jul 31 '22 10:07 bertvh