【问题标题】:Html2canvas vs jspdf can't export svg in PDF fileHtml2canvas vs jspdf无法在PDF文件中导出svg
【发布时间】:2018-11-09 02:15:46
【问题描述】:

我在我的 Reactjs 项目中使用 html2canvas 与 jsPDF,并且我需要将 DOM 节点导出到 PDF 文件。当我导出时,HTML 和 CSS 被保留,只是 SVG 不能。我不知道为什么。客户端上有另一个包可以帮助我吗?感谢您的关注。 这是我要导出的代码

const filename = 'TyVan.pdf';
    html2canvas(document.querySelector('#buivanty'),{scale: quality}).then(canvas => {
        let pdf = new jsPDF('l', 'mm', 'a4', true)

        pdf.addImage(canvas.toDataURL('image/png', 1.0), 'png', 10, 10, 180, 150);
        pdf.save(filename);
    })

【问题讨论】:

    标签: reactjs jspdf html2canvas


    【解决方案1】:

    我能够通过使用 onClone 选项进行后期处理来解决它

    const options = {
      scale: 1,
      foreignObjectRendering: true,
      onclone: (element) => {
        const svgElements: any[] = element.body.getElementsByTagName('svg');
        Array.from(svgElements).forEach((svgElement) => {
            const bBox: any = svgElement.getBBox();
            svgElement.setAttribute('width', bBox.width);
            svgElement.setAttribute('height', bBox.height);
        });
      },
    };
    
      html2canvas(<HTMLScriptElement>document.querySelector('.main-container'), options).then(canvas => {
          this.clipImage = canvas.toDataURL('image/png');
      });
    

    【讨论】:

    • 我可以自定义 svg 的宽度和高度吗? :)))。这段代码很棒。刚刚遇到了关于 svg 大小的问题 :)) 非常感谢
    猜你喜欢
    • 2021-06-05
    • 1970-01-01
    • 2021-12-26
    • 2021-11-28
    • 2020-09-16
    • 2017-02-16
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多