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

相关文章

springboot集成easypoi导出word换行处理过程

《springboot集成easypoi导出word换行处理过程》SpringBoot集成Easypoi导出Word时,换行符n失效显示为空格,解决方法包括生成段落或替换模板中n为回车,同时需确... 目录项目场景问题描述解决方案第一种:生成段落的方式第二种:替换模板的情况,换行符替换成回车总结项目场景s

Vue和React受控组件的区别小结

《Vue和React受控组件的区别小结》本文主要介绍了Vue和React受控组件的区别小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学... 目录背景React 的实现vue3 的实现写法一:直接修改事件参数写法二:通过ref引用 DOMVu

oracle 11g导入\导出(expdp impdp)之导入过程

《oracle11g导入导出(expdpimpdp)之导入过程》导出需使用SEC.DMP格式,无分号;建立expdir目录(E:/exp)并确保存在;导入在cmd下执行,需sys用户权限;若需修... 目录准备文件导入(impdp)1、建立directory2、导入语句 3、更改密码总结上一个环节,我们讲了

Java实现将HTML文件与字符串转换为图片

《Java实现将HTML文件与字符串转换为图片》在Java开发中,我们经常会遇到将HTML内容转换为图片的需求,本文小编就来和大家详细讲讲如何使用FreeSpire.DocforJava库来实现这一功... 目录前言核心实现:html 转图片完整代码场景 1:转换本地 HTML 文件为图片场景 2:转换 H

C#使用Spire.Doc for .NET实现HTML转Word的高效方案

《C#使用Spire.Docfor.NET实现HTML转Word的高效方案》在Web开发中,HTML内容的生成与处理是高频需求,然而,当用户需要将HTML页面或动态生成的HTML字符串转换为Wor... 目录引言一、html转Word的典型场景与挑战二、用 Spire.Doc 实现 HTML 转 Word1

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法

Vue3绑定props默认值问题

《Vue3绑定props默认值问题》使用Vue3的defineProps配合TypeScript的interface定义props类型,并通过withDefaults设置默认值,使组件能安全访问传入的... 目录前言步骤步骤1:使用 defineProps 定义 Props步骤2:设置默认值总结前言使用T

基于C#实现PDF转图片的详细教程

《基于C#实现PDF转图片的详细教程》在数字化办公场景中,PDF文件的可视化处理需求日益增长,本文将围绕Spire.PDFfor.NET这一工具,详解如何通过C#将PDF转换为JPG、PNG等主流图片... 目录引言一、组件部署二、快速入门:PDF 转图片的核心 C# 代码三、分辨率设置 - 清晰度的决定因

Python自动化处理PDF文档的操作完整指南

《Python自动化处理PDF文档的操作完整指南》在办公自动化中,PDF文档处理是一项常见需求,本文将介绍如何使用Python实现PDF文档的自动化处理,感兴趣的小伙伴可以跟随小编一起学习一下... 目录使用pymupdf读写PDF文件基本概念安装pymupdf提取文本内容提取图像添加水印使用pdfplum

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装