Attach random file to a pdf using itText

亡梦爱人 提交于 2020-01-02 12:42:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!