vue页面上是按钮点击,这个方法就是下面js的方法,pdf是要导出的范围div的属性ref=pdf
toPDF{
downloadPDF(this.$refs.pdf)
}
普通的vue导出PDF
参考Vue页面生成PDF的方法_vue 生成pdf-CSDN博客
导出PDF
export const downloadPDF = page => {
html2canvas(page).then(function(canvas) {
canvas2PDF(canvas);
});
};
const canvas2PDF = canvas => {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = 814.89/contentWidth * contentHeight;
// 第一个参数: l:横向 p:纵向
// 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
let pdf = new jsPDF("p", "pt");
pdf.addImage(
canvas.toDataURL("image/jpeg", 1.0),
"JPEG",
0,
0,
imgWidth,
imgHeight
);
pdf.save("报价单.pdf");
};
附带其他条件
export const downloadPDF = async (page) => {
const pdf = new jsPDF('p', 'mm', 'a4');
const pageWidth = 210; // A4 width in mm
const pageHeight = 297; // A4 height in mm
const margin = 10;
const contentWidth = pageWidth - 2 * margin;
let currentPosition = 0;
const addPageToPDF = (canvas, isFirstPage) => {
const imgData = canvas.toDataURL('image/jpeg', 1.0);
const imgProps = pdf.getImageProperties(imgData);
const imgHeight = (imgProps.height * contentWidth) / imgProps.width;
if (!isFirstPage) {
pdf.addPage();
}
pdf.addImage(imgData, 'JPEG', margin, margin, contentWidth, imgHeight);
currentPosition += imgHeight + margin; // Update current position
};
const processCanvas = (canvas) => {
const totalHeight = canvas.height;
const a4HeightPx = Math.floor((pageHeight * canvas.width) / pageWidth);
let remainingHeight = totalHeight;
let isFirstPage = true;
while (remainingHeight > 0) {
const pageCanvas = document.createElement('canvas');
const pageCtx = pageCanvas.getContext('2d');
pageCanvas.width = canvas.width;
pageCanvas.height = Math.min(a4HeightPx, remainingHeight);
pageCtx.clearRect(0, 0, pageCanvas.width, pageCanvas.height);
pageCtx.drawImage(canvas, 0, currentPosition, canvas.width, pageCanvas.height, 0, 0, canvas.width, pageCanvas.height);
addPageToPDF(pageCanvas, isFirstPage);
remainingHeight -= a4HeightPx;
isFirstPage = false;
}
pdf.save('报价单.pdf');
};
//当点击导出按钮的时候class为.print, .muban的div隐藏
const hideElements = () => {
document.querySelectorAll('.print, .muban').forEach(el => el.style.display = 'none');
};
const showElements = () => {
document.querySelectorAll('.print, .muban').forEach(el => el.style.display = '');
};
hideElements();
try {
const canvas = await html2canvas(page, {
useCORS: true,
scale: window.devicePixelRatio
});
processCanvas(canvas);
} catch (err) {
console.error(err);
} finally {
showElements();
}
};
重点参考这位大佬直接完美运行