我需要生成包含CSV文件内部的PDF作为可以打开的附件(双击它)。有没有办法在JAVA中进行这种程序化?感谢。
答案 0 :(得分:0)
由于您没有显示任何代码,因此很难知道您是使用新的iText 7还是旧的(不再支持的)iText 5。
还不清楚您是要作为文档级附件(仅在PDF的附件面板中可见)或作为注释的文件(在页面上也可见)附加。
让我们假设您是iText的新用户,并且您从最新版本开始。在这种情况下,您可以添加文档级附件,如下所示:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
PdfFileSpec fs = PdfFileSpec.createEmbeddedFileSpec(pdfDoc,
PATH, null, "test.csv", null, null, false);
pdfDoc.addFileAttachment("specificname", fs);
在这种情况下,PATH
是CSV文件的文件路径。
添加文件附件注释的iText 7代码如下所示:
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
Rectangle rect = new Rectangle(36, 700, 100, 100);
PdfFileSpec fs = PdfFileSpec.createEmbeddedFileSpec(pdfDoc,
PATH, null, "test.csv", null, null, false);
PdfAnnotation attachment = new PdfFileAttachmentAnnotation(rect, fs)
.setContents("Click me");
pdfDoc.addNewPage().addAnnotation(attachment);
矩形rect
定义注释的位置和尺寸。如果要将文件附件注释添加到现有文档,可以创建PdfDocument
,同时将PdfReader
实例作为参数。
如果由于某种原因您仍想使用旧的iText,那么您可以添加如下文档级附件:
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
writer, null, fileName, csv_stream;
fs.AddDescription("specificname", false);
writer.AddFileAttachment(fs);
或者像这样:
PdfFileSpecification fs = PdfFileSpecification.FileEmbedded(
writer, null, fileName, csv_stream);
fs.AddDescription("specificname", false);
stamper.AddFileAttachment(fs);
以前的代码段适用于您拥有PdfWriter
实例的情况,因为您正在从头开始创建文档;当您拥有PdfStamper
个实例时,后一个代码段适用,因为您正在为现有文档添加附件。
对于文件附件注释,您需要以下代码:
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
writer, null, fileName, csv_stream);
PdfAnnotation attachment =
PdfAnnotation.createFileAttachment(writer, rect, fileName, fs);
writer.addAnnotation(attachment);
或者,如果您没有writer
,但stamper
:
stamper.addAnnotation(attachment, p);
其中p
是页码。
显然,建议使用iText 7,因为它比iText 5更具未来性。