jq把html转换为pdf(实现逻辑:html页面生成的canvas,以图片形式在pdf中呈现)
<div class="page_box"> 页面
----------------------页面代码
<input type="button" class="save" name="save" value="保存"></div>
引入包:
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="index.css">
<script src="jquery-3.1.1.js"></script>
<script src="html2canvas.min.js"></script> // 核心包
<script src="jspdf.debug.js"></script> // 核心包
<script src="index.js"></script>
</head>
核心代码逻辑:
$("input[name='save']").click(function () {
window.pageYoffset = 0;
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
以上三行代码是核心,必须在截图之前回到顶部,否则会出现截图不全并且出现黑块的情况。
$(".form-item.margin").css("marginBottom", "200px");
$(".form-item.rules").css("paddingTop", "60px"); 这部分是页面截图之后分页截断处上下距离有差异,有些在文字中间截断了,可通过改变页面元素中的间距来调整。且一定要在截图之前,否则也是么有效果的哦
$("input[name='save']").css("display", "none");
html2canvas($(".page_box"), {
allowTaint: true,
height: $(".page_box").innerHeight(), // 一定是页面高度
scale: 2, // 提升画面质量
onrendered: function (canvas) {
let contentWidth = canvas.width;
let contentHeight = canvas.height;//一页pdf显示html页面生成的canvas高度;
let pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
let leftHeight = contentHeight;
//页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
if (leftHeight < pageHeight) {
} else {
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf'); 下载pdf,保存路径为当前项目的根目录,名字为content.pdf。
}
})
});
本文来自博客园,作者:小虾米吖~,转载请注明原文链接:https://www.cnblogs.com/LindaBlog/p/14675490.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2016-04-19 OGNL(对象图导航语言)学习