Untitled
unknown
javascript
2 years ago
1.6 kB
7
Indexable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Create and Download PDF File</title>
<script src="https://cdn.jsdelivr.net/npm/pdf-lib@1.16.0/dist/pdf-lib.js"></script>
</head>
<body>
<button type="button" id="GetFile">Download</button>
<script>
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);
}
});
</script>
</body>
</html>
Editor is loading...
Leave a Comment