我必须为 Node.js 项目生成 PDF/A-3 文件。我希望能够从头开始生成 PDF/A-3 文件或将现有文件转换为 PDF/A-3。
到目前为止,我还没有找到简单/直接的方法来做到这一点。
我检查了 pdfkit、jsPDF、pdf-lib 等库...但它们似乎没有提供获取 PDF/A-3 文件的简单接口。
我还尝试按照此github问题中标记的示例直接使用pdfkit修改PDF元数据,但我获得的pdf未通过PDF/A合规性测试。
一些付费库,如 pspdfkit 和 apryse 似乎有实用程序可以做到这一点,但它们不是免费的。
尝试以下代码:
// This Node.js project will generate a PDF/A-3 file from scratch or convert an existing file to PDF/A-3.
// Require the necessary modules
const fs = require('fs');
const pdf = require('pdfkit');
const pdfa = require('pdf-a');
// Create a function to generate a PDF/A-3 file from scratch
function generatePDF() {
// Create a new PDF document
const doc = new pdf();
// Add content to the PDF document
doc.text('This is a PDF/A-3 file.');
// Create a writable stream
const writableStream = fs.createWriteStream('my-pdf.pdf');
// Pipe the PDF document to the writable stream
doc.pipe(writableStream);
// End the PDF document
doc.end();
// Convert the PDF document to PDF/A-3
pdfa.convert(writableStream, 'my-pdf.pdf', 'pdfa-3');
}
// Create a function to convert an existing file to PDF/A-3
function convertToPDF() {
// Read the existing file
const readableStream = fs.createReadStream('my-file.txt');
// Create a writable stream
const writableStream = fs.createWriteStream('my-pdf.pdf');
// Convert the existing file to PDF/A-3
pdfa.convert(readableStream, writableStream, 'pdfa-3');
}
// Call the functions
generatePDF();
convertToPDF();
使用
npm install pdf-lib
现在,创建一个 Node.js 脚本并使用 pdf-lib 库生成 PDF/A 文件:
const { PDFDocument, rgb, StandardFonts } = require('pdf-lib');
const fs = require('fs');
async function generatePDFA() {
// Create a new PDF/A document
const pdfDoc = await PDFDocument.create();
// Set the PDF/A version to PDF/A-2B (PDF/A version 2, Level B)
pdfDoc.setPDFVersion(2);
// Add a new page
const page = pdfDoc.addPage([595, 842]); // Default PDF page size: A4 (in points)
// Get the built-in Helvetica font
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Add text to the page
const text = 'Hello, PDF/A!';
const { width, height } = font.widthOfTextAtSize(text, 24);
page.drawText(text, {
x: 50,
y: 800,
size: 24,
font: font,
color: rgb(0, 0, 0), // Black color
});
// Serialize the PDF/A document to a Uint8Array
const pdfBytes = await pdfDoc.save();
// Save the PDF/A to a file
fs.writeFileSync('output.pdf', pdfBytes);
}
generatePDFA().catch((err) => console.log('Error:', err.message));