Technology Sharing

Generate local pdf and download in Vue3

2024-07-08

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1 Introduction

In the front end, we often encounter the problem of exporting a PDF file based on data in the system. Generally, it is implemented by the back end. Since the back end can do it, why can't the front end do it? I happened to write this requirement once, so I wrote a small demo.

sample graph:
Front-end view source code
Download the completed pdf file

2. Implementation steps

  1. First downloadhtml2pdf.jsThis library
    yarn add html2pdf.js
    // 或
    npm i html2pdf.js
    
  2. Reference this component where you need to use this function in your project
  3. usehtml2pdf.js
    // 获取一个dom对象,这个dom对象就是pdf中显示的内容
    let element = document.querySelector('.tableBox');
    
    // 设置html2pdf的配置
    let opt = {
      margin: 0, // 设置PDF页面的边距为0,即没有边距
      filename: `成绩表.pdf`, // 指定生成文件的名称
      image: { type: 'jpeg', quality: 1 }, // 设置生成PDF时使用的图像格式为JPEG,质量为1(最高质量)
      // 这是一个用于将HTML元素转换为canvas的库
      html2canvas: {
        scale: 2, //  缩放比例为2,即生成的canvas尺寸是原始尺寸的两倍
        allowTaint: false, // 设置为false,表示不允许加载跨域的图片
        useCORS: true, // 设置为true,允许跨域加载的图片使用CORS策略
      },
      //  控制PDF页面的分页行为
      // mode: 设置为avoid-all,尽量避免分页
      // after: 在生成PDF时,当遇到id为levelAnalysis的元素后进行分页
      pagebreak: { mode: 'avoid-all', after: '#levelAnalysis' },
      enableLinks: true, // 支持文本中放链接,可点击跳转
    };
    
    // 执行pdf的导出
    // html2pdf()将html转换为pdf
    // set(opt)表示转换为pdf时使用指定的配置
    // form表示html2pdf中将指定的dom元素加入pdf
    // save()表示将创建完成的pdf保存到本地
    html2pdf().set(opt).from(element).save();
    

3. Conclusion

Generate local PDF and download it in Vue3 mainly usinghtml2pdf.jsA third-party library, through which the specifieddompasscanvasConvert it to an image, so that you only need to load this image in the PDF, and then save the PDF to the local computer through the specified configuration and the specified API.