最近遇一需求 需要将网页部分内容转换成pdf保存下来;
思路是将html转成canvas(html2canvas) 再根据canvas.toDataURL将canvas转换成图片,最后使用pdfjs将图片保存到pdf文件里;
贴一下代码mark下
需要用到上面那两个依赖;
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
const dom = document.getElementById('orderDetail');
html2canvas(dom).then(view => {
const img = view.toDataURL('image/png');
const w = view.width;
const h = view.height;
//一页pdf显示html页面生成的canvas高度;
const pageHeight = w / 592.28 * 841.89;
let leftHeight = h;
// 页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
const a4w = 595.28;
const a4h = 592.28 / w * h;
const pdf = new jspdf('', 'pt', 'a4');
if (leftHeight < pageHeight) {// 仅为一页时
pdf.addImage(img, 'png', 0, 0, a4w, a4h);
} else {// 多页
while(leftHeight > 0) {
pdf.addImage(img, 'png', 0, position, a4w, a4h);
leftHeight -= pageHeight;
position -= 841.89;
if (leftHeight > 0) pdf.addPage()
}
}
pdf.save(`订单${this.temp.order_id}.pdf`);
})