以角度方式将 svg 显示为 pdf 文件

问题描述 投票:0回答:1
html angular pdf svg jspdf
1个回答
0
投票

首先,您需要按照 Robert 的评论建议添加 SVG 命名空间。其次,您使用了错误的方法将 SVG 直接放入 PDF 中。根据文档,正确的方法是使用

addSvgAsImage
:
https://raw.githack.com/MrRio/jsPDF/master/docs/module-svg.html

请注意,这是一个异步方法,因此您可能需要使用:

而不是
doc.addImage(...)

await doc.addSvgAsImage(svgContent, 10, 10, 100, 100);

如果您想使用

addImage
方法,您仍然可以这样做,但您必须先将 SVG 放在画布上:

const svgContent = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">' +
  '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
'</svg>';

const svgData = 'data:image/svg+xml;base64,' + btoa(svgContent);
const canvas = document.createElement('canvas');

canvas.width = 100;
canvas.height = 100;

const doc = new jsPDF();
const img = new Image();

document.body.appendChild(canvas);

img.onload = function() {
  canvas.getContext('2d')!.drawImage(img, 0, 0);

  doc.addImage(canvas.toDataURL('image/jpeg'), 'JPEG', 10, 10, 100, 100);
};

img.src = svgData;
© www.soinside.com 2019 - 2024. All rights reserved.