Skip to content

SVG cannot be added #2541

@Loceka

Description

@Loceka

Hello,

My bug looks similar to 2157 : I'm trying to add an SVG to the PDF but the output is a blank page.

When I try to load the same SVG as an image, it works well :

<!doctype html>
<html>
	<head>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
		<script type="text/javascript">
			function svgToImg(svg) {
				return new Promise(resolve => {
					var png = new Image();
					var DOMURL = self.URL || self.webkitURL || self;
					var img = new Image();
					var svgBlob = new Blob([svg.outerHTML], {type: "image/svg+xml;charset=utf-8"});
					var url = DOMURL.createObjectURL(svgBlob);

					img.onload = function() {
						var canvas = document.createElement("canvas");
						canvas.setAttribute("width", img.width);
						canvas.setAttribute("height", img.height);
						var ctx = canvas.getContext("2d");
						ctx.drawImage(img, 0, 0, img.width, img.height);
						var pngSrc = canvas.toDataURL("image/png");
						png.src = pngSrc;
						DOMURL.revokeObjectURL(pngSrc);

						resolve(png);
					};
					img.src = url;
				});
			}
			async function generatePDF() {
				var png = await svgToImg(document.querySelector("svg"));
				var pdf = new jsPDF();
				pdf.addSvg(document.querySelector('svg').outerHTML, 0, 0);
				pdf.addPage();
				pdf.addImage(png.src, 'png', 0, 0);
				pdf.save("svg.pdf");
			}
		</script>
	</head>
	<body onload="generatePDF()">
<svg width="62pt" height="44pt" viewBox="0.00 0.00 62.00 44.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph1" class="graph" transform="scale(1 1) rotate(0) translate(4 40)">
<title>G</title>
<polygon fill="white" stroke="white" points="-4,5 -4,-40 59,-40 59,5 -4,5"></polygon>
<!-- a -->
<g id="node1" class="node"><title>a</title>
<ellipse fill="none" stroke="black" cx="27" cy="-18" rx="27" ry="18"></ellipse>
<text text-anchor="middle" x="27" y="-13.8" font-family="Times,serif" font-size="14.00">a</text>
</g>
</g>
</svg>
	</body>
</html>

Having the addSvg() method working would be really appreciated since SVG contains text that can be searched, copied and pasted contrary to an image, and it would be great in a PDF file.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions