vue 生成PDF(A4标准PDF分页)
1.先安裝兩個插件
//頁面轉圖片
npm install --save html2canvas
//圖片轉PDF
npm install jspdf --save?
2. 在需要導出的dom節點增加ref='pdf' 例如
<div ref="pdf"> 這是待轉換的頁面,點擊 <button @click="handleExport">導出</button> 點擊導出PDF</div>
3.定義導出方法
handleExport() {
? ? ? downloadPDF(this.$refs.pdf);
? ?},
4.在頁面導入?import { downloadPDF } from "@/utils/pdf.js";
pdf.js 內容如下
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
export const downloadPDF = page => {
? ? html2canvas(page).then(function (canvas) {
? ? ? ? canvas2PDF(canvas);
? ? });
};
const canvas2PDF = canvas => {
? ? let contentWidth = canvas.width;
? ? let contentHeight = canvas.height;
? ? //a4紙的尺寸[595.28,841.89],html頁面生成的canvas在pdf中圖片的寬高
? ? let imgWidth = 595.28;
? ? let imgHeight = 592.28 / contentWidth * contentHeight;
? ? //let imgHeight = 700/contentWidth * contentHeight;
? ? //一頁pdf顯示html頁面生成的canvas高度;
? ? var pageHeight = contentWidth / 592.28 * 841.89;
? ? let totalHeight = contentHeight;
? ? // 第一個參數: l:橫向 ?p:縱向
? ? // 第二個參數:測量單位("pt","mm", "cm", "m", "in" or "px")
? ? let pdf = new jsPDF("p", "pt");
? ? let position = 0;
? ? // ? pdf.addImage(
? ? // ? ? canvas.toDataURL("image/jpeg", 1.0),
? ? // ? ? "JPEG",
? ? // ? ? 0,
? ? // ? ? 0,
? ? // ? ? imgWidth,
? ? // ? ? imgHeight
? ? // ? );
? ? if (totalHeight < pageHeight) {
? ? ? ? pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, 0, imgWidth, imgHeight);
? ? } else { ? ?
? ? ? ? while (totalHeight > 0) {
? ? ? ? ? ? pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, position, imgWidth, imgHeight)
? ? ? ? ? ? totalHeight -= pageHeight;
? ? ? ? ? ? position -= 841.89;
? ? ? ? ? ? //避免添加空白頁
? ? ? ? ? ? if (totalHeight > 0) {
? ? ? ? ? ? ? ? pdf.addPage();
? ? ? ? ? ? }
? ? ? ? }
? ? }
? ? // pdf.addImage(
? ? // ? ? canvas.toDataURL("image/jpeg", 1.0),
? ? // ? ? "JPEG",
? ? // ? ? 0,
? ? // ? ? position,
? ? // ? ? imgWidth,
? ? // ? ? imgHeight
? ? // );
?
? ? pdf.save("導出.pdf");
};
5.點擊導出即可成功
總結
以上是生活随笔為你收集整理的vue 生成PDF(A4标准PDF分页)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Odoo] Report PDF 分页
- 下一篇: html5倒计时秒杀怎么做,vue 设