最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

vue3 如何將頁面生成 pdf 導(dǎo)出

2023-07-18 16:05 作者:蘇軾徒弟  | 我要投稿

原文鏈接:https://fe32.top/articles/vue20003/

前言

最近工作中有需要將一些前端頁面(如報表頁面等)導(dǎo)出為pdf的需求,博主采用的是html2Canvas + jspdf

步驟

1.引入兩個依賴

BASH

npm i html2canvasnpm i jspdf

點擊?jsPDF GitHub、jsPDF 文檔?查看關(guān)于jsPDF更多信息。

2.在utils文件夾下新建html2pdf.ts文件

Ts

import html2canvas from 'html2canvas';import jsPDF from 'jspdf'export const htmlToPDF = async (htmlId: string, title: string = "報表", bgColor = "#fff") => { ? ?let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement ? ?pdfDom.style.padding = '0 10px !important' ? ?const A4Width = 595.28; ? ?const A4Height = 841.89; ? ?let canvas = await html2canvas(pdfDom, { ? ? ? ?scale: 2, ? ? ? ?useCORS: true, ? ? ? ?backgroundColor: bgColor, ? ?}); ? ?let pageHeight = (canvas.width / A4Width) * A4Height; ? ?let leftHeight = canvas.height; ? ?let position = 0; ? ?let imgWidth = A4Width; ? ?let imgHeight = (A4Width / canvas.width) * canvas.height; ? ?/* ? ? 根據(jù)自身業(yè)務(wù)需求 ?是否在此處鍵入下方水印代碼 ? ?*/ ? ?let pageData = canvas.toDataURL("image/jpeg", 1.0); ? ?let PDF = new jsPDF("p", 'pt', 'a4'); ? ?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 -= A4Height; ? ? ? ? ? ?if (leftHeight > 0) PDF.addPage(); ? ? ? ?} ? ?} ? ?PDF.save(title + ".pdf");}

如果你想給pdf加上水印,則添加下面這段代碼:

Ts

const ctx: any = canvas.getContext('2d');ctx.textAlign = 'center';ctx.textBaseline = 'middle';ctx.rotate((20 * Math.PI) / 180);ctx.font = '20px Microsoft Yahei';ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';for (let i = canvas.width * -1; i < canvas.width; i += 240) { ? ?for (let j = canvas.height * -1; j < canvas.height; j += 200) { ? ? ? ?// 填充文字,x 間距, y 間距 ? ? ? ?ctx.fillText('水印名', i, j); ? ?}}

3.在目標頁面引入方法即可

Ts

import { htmlToPDF } from '@/utils/html2pdf'

HTML

<div id="test-id" style="padding: 20px 0;"> ? ?<div style="background: #000;width: 100px;height: 100px;margin: auto;"></div> ? ?<p>test</p> ? ?<p>test</p> ? ?<p>test</p> ? ?<p>test</p> ? ?<p>test</p> ? ?<p>test</p> ? ?<p>test</p></div><button @click="() => htmlToPDF('test-id','test pdf')">導(dǎo)出</button>

效果如下:

參考

  • jsPDF

  • Vue3 導(dǎo)出 pdf 方案

  • vue頁面生成pdf且避免分頁截斷處理

  • 實現(xiàn)前端頁面局部轉(zhuǎn) pdf 及 打印 加分頁防止內(nèi)容截斷

  • 純前端生成 PDF 之 jspdf 使用及注意事項

  • jsPDF + html2canvas A4 分頁截斷 完美解決方案(含代碼 + 案例)


vue3 如何將頁面生成 pdf 導(dǎo)出的評論 (共 條)

分享到微博請遵守國家法律
韶关市| 华宁县| 镇康县| 仁寿县| 湘西| 平江县| 呈贡县| 台南市| 稷山县| 平乡县| 隆回县| 河曲县| 襄樊市| 万载县| 封开县| 略阳县| 东平县| 肇庆市| 衡阳县| 巴彦淖尔市| 颍上县| 武平县| 邯郸县| 岳池县| 泌阳县| 离岛区| 巴青县| 温泉县| 抚州市| 洪洞县| 北辰区| 海阳市| 定南县| 东阳市| 马鞍山市| 莱西市| 平乐县| 高尔夫| 耿马| 秦皇岛市| 桐乡市|