Node.js中基于pdf-lib实现PDF24小时自动过期的方案咨询
Great question—adding a local expiry date to a PDF (that triggers directly on the user’s device, no server checks needed) is totally feasible, even though pdf-lib doesn’t have this feature built-in. The solution leans on PDF’s native support for JavaScript actions, which run automatically when the document is opened. Here’s how to implement it with your existing code:
Step-by-Step Implementation
We’ll add a JavaScript snippet that checks the current date against your 24-hour expiry window when the PDF opens. If the user opens it after the deadline, the script shows a warning and closes the document. We’ll also add a visible expiry notice as a fallback for readers that don’t support JavaScript.
Here’s your modified code:
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib' const createExpiringPDF = async () => { const pdfDoc = await PDFDocument.create() const timesRomanFont = await pdfDoc.embedFont(StandardFonts.TimesRoman) const page = pdfDoc.addPage() const { width, height } = page.getSize() const fontSize = 30 // Add visible expiry notice (for JS-unfriendly readers) page.drawText(`This PDF expires in 24 hours. Generated on: ${new Date().toLocaleString()}`, { x: 50, y: height - 6 * fontSize, size: 14, font: timesRomanFont, color: rgb(0.8, 0, 0), }) page.drawText('Creating PDFs in JavaScript would be great if the PDF had an expiry date!', { x: 50, y: height - 4 * fontSize, size: fontSize, font: timesRomanFont, color: rgb(0, 0.53, 0.71), }) // Calculate 24-hour expiry (use UTC to avoid timezone mismatches) const expiryDate = new Date() expiryDate.setHours(expiryDate.getHours() + 24) const expiryTimestamp = expiryDate.getTime() // JavaScript to run on document open const expiryScript = ` const currentTime = new Date().getTime(); const expiryTime = ${expiryTimestamp}; if (currentTime > expiryTime) { app.alert("This PDF has expired and can no longer be viewed.", 1); this.closeDoc(); } ` // Attach the script to the document's open event pdfDoc.addJavaScript('OpenAction', expiryScript) const pdfBytes = await pdfDoc.save() return pdfBytes } // Example: Save or send the PDF to the client createExpiringPDF().then(pdfBytes => { // Handle the PDF bytes (e.g., write to file, send as HTTP response) })
Key Considerations
- JavaScript Support: Not all PDF readers handle JavaScript (e.g., some mobile viewers, lightweight tools). The visible text notice ensures users still get expiry info even if the script doesn’t run.
- Timezone Safety: Using UTC timestamps (
getTime()) prevents issues where your server’s timezone differs from the user’s device. - Limitations: This won’t block tech-savvy users from disabling JS in their reader or editing the PDF to remove the script. For stricter control, you’d need server-side validation (like signed PDFs that check in with your server on open), but that’s a more complex workflow.
- Alternatives: If you need more robust features, you could use Node.js wrappers for tools like Ghostscript, or generate PDFs via headless browsers with expiry rules—but the JavaScript method is the simplest for local, client-side expiry.
内容的提问来源于stack exchange,提问作者Luke Brown

