1、导出pdf,先下载两个库
//第一个:将页面html转换成图片
npm install --save html2canvas
//第二个:将图片生成pdf
npm install jspdf --save
新增一个文件exportPDF,复制代码。
/*
* @Description: 导出pdf文件
* @Autor: lcz
* @Date: 2022-09-24 18:03:21
* @LastEditors: lcz
* @LastEditTime: 2022-10-08 10:02:37
*/
// 导出页面为PDF格式
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
export function getPdf(title, id) {
let dom = document.querySelectorAll('.welcome_box');
let scale = dom ? 1 / dom[0].style.transform.replace('scale(', '').replace(')', '') : 1
html2Canvas(document.querySelector(`#${id}`), {
allowTaint: true,
scale,
onclone: function (documentClone) {
let cloneDom = documentClone.querySelectorAll('.welcome_box')
cloneDom[0].style.transform = 'scale(1)';
}
}).then(function (canvas) {
// document.querySelector(`.Pagebox`).appendChild(canvas);
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = (contentWidth / 592.28) * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 555.28;
let imgHeight = (592.28 / contentWidth) * contentHeight;
let pageData = canvas.toDataURL("image/jpeg", 1.0);
let PDF = new JsPDF("", "pt", "a4");
if (leftHeight < pageHeight) {
PDF.addImage(pageData, "JPEG", 20, 20, 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(title + ".pdf");
});
}
在需要导出文件的地方,引入js文件函数
import { getPdf } from "../../utils/exportPdf";
在方法中调用函数,导出内容应该是一个id(body_content)。
exportPDF() {
getPdf("报告", "body_content");
},
此方法导出
是先将html转换成图片,再转换成pdf的,由于导出必须是一个id,且必须是屏幕上的内容,涉及到展示的内容和人导出的内容不一样,所以做了id浮动到屏幕外面,保留在页面上进行导出pdf。
后来导出出现了导出内容参差不齐的情况,以上js代码也已经解决
原来的参差不齐
排列整齐之后的样子
2、调用浏览器进行导出pdf,但是需要自己调整打印参数
win_print() {
document.title = "";
window.print();
}