html2canvas+jsPDF导出超长网页的PDF

2024-01-03 06:52

本文主要是介绍html2canvas+jsPDF导出超长网页的PDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

项目需求:有一个网页大概60000px的高度,现在需要导出为PDF


index.vue

<template><div class="ctn"><div class="pdf-ctn"><div class="pdf-panel" ><div class="pdf-inside-panel" id="myList"><div v-for="(item, index) in 3000" :key="index" style="height: 20px">{{index}}---我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我是测试我的高度{{(index+1)*20}}</div></div></div><divclass="pdf-header"style="font-weight: bold;padding: 15px 8px;width: 100%;border-bottom: 1px solid rgba(0, 0, 0, 0.85);color: rgba(0, 0, 0, 0.85);position: fixed;top: -100vh;">页头</div><divclass="pdf-footer"style="font-weight: bold;padding: 15px 8px;width: 100%;border-top: 1px solid rgba(0, 0, 0, 0.85);position: fixed;top: -100vh;"><divstyle="display: flex;justify-content: center;align-items: center;padding-top: 5px;">我是页尾</div><divstyle="display: flex;justify-content: center;align-items: center;margin-top: 20px;">第<div class="pdf-footer-page"></div>页 / 第<div class="pdf-footer-page-count"></div>页</div></div></div><div><a-buttonstyle="top: 50px; left: 1450px; position: fixed"@click="handleOutput">测试导出</a-button></div></div>
</template><script>
import { message } from "ant-design-vue";
import { outCanvas } from "../scroll";
export default {name: "HelloWorld",props: {msg: String,},methods: {async handleOutput() {const element = document.querySelector("#myList");const header = document.querySelector(".pdf-header");const footer = document.querySelector(".pdf-footer");await outCanvas(element);let endTime = new Date().getTime();let timeElapsed = endTime - startTime; // 获取时间差(毫秒)console.log(`函数运行时间: ${timeElapsed} 毫秒`);} catch (error) {console.log(error)message.error(typeof error === "string" ? error : JSON.stringify(error));}},}
};
</script><!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.ctn {.pdf-ctn {width: 1300px;.pdf-panel {position: relative;}}
}
</style>

JS

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import { message } from 'ant-design-vue';// jsPDFs实例
let pdf = new jsPDF({unit: 'pt',format: 'a4',orientation: 'p',// format: [550, 550]
});// 对图片进行等比缩放
function resizeImage(imgWidth, imgHeight, maxWidth = 590) {// 计算当前图片的宽高比const ratio = imgWidth / imgHeight;// 如果最大宽度小于当前宽度,则按最大宽度进行缩放if (imgWidth > maxWidth) {return {newWidth: maxWidth,newHeight: maxWidth / ratio};} else { // 否则,图片本身就在允许的最大宽度内,不需要缩放return {newWidth: imgWidth,newHeight: imgHeight};}
}async function toCanvas(element,scrolledHeight=0,viewHeight=window.innerHeight) {// 放大倍率const scaleRatio = window.devicePixelRatio * 2const canvas = await html2canvas(element, {scale: scaleRatio,useCORS: true,width: document.querySelector("#myList").scrollWidth,height: Math.min(element.scrollHeight,  viewHeight),windowWidth: document.querySelector("#myList").scrollWidth,windowHeight: document.querySelector("#myList").scrollHeight,x: 0,y: scrolledHeight,})let canvasImg = canvas.toDataURL("image/jpeg",1);return { width:canvas.width, height:canvas.height, data: canvasImg}
}// 循环生成PDF
let pdfImgTop = 0
let pageHeight = 0
async function loopGeneratePDF(targetElement, scrolledHeight = 0, viewHeight =window.innerHeight) {const A4_HEIGHT = 900if (scrolledHeight >= targetElement.scrollHeight) {message.success("生成PDF成功");return;}const { data: imgData, height, width } = await toCanvas(targetElement, scrolledHeight, viewHeight);// console.log("图片",imgData)const { newWidth, newHeight } = resizeImage(width, height);pdf.addImage(imgData, 'JPEG', 0, pdfImgTop, newWidth, newHeight);const pages = pdf.internal.getNumberOfPages()message.success(`生成第${pages}页`)// 下一次需要截取的开始高度scrolledHeight += Math.floor(height / 2);pdfImgTop += newHeight;// 如果当前页内容不足一页A4纸的高度,则递归调用并调整视图高度if (A4_HEIGHT>scrolledHeight) {// 剩余页面的高度pageHeight = A4_HEIGHT - scrolledHeight;return loopGeneratePDF(targetElement, scrolledHeight, pageHeight);}else {if(targetElement.scrollHeight - scrolledHeight > A4_HEIGHT || pdfImgTop>A4_HEIGHT){pdf.addPage();pdfImgTop = 10;}return loopGeneratePDF(targetElement, scrolledHeight-20);}}export const outCanvas = async function (targetElement) {if (!(targetElement instanceof HTMLElement)) {return;}await loopGeneratePDF(targetElement,0,window.innerHeight)return pdf.save('test.pdf');
}

这篇关于html2canvas+jsPDF导出超长网页的PDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/564847

相关文章

HTML5的input标签的`type`属性值详解和代码示例

《HTML5的input标签的`type`属性值详解和代码示例》HTML5的`input`标签提供了多种`type`属性值,用于创建不同类型的输入控件,满足用户输入的多样化需求,从文本输入、密码输入、... 目录一、引言二、文本类输入类型2.1 text2.2 password2.3 textarea(严格

SpringBoot返回文件让前端下载的几种方式

《SpringBoot返回文件让前端下载的几种方式》文章介绍了开发中文件下载的两种常见解决方案,并详细描述了通过后端进行下载的原理和步骤,包括一次性读取到内存和分块写入响应输出流两种方法,此外,还提供... 目录01 背景02 一次性读取到内存,通过响应输出流输出到前端02 将文件流通过循环写入到响应输出流

Python结合Free Spire.PDF for Python实现PDF页面旋转

《Python结合FreeSpire.PDFforPython实现PDF页面旋转》在日常办公或文档处理中,我们经常会遇到PDF页面方向错误的问题,本文将分享如何用Python结合FreeSpir... 目录基础实现:单页PDF精准旋转完整代码代码解析进阶操作:覆盖多场景旋转需求1. 旋转指定角度(90/27

SpringBoot+Vue3整合SSE实现实时消息推送功能

《SpringBoot+Vue3整合SSE实现实时消息推送功能》在日常开发中,我们经常需要实现实时消息推送的功能,这篇文章将基于SpringBoot和Vue3来简单实现一个入门级的例子,下面小编就和大... 目录前言先大概介绍下SSE后端实现(SpringBoot)前端实现(vue3)1. 数据类型定义2.

使用C#实现将RTF转换为PDF

《使用C#实现将RTF转换为PDF》RTF(RichTextFormat)是一种通用的文档格式,允许用户在不同的文字处理软件中保存和交换格式化文本,下面我们就来看看如何使用C#实现将RTF转换为PDF... 目录Spire.Doc for .NET 简介安装 Spire.Doc代码示例处理异常总结RTF(R

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

使用Python在PDF中绘制多种图形的操作示例

《使用Python在PDF中绘制多种图形的操作示例》在进行PDF自动化处理时,人们往往首先想到的是文本生成、图片嵌入或表格绘制等常规需求,然而在许多实际业务场景中,能够在PDF中灵活绘制图形同样至关重... 目录1. 环境准备2. 创建 PDF 文档与页面3. 在 PDF 中绘制不同类型的图形python

使用C#导出Excel数据并保存多种格式的完整示例

《使用C#导出Excel数据并保存多种格式的完整示例》在现代企业信息化管理中,Excel已经成为最常用的数据存储和分析工具,从员工信息表、销售数据报表到财务分析表,几乎所有部门都离不开Excel,本文... 目录引言1. 安装 Spire.XLS2. 创建工作簿和填充数据3. 保存为不同格式4. 效果展示5

使用Python实现在PDF中添加、导入、复制、移动与删除页面

《使用Python实现在PDF中添加、导入、复制、移动与删除页面》在日常办公和自动化任务中,我们经常需要对PDF文件进行页面级的编辑,使用Python,你可以轻松实现这些操作,而无需依赖AdobeAc... 目录1. 向 PDF 添加空白页2. 从另一个 PDF 导入页面3. 删除 PDF 中的页面4. 在

前端Visual Studio Code安装配置教程之下载、汉化、常用组件及基本操作

《前端VisualStudioCode安装配置教程之下载、汉化、常用组件及基本操作》VisualStudioCode是微软推出的一个强大的代码编辑器,功能强大,操作简单便捷,还有着良好的用户界面,... 目录一、Visual Studio Code下载二、汉化三、常用组件1、Auto Rename Tag2