Last active
January 27, 2024 14:44
-
-
Save MS-Jahan/0315955903506253136fb524ea0b44e7 to your computer and use it in GitHub Desktop.
using jspdf from html dynamic.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// working html2pdf | |
async function download() { | |
let srcWidth = document.body.scrollWidth; | |
var margin = 18; // narrow margin - 1.27 cm (36); | |
// for mobile, use 0.5 cm (14.17) | |
// margin = 14.17; | |
var orientation = ''; | |
// if desktop, use landscape. if android or iphone, use portrait. use user agent to detect | |
if (navigator.userAgent.match(/Android/i) || | |
navigator.userAgent.match(/webOS/i) || | |
navigator.userAgent.match(/iPhone/i) || | |
navigator.userAgent.match(/iPad/i) || | |
navigator.userAgent.match(/iPod/i) || | |
navigator.userAgent.match(/BlackBerry/i) || | |
navigator.userAgent.match(/Windows Phone/i)) { | |
orientation = 'portrait'; | |
} else { | |
orientation = 'landscape'; | |
} | |
let pdf = new jsPDF({ | |
orientation: orientation, | |
unit: 'pt', | |
format: 'a4' | |
}); | |
let pWidth = pdf.internal.pageSize.width; | |
let scale = (pWidth - margin * 2) / srcWidth; | |
// console log everything | |
console.log('srcWidth', srcWidth); | |
console.log('pWidth', pWidth); | |
console.log('scale', scale); | |
// Use async/await to wait for the pdf.html() method to complete | |
await pdf.html(document.body, { | |
x: 1, | |
y: 1, | |
html2canvas: { | |
scale: scale, | |
} | |
}); | |
var pageCount = 1; | |
// keep the first page and remove the rest | |
while (pageCount < pdf.internal.getNumberOfPages()) { | |
pdf.deletePage(2); | |
// pageCount++; | |
} | |
// Open the PDF after the generation is complete | |
// window.open(pdf.output('bloburl')); | |
// save the pdf | |
pdf.save('INV/' + new Date().getFullYear() + '/' + print_data.invoice_number + '.pdf'); | |
} | |
document.addEventListener("DOMContentLoaded", function () { | |
download(); | |
}); | |
// close the page after 3 seconds | |
setTimeout(function () { | |
window.close(); | |
}, 3000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment