【发布时间】:2015-12-20 15:05:54
【问题描述】:
我已经能够编写代码来创建新的 PDF 或打开现有的 PDF 并追加。 我现在想要实现的是在其中插入另一个 PDF。以下是我迄今为止编写的附加 PDF 的示例代码。
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
// Append sample line
document.add(new Paragraph("my timestamp"));
document.close();
据我所知,Adobe 阅读器确实支持插入文档。不确定是否也可以使用 Java 代码来实现。
编辑:
以下是我编写的在 PDF 中嵌入 PDF 的代码。单击并打开嵌入的 pdf/附件时出现错误。
public class AddEmbeddedFile {
public static final String SRC = "C:\\Users\\User\\Desktop\\testSource.pdf";
public static final String Embed = "C:\\Users\\User\\Desktop\\testEmbed.pdf";
public static final String DEST = "C:\\Users\\User\\Desktop\\testDest.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new AddEmbeddedFile().manipulatePdf(SRC, DEST, Embed);
}
public void manipulatePdf(String src, String dest, String embed) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfReader reader2 = new PdfReader(embed);
int n = reader2.getNumberOfPages();
reader2.close();
ByteArrayOutputStream boas;
byte[] PDFContent = null;
byte[] PDFContent2 = new byte[0];
for (int i = 0; i < n; ) {
reader2.selectPages(String.valueOf(++i));
boas = new ByteArrayOutputStream();
PdfStamper stamper2 = new PdfStamper(reader2, boas);
PDFContent = boas.toByteArray();
byte[] c = new byte[PDFContent.length + PDFContent2.length];
System.arraycopy(PDFContent, 0, c, 0, PDFContent.length);
System.arraycopy(PDFContent2, 0, c, PDFContent.length, PDFContent2.length);
PDFContent2 = c;
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
stamper.getWriter(), null, "tests.pdf", PDFContent2, "pdf", null, 0);
stamper.addFileAttachment("some test file", fs);
stamper.close();
}
}
【问题讨论】:
-
@Stefan,你能确认一下它是否是开源的吗?此外,它只是插入文本和文本文档,而不是 pdf 文档。你能帮忙吗?谢谢。
-
iText 是在 AGPL 下发布的开源软件。这意味着您也必须将自己的代码发布为 AGPL。在许多情况下,这不包括在商业环境中使用 iText,除非您从 iText Software 购买商业许可。这在one-minute video 中有解释。简而言之:iText 是开源的,但这并不意味着您在商业应用程序中使用 iText 就不必购买商业许可证。
-
@BrunoLowagie,感谢您的解释。