I'm using jsPDF in my Typescript React project and I want to as an SVG to my PDF using jsPDF.
I use addSvgAsImage
like this:
let svg = this.ref.innerHTML
if (svg)
svg = svg.replace(/\r?\n|\r/g, '').trim()
pdf.addSvgAsImage(svg, 15, 45, 270, 130, 'SLOW')
and in my browser I got this error:
Uncaught (in promise) ReferenceError: canvg is not defined
at Object.et.addSvgAsImage (jspdf.min.js?e511:180)
...
It seems that I should include canvg
globally (https://github.com/MrRio/jsPDF/issues/2205), but I have no clue how I can do that.
Does anyone tried addSvgAsImage
in a React project or has an idea how I could solve this problem?
Ok, I find the solution for a React 16.10.2 project using Webpack 4 and it's quite simple:
webpack.config.js
:
const webpack = require('webpack')
module.exports = {
// ...
plugins: [
// ...
new webpack.ProvidePlugin({
canvg: 'canvg',
}),
// ...
],
// ...
}
MyComponent.js
:
// ...
const svg = useRef(null)
// ...
if (svg.current) {
const svgData = new XMLSerializer().serializeToString(svg.current)
pdf.addSvgAsImage(svgData, 0, 0, 270, 130)
pdf.save('a4.pdf')
}
// ...
however, the quality of the SVG is not good, therefor I started using html2canvas.