html2pdf 是基于 html2canvas 和 jsPDF 开发的将 html 页面导出成 pdf 文件的插件,通过配置 opt 相关选项,可以自定义导出的选项,最近在使用 html2pdf 的时候,发现页面中的 img 图片导出的图案是空白的,查阅了相应的 issue 发现可以通过相关配置解决这个问题,这里做下记录。
【问题重现】
需要导出成pdf的的页面部分如下:

页面中的头像对应的标签如下:
<img src="http://wx.qlogo.cn/mmopen/ajNVdqHZLLAicEC4g8RH23v6aNPjUd5dbh0NYk2MM2Umf5nZSnYw7oK1AANaZruTG1GRlpv541AjLX4skqyvRjPtwUTFhJiasmszksdPtPGc0/64" />
导出页面成pdf,查看效果如下:

发现页面中的头像图片没有导出成功,同样是标签,为什么图片没法导出呢,查阅插件相关的issue (Does it support img <img src=''/> in html ? ),
发现原来是跨域问题,插件基于安全问题的考虑,默认禁止导出的html 中包含引用外链的img,并给出了对应的解决方案,如下:


html2canvas 的配置项 options 中提供了两个字段,useCORS 和 proxy,因为 html2pdf 是基于 html2canvas 开发的,
所以在其配置项中包含了 html2canvas 字段,在这个字段中可以配置 html2canvas 的相关选项,如下:
const opt = {
filename: 'myReport.pdf',
image: { type: 'jpeg', quality: 0.95 },
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] },
html2canvas: {
scale: 2,
useCORS: true,
},
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
};
修改完成后再次导出,查看效果,发现引用外链的图片已经可以正常导出了,如下:

|