Untitled
unknown
javascript
a year ago
2.1 kB
5
Indexable
// Wait for the document to be fully loaded document.addEventListener("DOMContentLoaded", function () { // Attach the click event to the button with id "GetFile" document .getElementById("GetFile") .addEventListener("click", async function () { try { // Check if PDF-lib is available if (typeof PDFLib === "undefined") { // If not, dynamically load the PDF-lib script const script = document.createElement("script"); script.src = "https://cdn.jsdelivr.net/npm/pdf-lib@1.16.0/dist/pdf-lib.js"; script.type = "text/javascript"; script.onload = function () { // Once the script is loaded, execute the code that depends on PDF-lib createAndDownloadPDF(); }; // Append the script to the document's head document.head.appendChild(script); } else { // If PDF-lib is already available, directly execute the code createAndDownloadPDF(); } } catch (error) { console.error("Error:", error); } }); }); // Function to create and download PDF async function createAndDownloadPDF() { try { // Create a new PDF document const pdfDoc = await PDFLib.PDFDocument.create(); // Add a new page to the document const page = pdfDoc.addPage(); // Add text to the page const text = "This is my file PDF"; page.drawText(text, { x: 50, y: 500 }); // Save the PDF document as a blob const pdfBytes = await pdfDoc.save(); // Create a URL from the blob const pdfUrl = URL.createObjectURL( new Blob([pdfBytes], { type: "application/pdf" }) ); // Create an <a> element for downloading const a = document.createElement("a"); a.href = pdfUrl; a.download = "myfile.pdf"; document.body.appendChild(a); // Trigger the click event to initiate the download a.click(); // Remove the <a> element from the document document.body.removeChild(a); // Release the temporary URL URL.revokeObjectURL(pdfUrl); } catch (error) { console.error("Error:", error); } }
Editor is loading...
Leave a Comment