如何使用 iText 5 将 csv 文件附加到 Java 中新创建的 PDF?

How to attach csv file(s) to a newly created PDF in Java using iText 5?

看了几天的网页和帖子后,我仍然对如何在 Java 中使用“iText 5.3.1”创建的 PDF 文件添加“csv”文件附件感到困惑。

在我继承的 Java 可执行文件中,创建了多个 PDF 文件,然后将它们连接在一起成为一个 PDF 文件。 现在,需要将“csv”文件附加到这个 PDF 文档。例如,在“iText in Action”(清单 16.6)一书的第 16 章中,使用 PdfFileSpecification class 和 fileEmbedded 方法附加一个“xml”文件。

PdfFileSpecification fs = PdfFileSpecification。文件嵌入(作者,空,“Kubrick.xml”, txt.toByteArray()); writer.addFileAttachment(fs);

除了作者没有在代码片段中定义的“writer”参数外,我理解“fileEmbedded”的参数。

问题,使用“PdfFileSpecification”class如何声明“writer”以便将“csv”文件附加到已经创建的 PDF 文件,或者有更好的方法吗?

这是将几个 PDF 文件连接在一起的代码部分,现在需要附加“csv”文件,我认为是“文档级”附件。

尝试使用“PdfFileSpecification”class 和“fileEmbedded”方法。不要如何正确定义参数以将 csv 文件附加到新创建的 PDF。特别是 "writer" 参数。

aPDFFiles = (String[])vFileList.toArray(aPDFFiles);

Document document = new Document();

PdfCopy copy = new PdfCopy(document, new FileOutputStream(sFinalFile));

document.open();

PdfReader reader;         
int n;

// loop over the documents you want to concatenate
for (int i = 0; i < aPDFFiles.length; i++) {

reader = new PdfReader(aPDFFiles[i]);

// loop over the pages in that document
n = reader.getNumberOfPages();

for (int page = 0; page < n; ) {
    copy.addPage(copy.getImportedPage(reader, ++page));
}           

copy.freeReader(reader);

document.close();       

//  Add a “csv” file(s) as an attachment?

PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(writer, 
    sMainDir +  "TestAttachment.csv", "TestAttachment.csv", null);

事实证明,在这种情况下非常简单。我有最终 "pdf" 文件的 "PdfCopy" 对象(在将几个 PDF 文件连接成一个文件之后)并且 "PdfCopy" class 有一个 "addFileAttachment" 方法那。

copy.addFileAttachment("TestAttachment.csv", null, sMainDir + "TestAttachment.csv", "TestAttachment.csv");