Untitled

 avatar
unknown
javascript
2 years ago
1.1 kB
8
Indexable
document.getElementById("GetFile").addEventListener("click", async function () {
	try {
		// Tạo một tài liệu PDF mới
		const pdfDoc = await PDFLib.PDFDocument.create();

		// Thêm một trang mới vào tài liệu
		const page = pdfDoc.addPage();

		// Thêm văn bản vào trang
		const text = "This is my file PDF";
		page.drawText(text, { x: 50, y: 500 });

		// Tạo blob từ tài liệu PDF
		const pdfBytes = await pdfDoc.save();

		// Tạo đường dẫn URL từ blob
		const pdfUrl = URL.createObjectURL(
			new Blob([pdfBytes], { type: "application/pdf" })
		);

		// Tạo một thẻ <a> để tải xuống
		const a = document.createElement("a");
		a.href = pdfUrl;
		a.download = "myfile.pdf";
		document.body.appendChild(a);

		// Kích hoạt sự kiện click để tải xuống
		a.click();

		// Loại bỏ thẻ <a> khỏi tài liệu
		document.body.removeChild(a);

		// Giải phóng đường dẫn URL tạm thời
		URL.revokeObjectURL(pdfUrl);
	} catch (error) {
		console.error("Error:", error);
	}
});
Editor is loading...
Leave a Comment