C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#提取PDF附件

C#代码轻松实现从PDF文档中提取附件

作者:2501_93070778

本文介绍了如何使用 C# 从 PDF 文档中提取附件,主要包括文档级附件和注释附件两种类型,文中的示例代码讲解详细,感兴趣的小伙伴可以参考下

PDF 附件可以帮助用户查看与文档中特定内容相关的更多信息。PDF 中的附件主要分为两种:文档级附件和注释附件,二者的区别如下。

本文将介绍如何使用 C# 和 VB.NET 从 PDF 文档中提取这两种类型的附件。

安装相关库

首先,需要将相关库文件添加为 .NET 项目的引用。你可以下载对应的安装包,并将其中的 DLL 文件添加到项目中;也可以通过 NuGet 包管理器安装所需的库。

PM> Install-Package Spire.PDF

使用 C# 和 VB.NET 从 PDF 中提取附件

可以通过 PdfDocument.Attachments 属性获取 PDF 文档中的文档级附件。以下步骤演示如何提取 PDF 中的所有文档级附件,并将其保存到本地文件夹。

  1. 创建一个 PdfDocument 对象。
  2. 使用 PdfDocument.LoadFromFile() 方法加载 PDF 文件。
  3. 通过 PdfDocument.Attachments 属性获取文档中的附件集合。
  4. 使用 PdfAttachment.Data 属性获取指定附件的数据。
  5. 将附件数据写入文件,并保存到指定文件夹。

完整示例代码如下:

using Spire.Pdf;
using Spire.Pdf.Attachments;
using System.Net.Mail;

namespace ExtractAttachments
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建 PdfDocument 对象
            PdfDocument doc = new PdfDocument();

            // 加载包含附件的 PDF 文件
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf");

            // 获取 PDF 文档的附件集合
            PdfAttachmentCollection attachments = doc.Attachments;

            // 指定输出文件夹路径
            string outputFolder = "C:\\Users\\Administrator\\Desktop\\output\\";

            // 遍历附件集合
            for (int i = 0; i < attachments.Count; i++)
            {
                // 将附件写入文件
                File.WriteAllBytes(outputFolder + attachments[i].FileName, attachments[i].Data);
            }
        }
    }
}

使用 C# 和 VB.NET 从 PDF 中提取注释附件

注释附件是与 PDF 页面相关联的元素。若要获取指定页面中的注释,可以使用 PdfPageBase.AnnotationsV2 属性。随后,需要判断某个注释是否为文件附件注释。

以下步骤介绍如何从 PDF 文档中提取注释附件,并将其保存到本地文件夹。

  1. 创建一个 PdfDocument 对象。
  2. 使用 PdfDocument.LoadFromFile() 方法加载 PDF 文件。
  3. 通过 PdfDocument.Pages[] 属性获取文档中的指定页面。
  4. 使用 PdfPageBase.AnnotationsV2 属性获取该页面的注释集合。
  5. 判断指定注释是否属于 PdfFileAttachmentAnnotation 类型。如果是,则将注释附件写入文件,并保存到指定文件夹。

完整示例代码如下:

using Spire.Pdf;
using Spire.Pdf.Interactive.Annotations;

namespace ExtractAnnotationAttachments
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建 PdfDocument 对象
            PdfDocument doc = new PdfDocument();

            // 加载包含附件的 PDF 文件
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\AnnotationAttachments.pdf");

            // 指定输出文件夹路径
            string outputFolder = "C:\\Users\\Administrator\\Desktop\\Output\\";

            // 遍历所有页面
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // 获取页面的注释集合
                PdfAnnotationCollection collection = doc.Pages[i].AnnotationsV2;

                // 遍历所有注释
                for (int j = 0; j < collection.Count; j++)
                {
                    // 判断注释是否为 PdfFileAttachmentAnnotation 类型
                    if (collection[j] is PdfFileAttachmentAnnotation)
                    {
                        // 将注释附件写入文件
                        PdfFileAttachmentAnnotation attachmentAnnotation =
                            (PdfFileAttachmentAnnotation)collection[j];

                        PdfFileSpecification fileSpecification = attachmentAnnotation.FileSpecification;

                        // 获取附件文件名
                        String fileName = Path.GetFileName(fileSpecification.FileName);

                        // 获取附件数据
                        byte[] data = fileSpecification.EmbeddedFile.Data;

                        // 将附件保存到指定文件夹
                        File.WriteAllBytes(outputFolder + fileName, data);
                    }
                }
            }
        }
    }
}

知识扩展

从 PDF 中提取附件,核心是解析 PDF 内部的 EmbeddedFiles 名称树(文档级附件)和 FileAttachment 注释(页面级附件)。下面给出几种主流 C# 库的完整实现,并附上方案对比与注意事项。

1.使用 iText7(开源 / AGPL,推荐)

iText7 可以完整读取 PDF 的嵌入文件名称树,适合需要免费开源方案的场景。注意:AGPL 协议,商业闭源使用需购买许可。

安装

Install-Package itext7

完整代码

using System;
using System.Collections.Generic;
using System.IO;
using iText.Kernel.Pdf;

namespace PdfAttachmentExtractor
{
    class Program
    {
        static void Main(string[] args)
        {
            string pdfPath = @"C:\temp\input.pdf";
            string outputDir = @"C:\temp\attachments";

            ExtractAllAttachments(pdfPath, outputDir);
        }

        public static void ExtractAllAttachments(string pdfPath, string outputDir)
        {
            Directory.CreateDirectory(outputDir);

            using (PdfDocument pdfDoc = new PdfDocument(new PdfReader(pdfPath)))
            {
                PdfReader reader = pdfDoc.GetReader();

                // 1. 提取文档级嵌入文件(EmbeddedFiles 名称树)
                ExtractDocumentEmbeddedFiles(pdfDoc, reader, outputDir);

                // 2. 提取页面注释级文件附件(FileAttachment Annots)
                ExtractAnnotationAttachments(pdfDoc, reader, outputDir);
            }
        }

        private static void ExtractDocumentEmbeddedFiles(PdfDocument pdfDoc, PdfReader reader, string outputDir)
        {
            PdfDictionary catalog = pdfDoc.GetCatalog().GetPdfObject();
            PdfDictionary names = catalog.GetAsDictionary(PdfName.Names);
            if (names == null) return;

            PdfDictionary embeddedFiles = names.GetAsDictionary(PdfName.EmbeddedFiles);
            if (embeddedFiles == null) return;

            PdfNameTree nameTree = new PdfNameTree(embeddedFiles);
            IDictionary&lt;string, PdfObject&gt; files = nameTree.GetNames();

            foreach (var kv in files)
            {
                string fallbackName = kv.Key;
                if (kv.Value is PdfDictionary fileSpec)
                {
                    ExtractFileSpec(fileSpec, fallbackName, outputDir, reader);
                }
            }
        }

        private static void ExtractAnnotationAttachments(PdfDocument pdfDoc, PdfReader reader, string outputDir)
        {
            for (int i = 1; i &lt;= pdfDoc.GetNumberOfPages(); i++)
            {
                PdfPage page = pdfDoc.GetPage(i);
                PdfArray annots = page.GetPdfObject().GetAsArray(PdfName.Annots);
                if (annots == null) continue;

                foreach (PdfObject annotObj in annots)
                {
                    if (annotObj is PdfDictionary annot)
                    {
                        PdfName subtype = annot.GetAsName(PdfName.Subtype);
                        if (subtype != null &amp;&amp; subtype.Equals(new PdfName("FileAttachment")))
                        {
                            PdfDictionary fs = annot.GetAsDictionary(new PdfName("FS"));
                            if (fs != null)
                            {
                                ExtractFileSpec(fs, $"page{i}_annotation", outputDir, reader);
                            }
                        }
                    }
                }
            }
        }

        private static void ExtractFileSpec(PdfDictionary fileSpec, string fallbackName, string outputDir, PdfReader reader)
        {
            string name = fallbackName;

            // 优先使用 UF(Unicode 文件名),其次使用 F
            PdfString uf = fileSpec.GetAsString(PdfName.UF);
            if (uf != null)
            {
                name = uf.ToUnicodeString();
            }
            else
            {
                PdfString f = fileSpec.GetAsString(PdfName.F);
                if (f != null) name = f.ToUnicodeString();
            }

            PdfDictionary ef = fileSpec.GetAsDictionary(PdfName.EF);
            if (ef == null) return;

            PdfStream stream = ef.GetAsStream(PdfName.F) ?? ef.GetAsStream(PdfName.UF);
            if (stream == null) return;

            // 使用 reader.GetStreamBytes 自动解码 FlateDecode 等压缩流
            byte[] data = reader.GetStreamBytes(stream);

            string safeName = GetSafeFileName(name);
            string outPath = Path.Combine(outputDir, safeName);

            File.WriteAllBytes(outPath, data);
            Console.WriteLine($"提取: {safeName} ({data.Length} 字节) -&gt; {outPath}");
        }

        private static string GetSafeFileName(string name)
        {
            if (string.IsNullOrWhiteSpace(name)) return "attachment.bin";

            // 防止路径穿越:只取文件名部分
            name = Path.GetFileName(name);

            foreach (char c in Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }

            return string.IsNullOrWhiteSpace(name) ? "attachment.bin" : name;
        }
    }
}

2.使用 Aspose.PDF(商业库,代码最简洁)

Aspose.PDF 通过 Document.EmbeddedFiles 直接遍历所有嵌入文件,API 非常简洁。

安装

Install-Package Aspose.PDF

代码

using Aspose.Pdf;
using System;
using System.IO;

public static class AsposeExtractor
{
    public static void Extract(string pdfPath, string outputDir)
    {
        Directory.CreateDirectory(outputDir);

        Document pdf = new Document(pdfPath);

        foreach (FileSpecification fileSpec in pdf.EmbeddedFiles)
        {
            string safeName = GetSafeFileName(fileSpec.Name);
            string outPath = Path.Combine(outputDir, safeName);

            using (FileStream fs = new FileStream(outPath, FileMode.Create, FileAccess.Write))
            {
                fileSpec.Contents.CopyTo(fs);
            }

            Console.WriteLine($"提取: {safeName}");
        }
    }

    private static string GetSafeFileName(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) return "attachment.bin";
        name = Path.GetFileName(name);
        foreach (char c in Path.GetInvalidFileNameChars())
            name = name.Replace(c, '_');
        return string.IsNullOrWhiteSpace(name) ? "attachment.bin" : name;
    }
}

3.使用 Spire.PDF(商业库,有免费版)

Spire.PDF 通过 PdfDocument.Attachments 集合提取附件。

安装

Install-Package Spire.PDF

代码

using Spire.Pdf;
using Spire.Pdf.Attachments;
using System;
using System.IO;

public static class SpireExtractor
{
    public static void Extract(string pdfPath, string outputDir)
    {
        Directory.CreateDirectory(outputDir);

        PdfDocument doc = new PdfDocument();
        doc.LoadFromFile(pdfPath);

        foreach (PdfAttachment attachment in doc.Attachments)
        {
            string safeName = GetSafeFileName(attachment.FileName);
            string outPath = Path.Combine(outputDir, safeName);

            File.WriteAllBytes(outPath, attachment.Data);
            Console.WriteLine($"提取: {safeName}");
        }

        doc.Close();
    }

    private static string GetSafeFileName(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) return "attachment.bin";
        name = Path.GetFileName(name);
        foreach (char c in Path.GetInvalidFileNameChars())
            name = name.Replace(c, '_');
        return string.IsNullOrWhiteSpace(name) ? "attachment.bin" : name;
    }
}

4.使用 Syncfusion PDF(商业库,有社区版)

Syncfusion 通过 PdfLoadedDocument.Attachments 提取附件。

安装

Install-Package Syncfusion.Pdf.Net.Core

代码

using Syncfusion.Pdf.Parsing;
using System;
using System.IO;
public static class SyncfusionExtractor
{
    public static void Extract(string pdfPath, string outputDir)
    {
        Directory.CreateDirectory(outputDir);
        using (PdfLoadedDocument doc = new PdfLoadedDocument(pdfPath))
        {
            foreach (PdfAttachment attachment in doc.Attachments)
            {
                string safeName = GetSafeFileName(attachment.FileName);
                string outPath = Path.Combine(outputDir, safeName);
                File.WriteAllBytes(outPath, attachment.Data);
                Console.WriteLine($"提取: {safeName}");
            }
        }
    }
    private static string GetSafeFileName(string name)
    {
        if (string.IsNullOrWhiteSpace(name)) return "attachment.bin";
        name = Path.GetFileName(name);
        foreach (char c in Path.GetInvalidFileNameChars())
            name = name.Replace(c, '_');
        return string.IsNullOrWhiteSpace(name) ? "attachment.bin" : name;
    }
}

总结

本文介绍了如何使用 C# 从 PDF 文档中提取附件,主要包括文档级附件和注释附件两种类型。

对于文档级附件,可以通过 PdfDocument.Attachments 属性获取附件集合,并遍历集合,将附件数据保存到本地文件夹。对于注释附件,则需要遍历 PDF 文档的各个页面,获取页面中的注释集合,并判断注释是否属于 PdfFileAttachmentAnnotation 类型。确认后,即可提取附件的文件名和数据,并将其保存为本地文件。

通过以上方法,可以根据附件在 PDF 文档中的存储方式,选择合适的提取方法,便于后续查看、管理和处理 PDF 中的嵌入文件。

到此这篇关于C#代码轻松实现从PDF文档中提取附件的文章就介绍到这了,更多相关C#提取PDF附件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文