问题
I am trying to attach files to a pdf document using iText. Files can be images, xml, txt, pdf, etc.
Is it possible to do this?
回答1:
You can use this method with src the path to the original document, dest the path to the newly created PDF, and attachments is an array of paths to the files you want to attach:
public void addAttachments(
String src, String dest, String[] attachments) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
for (int i = 0; i < attachments.length; i++) {
addAttachment(stamper.getWriter(), new File(attachments[i]));
}
stamper.close();
}
protected void addAttachment(PdfWriter writer, File src) throws IOException {
PdfFileSpecification fs =
PdfFileSpecification.fileEmbedded(writer, src.getAbsolutePath(), src.getName(), null);
writer.addFileAttachment(src.getName().substring(0, src.getName().indexOf('.')), fs);
}
回答2:
Short Question, short answer :D
itext API : addFileAttachment
来源:https://stackoverflow.com/questions/10614640/attach-random-file-to-a-pdf-using-ittext