在vue3+ts中下载一个pdf文件

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf'

function exportDataPdf(el: HTMLElement, fileName: string) {
  html2canvas(el, {
    scale: 3, // 设置缩放
    useCORS: true, // 允许canvas画布内 可以跨域请求外部链接图片, 允许跨域请求。
    allowTaint: true,
    logging: false, // 打印日志用的 可以不加默认为false
    backgroundColor: '#ffffff'
  }).then((canvas) => {
    const contentWidth = canvas.width;
    const contentHeight = canvas.height;




    // 一页pdf显示html页面生成的canvas高度;a4纸的尺寸[595.28,841.89],pageHeight是应有高度吗,leftHeight是实际高度吗
    const pageHeight = (contentWidth / 592.28) * 841.89;
    // 未生成pdf的html页面高度
    let leftHeight = contentHeight;
    // 页面偏移
    let position = 0;
    // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
    const imgWidth = 595.28;
    const imgHeight = (595.28 / contentWidth) * contentHeight;



    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
    // 添加水印
    // ctx.textAlign = 'center';
    // ctx.textBaseline = 'middle';
    // ctx.rotate((25 * Math.PI) / 180);
    ctx.font = '20px Microsoft Yahei';
    // ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
    // for (let i = contentWidth * -1; i < contentWidth; i += 240) {
    //   for (let j = contentHeight * -1; j < contentHeight; j += 100) {
    //     // 填充文字,x 间距, y 间距
    //     ctx.fillText('水印名', i, j);
    //   }
    // }
    //toDataURL()方法是返回一个包含图片展示的数据URL。
    const pageData = canvas.toDataURL('image/jpeg', 1.0);
    const pdf = new jsPDF("p", "pt", "a4");
    if (leftHeight < pageHeight) {
      // 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
      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(`${fileName}.pdf`);
  })
}

export default exportDataPdf;
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容