LẬP TRÌNH WEB HTML - CSS - JAVA SCRIPT
BÀI 23: CHUYỂN HTML THÀNH FILE VÀ DOWNLOAD PDF TRONG WEB JS
Chèn thư viện này lên thẻ <head> trong HTML: nguồn
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js" integrity="sha512-GsLlZN/3F2ErC5ifS5QtgpiJtWd43JWSuIgh7mbzZ8zBps+dvLusV+eNQATqgA/HdeKFVgA5v3S/cIrLF7QnIg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Tạo một nút để in dữ liệu từ HTML + tạo một <div> bao quanh dữ liệu cần tạo PDF (ví dự div đó có class là container)
Tạo sự kiện click button (ví dụ nút có id là btn-print-bbgh)
Tạo biến chứa định dạng file HTML. Tham khảo thêm tại: https://github.com/eKoopmans/html2pdf.js#options
Tạo hàm để thay đổi tên file theo ngày tạo.
let btn_print_bbgh = document.getElementById('btn-print-bbgh');
btn_download_bbgh.addEventListener('click', () => {
const element = document.querySelector('.container');
html2pdf().set(opt).from(element).save();
});
var opt = {
margin: 0,
filename: `Biên bản giao hàng ${DayInFileNamePDF()}.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, width: 860},
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
};
function DayInFileNamePDF() {
var now = new Date();
return now.getDate() + "-" + (now.getMonth() + 1) + "-" + now.getFullYear();
}