通过html2canvas实现:
注意:html2canvas 截图只能截到当前屏幕可视范围内的内容,滚动到屏幕以外的截取不到
在index.html中通过引入js文件
<script src="https://cdn.bootcss.com/jspdf/1.5.3/jspdf.debug.js"></script>
<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
获取dom元素,导出pdf
downloadWord() {
html2canvas(
//转换id为export_content的div中的所有内容为pdf
document.getElementById("export_content"),
{
dpi: 172,//导出pdf清晰度
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;
//pdf页面偏移
let position = 0;
//html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89])
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一页显示的范围,无需分页
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 -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
},
//背景设为白色(默认为黑色)
background: "#fff"
})
}
通过dom-to-image实现:
注意:dom-to-image 截图生成多页pdf时,分页处文字和图片会被直接截成两部分
在index.html中通过引入js文件
<script src="https://cdn.bootcss.com/jspdf/1.5.3/jspdf.debug.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/dom-to-image/2.6.0/dom-to-image.min.js"></script>
downloadWord() {
let dom = document.getElementById("export_content");
dom.style.backgroundColor = "#fff" //背景设为白色(默认为透明)
domtoimage.toPng(dom)
.then(function (pageData) {
let contentWidth = dom.clientWidth;
let contentHeight = dom.clientHeight;
//一页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 pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
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 -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save('content.pdf');
});
}
参考:
https://www.cnblogs.com/CTXXCH/p/6721893.html
https://blog.csdn.net/qq_29042647/article/details/107731889