123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- import html2canvas from "html2canvas";
- import jsPDF from "jspdf";
- export const downloadPDF = page => {
- console.log(444);
- html2canvas(page).then(function(canvas) {
- canvas2PDF(canvas);
- });
- };
- const canvas2PDF = canvas => {
- let contentWidth = canvas.width;
- let contentHeight = canvas.height;
- // 一页pdf显示html页面生成的canvas高度;
- let pageHeight = contentWidth / 592.28 * 841.89 ;
- // let pageHeight = 841.89;
- // 未生成pdf的html页面高度
- let leftHeight = contentHeight;
- // 页面偏移
- let position = 0;
- // html页面生成的canvas在pdf中图片的宽高(本例为:横向a4纸[841.89,592.28],纵向需调换尺寸)
- let imgWidth = 592.28;
- let imgHeight = 592.28 / contentWidth * contentHeight;
- // let imgHeight = 841.89;
- let pageData = canvas.toDataURL('image/jpeg', 1.0);
- let PDF = new jsPDF('', 'pt', 'a4');
- // 两个高度需要区分: 一个是html页面的实际高度,和生成pdf的页面高度
- // 当内容未超过pdf一页显示的范围,无需分页
- if (leftHeight < pageHeight) {
- PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
- } else {
- while (leftHeight > 0) {
- PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
- leftHeight -= pageHeight;
- position -= 841.89;
- // 避免添加空白页
- if (leftHeight > 0) {
- PDF.addPage();
- }
- }
- }
- PDF.save('测试' + '.pdf')
- // let contentWidth = canvas.width;
- // let contentHeight = canvas.height;
- // console.log(contentWidth,contentHeight);
- // let imgHeight = contentHeight;
- // let imgWidth = contentWidth/2;
- // // 第一个参数: l:横向 p:纵向
- // // 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
- // let pdf = new jsPDF('l', 'pt', 'a4');
- // pdf.addImage(
- // canvas.toDataURL("image/jpeg", 1.0),
- // "JPEG",
- // 0,
- // 0,
- // imgWidth,
- // imgHeight
- // );
- // pdf.save("导出.pdf");
- };
|