vue export pdf

Export pdf in vue project (pure front-end operation)

There are many times when we need to export pdf files in the project. In fact, we use plug-ins to render vue components into pictures, and then add the pictures to PDF documents for export.


本文用到的插件是html2canvas和jsPDF


foreword

提示:这里可以添加本文要记录的大概内容:

For example: With the continuous development of artificial intelligence, the technology of machine learning is becoming more and more important. Many people have started to learn machine learning. This article introduces the basic content of machine learning.


提示:以下是本篇文章正文内容,下面案例可供参考

1. What is the html2canvas plug-in?

html2canvas is a JavaScript library for rendering HTML elements as Canvas elements. It can convert any HTML element on a web page (including images, text, SVG, etc.)

2. What is the jsPDF plug-in?

jsPDF is a JavaScript library for generating PDF documents on the client side. It provides an easy way to create and download PDF documents without using server-side code or third-party services.
Although jsPDF itself is already very powerful, it can also use many plug-ins to extend its functionality. These plugins can add new functionality such as adding watermarks, importing and exporting data, generating QR codes and barcodes, etc.

1. Import library

The code is as follows (example):

npm install --save html2canvas 
npm install --save jsPDF 

2. Import the vue file

The code is as follows (example):

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

3. Key code

The code is as follows (example):


<el-button size="mini" type="success" @click="exportPDF">导出pdf</el-button>

//js部分
   async exportPDF() {
    
    
   // 获取要导出的Vue组件
      const vueComponent = document.querySelector('.pdf-canvas-warp')
      // 使用html2canvas将Vue组件渲染为图片
      const canvas = await html2canvas(vueComponent)
      // 创建新的jsPDF文档
      const pdf = new jsPDF('p', 'mm', 'a4')
      // 将渲染的图片添加到PDF文档中
      pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298)
      // 下载PDF文件
      pdf.save('my-pdf-document.pdf')
    },

点击导出按钮,网页便会执行下载操作,具体参数需要根据实际情况配置。

attach

If there are other extended functions, such as adding watermarks, importing and exporting data, generating QR codes and barcodes, etc. Can be used in conjunction with the following plug-ins:
1. html2pdf - allows converting HTML content into PDF documents.
2. jspdf-autotable - allows to create tables in PDF.
3. jspdf-debugger - Provides a method for debugging jsPDF to generate PDF documents.
4. jspdf-split-text-to-size - Allows text to be split into multiple lines.
5. jspdf-vue - a plugin for using jsPDF in Vue.js applications.

Summarize

The content of this issue has been shared, and everyone's guidance and suggestions are welcome.

Guess you like

Origin blog.csdn.net/weixin_48211022/article/details/130103078