通過C#從PDF文檔中提取附件

如何使用 C#以程式設計方式從 PDF 中提取附件。

如何使用 .NET 庫提取附件

為了提取PDF檔中的附件,我們將使用[Aspose.PDF用於.NET](https://products.aspose.com/pdf/net)API,這是一個功能豐富,功能強大且易於使用的文檔操作API,適用於 net 平臺。打開 [NuGet](https://www.nuget.org/packages/aspose.pdf) 包管理器,搜索“.PDF”並安裝。您也可以從程式包管理器主控台使用以下命令。

Package Manager Console

PM > Install-Package Aspose.PDF

從 PDF C#中提取附件


您需要 [Aspose.PDF用於.NET](https://releases.aspose.com/pdf/net) 在您的環境中嘗試代碼。

  1. 抓取嵌入檔案集合。
  2. 抓取嵌入檔案的計數。 迴圈訪問集合以獲取所有附件。
  3. 檢查參數物件是否包含參數。
  4. 取得附件並寫入檔或流。

將附件提取到 PDF 文件。


    // Open document
    Document pdfDocument = new Document(dataDir + "GetAlltheAttachments.pdf");

    // Get embedded files collection
    EmbeddedFileCollection embeddedFiles = pdfDocument.EmbeddedFiles;

    // Get count of the embedded files
    Console.WriteLine("Total files : {0}", embeddedFiles.Count);

    int count = 1;

    // Loop through the collection to get all the attachments
    foreach (FileSpecification fileSpecification in embeddedFiles)
    {
        Console.WriteLine("Name: {0}", fileSpecification.Name);
        Console.WriteLine("Description: {0}",
        fileSpecification.Description);
        Console.WriteLine("Mime Type: {0}", fileSpecification.MIMEType);

        // Check if parameter object contains the parameters
        if (fileSpecification.Params != null)
        {
            Console.WriteLine("CheckSum: {0}",
            fileSpecification.Params.CheckSum);
            Console.WriteLine("Creation Date: {0}",
            fileSpecification.Params.CreationDate);
            Console.WriteLine("Modification Date: {0}",
            fileSpecification.Params.ModDate);
            Console.WriteLine("Size: {0}", fileSpecification.Params.Size);
        }

        // Get the attachment and write to file or stream
        byte[] fileContent = new byte[fileSpecification.Contents.Length];
        fileSpecification.Contents.Read(fileContent, 0,
        fileContent.Length);
        FileStream fileStream = new FileStream(dataDir + count + "_out" + ".txt",
        FileMode.Create);
        fileStream.Write(fileContent, 0, fileContent.Length);
        fileStream.Close();
        count+=1;
    }