Nuxtjs project.
printPDF() {
// Initialize the PDF.
let pdf = new jsPDF('p', 'in', [8.5, 11], false);
let totalPage=0
this.userInfos.forEach((r, i) => {
//userInfos is to get user count
const contentPrint = document.getElementById('contentPrint-' + i);
html2canvas(contentPrint, {
scale: 2, useCORS: true, allowTaint: true, scrollY: 0
})
.then((canvas) => {
const image = {type: 'jpeg', quality: 1};
const margin = [0.5, 0.5];
const filename = 'e-ticket';
let imgWidth = 8.5;
let pageHeight = 11;
let innerPageWidth = imgWidth - margin[0] * 2;
let innerPageHeight = pageHeight - margin[1] * 2;
// Calculate the number of pages.
let pxFullHeight = canvas.height;
let pxPageHeight = Math.floor(canvas.width * (pageHeight / imgWidth));
let nPages = Math.ceil(pxFullHeight / pxPageHeight);
totalPage+=nPages
console.log("nPages", nPages)
// Define pageHeight separately so it can be trimmed on the final page.
pageHeight = innerPageHeight;
// Create a one-page canvas to split up the full image.
let pageCanvas = document.createElement('canvas');
let pageCtx = pageCanvas.getContext('2d');
pageCanvas.width = canvas.width;
pageCanvas.height = pxPageHeight;
for (let page = 0; page <= nPages; page++) {
// Trim the final page to reduce file size.
if (page === nPages - 1 && pxFullHeight % pxPageHeight !== 0) {
pageCanvas.height = pxFullHeight % pxPageHeight;
pageHeight = (pageCanvas.height * innerPageWidth) / pageCanvas.width;
}
// Display the page.
let w = pageCanvas.width;
let h = pageCanvas.height;
pageCtx.fillStyle = 'white';
pageCtx.fillRect(0, 0, w, h);
pageCtx.drawImage(canvas, 0, page * pxPageHeight, w, h, 0, 0, w, h);
// Add the page to the PDF.
if (page > 0) pdf.addPage();
// console.log("pdf",page)
let imgData = pageCanvas.toDataURL('image/' + image.type, image.quality);
pdf.addImage(imgData, image.type, margin[1], margin[0], innerPageWidth, pageHeight);
}
});
});
setTimeout(() => {
pdf.deletePage(totalPage+1) //delete last empty page
window.print()
pdf.save("filename" + '.pdf')
}, 3000)
},
In my project, I have 2 buttons. The first is to create Pdf, the second button is to print documents. Many user's information can be seen on my web page separately and when I wanted I can print them separately. This code area is to print pdf and it splits pages also. For example, if there 2 users and the first user's info can fill in 1.5 pages and the second user's info can fill in 3.2 pages, it fills these areas separately and shows them separately.
I want to do the same logic with Print also. When the user clicked Print I want to show user information separately, one under the other, and print them separately.
But here I cant separate pages when I wanted to print them. For example, all pages are a total of 6 pages but when I wanted to print it shows 4 pages because it fills empty places also.