使用itText将随机文件附加到pdf [英] Attach random file to a pdf using itText

查看:316
本文介绍了使用itText将随机文件附加到pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用iText将文件附加到pdf文档。文件可以是图片,xml,txt,pdf等。

I am trying to attach files to a pdf document using iText. Files can be images, xml, txt, pdf, etc.

是否可以这样做?

推荐答案

您可以将此方法与 src 一起使用原始文档的路径, dest 新创建的PDF的路径,附件是要附加的文件的路径数组:

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);
}

这篇关于使用itText将随机文件附加到pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆