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

相关文章

CSS3 布局样式及其应用举例

《CSS3布局样式及其应用举例》CSS3的布局特性为前端开发者提供了无限可能,无论是Flexbox的一维布局还是Grid的二维布局,它们都能够帮助开发者以更清晰、简洁的方式实现复杂的网页布局,本文给... 目录深入探讨 css3 布局样式及其应用引言一、CSS布局的历史与发展1.1 早期布局的局限性1.2

使用animation.css库快速实现CSS3旋转动画效果

《使用animation.css库快速实现CSS3旋转动画效果》随着Web技术的不断发展,动画效果已经成为了网页设计中不可或缺的一部分,本文将深入探讨animation.css的工作原理,如何使用以及... 目录1. css3动画技术简介2. animation.css库介绍2.1 animation.cs

CSS引入方式和选择符的讲解和运用小结

《CSS引入方式和选择符的讲解和运用小结》CSS即层叠样式表,是一种用于描述网页文档(如HTML或XML)外观和格式的样式表语言,它主要用于将网页内容的呈现(外观)和结构(内容)分离,从而实现... 目录一、前言二、css 是什么三、CSS 引入方式1、行内样式2、内部样式表3、链入外部样式表四、CSS 选

使用雪花算法产生id导致前端精度缺失问题解决方案

《使用雪花算法产生id导致前端精度缺失问题解决方案》雪花算法由Twitter提出,设计目的是生成唯一的、递增的ID,下面:本文主要介绍使用雪花算法产生id导致前端精度缺失问题的解决方案,文中通过代... 目录一、问题根源二、解决方案1. 全局配置Jackson序列化规则2. 实体类必须使用Long封装类3.

C#实现查找并删除PDF中的空白页面

《C#实现查找并删除PDF中的空白页面》PDF文件中的空白页并不少见,因为它们有可能是作者有意留下的,也有可能是在处理文档时不小心添加的,下面我们来看看如何使用Spire.PDFfor.NET通过C#... 目录安装 Spire.PDF for .NETC# 查找并删除 PDF 文档中的空白页C# 添加与删

Nginx部署React项目时重定向循环问题的解决方案

《Nginx部署React项目时重定向循环问题的解决方案》Nginx在处理React项目请求时出现重定向循环,通常是由于`try_files`配置错误或`root`路径配置不当导致的,本文给大家详细介... 目录问题原因1. try_files 配置错误2. root 路径错误解决方法1. 检查 try_f

C#实现高性能Excel百万数据导出优化实战指南

《C#实现高性能Excel百万数据导出优化实战指南》在日常工作中,Excel数据导出是一个常见的需求,然而,当数据量较大时,性能和内存问题往往会成为限制导出效率的瓶颈,下面我们看看C#如何结合EPPl... 目录一、技术方案核心对比二、各方案选型建议三、性能对比数据四、核心代码实现1. MiniExcel

在React聊天应用中实现图片上传功能

《在React聊天应用中实现图片上传功能》在现代聊天应用中,除了文字和表情,图片分享也是一个重要的功能,本文将详细介绍如何在基于React的聊天应用中实现图片上传和预览功能,感兴趣的小伙伴跟着小编一起... 目录技术栈实现步骤1. 消息组件改造2. 图片预览组件3. 聊天输入组件改造功能特点使用说明注意事项

一文详解如何在Vue3中封装API请求

《一文详解如何在Vue3中封装API请求》在现代前端开发中,API请求是不可避免的一部分,尤其是与后端交互时,下面我们来看看如何在Vue3项目中封装API请求,让你在实现功能时更加高效吧... 目录为什么要封装API请求1. vue 3项目结构2. 安装axIOS3. 创建API封装模块4. 封装API请求

全解析CSS Grid 的 auto-fill 和 auto-fit 内容自适应

《全解析CSSGrid的auto-fill和auto-fit内容自适应》:本文主要介绍了全解析CSSGrid的auto-fill和auto-fit内容自适应的相关资料,详细内容请阅读本文,希望能对你有所帮助... css  Grid 的 auto-fill 和 auto-fit/* 父元素 */.gri