前端把dom页面转为pdf文件下载和弹窗预览

需求

把dom元素生成的页面生成pdf文件,实现下载和预览pdf文件。

解决方案

利用html2canvas和jsPDF实现把页面转为pdf文件。

具体实现步骤

1、给需要转换为pdf文件的dom增加id

例如:

javascript 复制代码
<div id="pdf-box">
// 此处为你的页面内容
</div>

2、在utils公共工具函数文件中引入html2canvas和jsPDF

javascript 复制代码
import dayjs from "dayjs";
import html2canvas from "html2canvas";

3、创建具体实现方法函数htmlToPDF

javascript 复制代码
/** 将dom页面转为pdf预览 */
export const htmlToPDF = async (htmlId: string, title: string, bgColor = "#fff") => {
  const loading = ElLoading.service({
    lock: true,
    text: '导出pdf中...',
    background: "rgba(0, 0, 0, 0.7)",
  });
  let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement
  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;
  /*
   根据自身业务需求  是否在此处键入下方水印代码
  */
  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();
      }
  }
  
  loading.close()
  // PDF.save(title + ".pdf"); // 如果需要下载pdf文件则使用这行代码
  let pdfUrl = window.URL.createObjectURL(new Blob([PDF.output('blob')], { type: "application/pdf" })) || ''
  return pdfUrl
}

4、调用htmlToPDF方法

javascript 复制代码
const pdfUrl = htmlToPDF("pdf-box", 'xxx.pdf')
window.open(pdfUrl, "_blank");

备注

以上便是完整的利用html2canvas和jsPDF实现把页面转为pdf文件实现下载和预览的功能,不足的地方请多指教。

相关推荐
一拳不是超人10 分钟前
Electron主窗口弹框被WebContentView遮挡?独立WebContentView弹框方案详解!
前端·javascript·electron
anyup20 分钟前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
雮尘1 小时前
如何在非 Claude IDE (TARE、 Cursor、Antigravity 等)下使用 Agent Skills
前端·agent·ai编程
icebreaker1 小时前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker1 小时前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
wuhen_n1 小时前
代码生成:从AST到render函数
前端·javascript·vue.js
Lee川1 小时前
从异步迷雾到优雅流程:JavaScript异步编程与内存管理的现代化之旅
javascript·面试
喝咖啡的女孩1 小时前
浏览器前端指南
前端
wuhen_n1 小时前
AST转换:静态提升与补丁标志
前端·javascript·vue.js
喝咖啡的女孩1 小时前
浏览器前端指南-2
前端