c# - 如何从 pdf 文件中提取附件?

标签 c# .net pdf

我有大量附有 xml 文件的 pdf 文档。我想提取那些附加的 xml 文件并阅读它们。我如何使用 .net 以编程方式执行此操作?

最佳答案

iTextSharp 也非常有能力提取附件...尽管您可能必须使用低级对象来执行此操作。

有两种方法可以在 PDF 中嵌入文件:

  1. 在文件注释中
  2. 在文档级别“EmbeddedFiles”。

一旦您从任一来源获得文件规范字典,文件本身将成为标有“EF”(嵌入式文件)的字典中的一个流。

因此,要在文档级别列出所有文件,可以这样编写代码(用 Java):

Map<String, byte[]> files = new HashMap<String,byte[]>();

PdfReader reader = new PdfReader(pdfPath);
PdfDictionary root = reader.getCatalog();
PdfDictionary names = root.getAsDict(PdfName.NAMES); // may be null
PdfDictionary embeddedFilesDict = names.getAsDict(PdfName.EMBEDDEDFILES); //may be null
PdfArray embeddedFiles = embeddedFilesDict.getAsArray(PdfName.NAMES); // may be null

int len = embeddedFiles.size();
for (int i = 0; i < len; i += 2) {
  PdfString name = embeddedFiles.getAsString(i); // should always be present
  PdfDictionary fileSpec = embeddedFiles.getAsDict(i+1); // ditto

  PdfDictionary streams = fileSpec.getAsDict(PdfName.EF);
  PRStream stream = null;

  if (streams.contains(PdfName.UF))
    stream = (PRStream)streams.getAsStream(PdfName.UF);
  else
    stream = (PRStream)streams.getAsStream(PdfName.F); // Default stream for backwards compatibility

  if (stream != null) {
    files.put( name.toUnicodeString(), PdfReader.getStreamBytes((PRStream)stream));
  }
}

关于c# - 如何从 pdf 文件中提取附件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6305505/

相关文章:

c# - 我的 C# 应用程序的最佳数据库选择

c# - Linq 对匿名集合求和以在 View 中查找总数

.net - 什么是仅为 session 启用 Mini-profiler 的简单方法?

c# - EmitCalli .net 核心替代方案

php - 从附加的 html 内容生成 pdf

java - 如何让图片和文字并排显示 itext

c# - Linq to Sql - 具有多个连接的不同项目的查询列表

c# - 使用 C# 中的静态类通过事件通知其他订阅者的简单状态机

c# - 为暂存和生产 web.config 文件生成 xml 文档转换

.net - 生成 PDF