You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JS将外部URL的SVG图片转为Base64,并结合jsPDF将SVG文件添加到生成的PDF中?

如何通过JS将外部URL的SVG图片转为Base64,并结合jsPDF将SVG文件添加到生成的PDF中?

我之前花了好长时间才搞定用jsPDF把外部URL的SVG文件添加到生成的PDF里这个需求,踩了不少坑,现在把可行的方案分享给大家。

核心思路是:先把外部SVG通过AJAX请求获取并转换为Base64格式,再把Base64赋值给页面上的img元素,最后就可以用jsPDF的addImage方法把这个img元素添加到PDF中了。

第一步:编写SVG转Base64的工具函数

这个函数会通过XMLHttpRequest请求外部SVG资源,然后用FileReader把Blob转为DataURL(也就是Base64格式):

/**
 * @params url - 外部SVG的URL,例如 'https://www.example.com/your-logo.svg'
 */
const convertSvgToBase64 = (url: string | null): string => {
  if (!url) {
    return '';
  }

  let result: string | ArrayBuffer | null = null;
  const xhr = new XMLHttpRequest();

  xhr.onload = () => {
    const reader = new FileReader();
    reader.onloadend = () => {
      // 获取页面中提前准备好的img元素
      const img = document.getElementById('pdfCruiseLogo');
      if (reader.result) {
        // 将转换后的Base64设置为img的src
        img?.setAttribute('src', reader.result.toString());
        result = reader.result;
      }
    };
    // 将请求到的Blob转为DataURL
    reader.readAsDataURL(xhr.response);
  };

  xhr.open('GET', url);
  xhr.responseType = 'blob';
  xhr.send();

  return typeof result === 'string' ? result : '';
};

第二步:在页面中准备img元素

我们需要一个中转用的img元素(可以隐藏),用来承载转换后的Base64内容:

<!-- 可以设置display:none隐藏,仅作为资源载体 -->
<img
  id="pdfCruiseLogo"
  :src="convertSvgToBase64(voyageData.voyage.cruiseLineLogoUrl)"
  :alt="voyageData.voyage.cruiseLineName"
  style="display:none;"
/>

第三步:结合jsPDF生成PDF

一定要等img元素加载完成后再调用jsPDF的方法,否则会出现图片无法渲染的问题:

// 监听img加载完成事件
const imgElement = document.getElementById('pdfCruiseLogo');
imgElement.onload = () => {
  const doc = new jsPDF();
  // 添加图片到PDF,参数依次为:元素、格式、x坐标、y坐标、宽度、高度
  doc.addImage(imgElement, 'SVG', 10, 10, 50, 50);
  // 保存生成的PDF
  doc.save('document-with-svg.pdf');
};

注意事项

  • 跨域问题:如果外部SVG的域名和你的项目域名不同,需要目标服务器配置CORS允许你的域名访问,否则请求会失败。
  • 异步时机:转换Base64和图片加载都是异步操作,务必确保资源加载完成后再执行PDF生成逻辑。

备注:内容来源于stack exchange,提问作者front-end-performer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 12:28:07