如何在 PDF C# 中新增和移除附件

如何在 C# 中使用 IronPDF 新增和移除 PDF 附件

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronPDF 允許您通過簡單的 C# 方法(如 AddAttachment()RemoveAttachment())以程式化方式新增、檢索和移除 PDF 文件中的文件附件,讓您直接將輔助文件嵌入您的 PDF 中。

PDF 文件中的附件是指嵌入在 PDF 文件本身內的文件或附加資料。 這與 PDF 的常規內容不同,後者包括您查看 PDF 時的可見文字、圖像和格式設置。 這些附件可以是多種文件型別,包括圖像、文件、電子表格或其他格式。 通常,附件用來提供其他參考資料或補充資料,讓使用者在開啟 PDF 時可以存取。 這種能力在建立綜合 PDF 報告或需要合併多個 PDF以支持文件時特別有用。

快速開始:向 PDF 新增附件 using IronPDF 將附件新增到您的 PDF 文件中。 此快速範例演示了如何將文件作為附件嵌入到 PDF 中。 載入現有的 PDF,使用 AddAttachment 方法,然後保存更新的文件。 此過程確保您的輔助材料包含在您的 PDF 中,使其直接在任何 PDF 查看器中即可存取。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 複製並運行這段程式碼片段。

    var pdf = IronPdf.PdfDocument.FromFile("example.pdf");
    pdf.Attachments.AddAttachment("file.txt", System.IO.File.ReadAllBytes("file.txt"));
    pdf.SaveAs("updated.pdf");
  3. 部署以在您的實時環境中測試

    今天就開始在您的專案中使用IronPDF,透過免費試用

    arrow pointer


如何將文件作為附件新增到 PDF?

要將文件作為附件新增,首先將其作為 byte[] 載入。 最簡單的方法是使用 File.ReadAllBytes 方法。 在文件載入為 byte[] 後,使用 AddAttachment 方法將物件作為附件新增到 PDF 中:

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-add-attachment.cs
using IronPdf;
using System.IO;

// Import attachment file
byte[] fileData = File.ReadAllBytes(@"path/to/file");

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Add attachment to the PDF
pdf.Attachments.AddAttachment("Example", fileData);

pdf.SaveAs("addAttachment.pdf");
Imports IronPdf
Imports System.IO

' Import attachment file
Private fileData() As Byte = File.ReadAllBytes("path/to/file")

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Add attachment to the PDF
pdf.Attachments.AddAttachment("Example", fileData)

pdf.SaveAs("addAttachment.pdf")
$vbLabelText   $csharpLabel

AddAttachment 功能輸出一個 PdfAttachment 物件,您可以保留以供將來參考或在需要時刪除。 這種方法類似於向 PDF 新增圖像管理其他 PDF 資產

保存 PDF 後,您可以從 PDF 查看器的工具欄打開附件。 下面的圖像演示了如何在 Google Chrome 的 PDF 查看器中找到此功能:

PDF 查看器顯示 Hello World 文件,帶導航控制和側邊欄面板

從那裡,您可以點擊它並將附件保存到您的儲存中。

我可以將哪些文件型別附加到 PDF?

IronPDF 支援將幾乎任何文件型別附加到 PDF 文件中。 常見的附件型別包括:

  • Office 文件(DOCX、XLSX、PPTX)
  • 圖像(JPG、PNG、GIF、SVG)
  • 文字文件(TXT、CSV、XML)
  • 壓縮檔案(ZIP、RAR)
  • 其他 PDF

附件系統使用二進位資料工作,因此任何可以以位元組讀取的文件都可以附加。 在處理特定的文件型別時,您還可以考慮使用 IronPDF 的內建轉換功能,如將 DOCX 轉換為 PDF將圖像轉換為 PDF

附件在 PDF 查看器中顯示在哪裡?

不同的 PDF 查看器在不同的位置顯示附件:

  • Adobe Acrobat:在導航窗格中顯示回形針圖標
  • Chrome PDF Viewer:單擊時在左側邊欄中顯示附件
  • Firefox PDF Viewer:在專用面板中顯示附件
  • Microsoft Edge:類似於 Chrome,具有側邊欄附件視圖

大多數現代 PDF 查看器支援附件,儘管介面可能在應用程式之間略有不同。

將 PdfAttachment 物件新增後會發生什麼?

當您調用 AddAttachment() 時,IronPDF 建立一個包含以下內容的 PdfAttachment 物件:

  • 名稱:附件的顯示名稱
  • 資料:附件文件的二進位內容
  • 描述:可選的附件元資料

此物件被新增到 PDF 的內部附件集合中,並通過 Attachments 屬性保持可存取,直到明確移除。

Attachments

如何從現有 PDF 中檢索附件?

可以通過存取 Attachments 物件的 PdfDocument 屬性,將 PDF 中的附件作為二進位資料檢索。 有了二進位資料,您可以將附件導出為其相應的文件格式。

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-retrieve-attachment.cs
using IronPdf;
using System.IO;

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("addAttachment.pdf");

// Iterate through all attachments
foreach (var attachment in pdf.Attachments)
{
    if (attachment.Name.Contains("Example"))
    {
        // Save byte to file
        File.WriteAllBytes($"{attachment.Name}.doc", attachment.Data);
    }
}
Imports IronPdf
Imports System.IO

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("addAttachment.pdf")

' Iterate through all attachments
For Each attachment In pdf.Attachments
	If attachment.Name.Contains("Example") Then
		' Save byte to file
		File.WriteAllBytes($"{attachment.Name}.doc", attachment.Data)
	End If
Next attachment
$vbLabelText   $csharpLabel

當您需要從 PDF 中提取內容或以程式化方式處理附件的文件時,這個過程特別有用。

如何在 PDF 中存取多個附件?

Attachments 屬性返回一個集合,您可以通過 LINQ 進行迭代或查詢:

// Get all attachments as a list
var allAttachments = pdf.Attachments.ToList();

// Filter attachments by size (e.g., files larger than 1MB)
var largeAttachments = pdf.Attachments
    .Where(a => a.Data.Length > 1024 * 1024)
    .ToList();

// Find specific attachment by exact name
var specificAttachment = pdf.Attachments
    .FirstOrDefault(a => a.Name == "report.xlsx");
// Get all attachments as a list
var allAttachments = pdf.Attachments.ToList();

// Filter attachments by size (e.g., files larger than 1MB)
var largeAttachments = pdf.Attachments
    .Where(a => a.Data.Length > 1024 * 1024)
    .ToList();

// Find specific attachment by exact name
var specificAttachment = pdf.Attachments
    .FirstOrDefault(a => a.Name == "report.xlsx");
' Get all attachments as a list
Dim allAttachments = pdf.Attachments.ToList()

' Filter attachments by size (e.g., files larger than 1MB)
Dim largeAttachments = pdf.Attachments _
    .Where(Function(a) a.Data.Length > 1024 * 1024) _
    .ToList()

' Find specific attachment by exact name
Dim specificAttachment = pdf.Attachments _
    .FirstOrDefault(Function(a) a.Name = "report.xlsx")
$vbLabelText   $csharpLabel

檢索到的附件有哪些可用屬性?

每個 PdfAttachment 物件提供:

  • Name:附件的顯示名稱
  • Data:以位元組陣列形式的二進位內容
  • Description:可選的描述元資料(如果已設置)

您可以使用這些屬性來識別、過濾和處理基於您需求的附件。

如何按名稱或型別篩選附件?

由於附件是使用顯示名稱儲存的,您可以使用字串操作來篩選它們:

// Filter by file extension (assuming names include extensions)
var imageAttachments = pdf.Attachments
    .Where(a => a.Name.EndsWith(".jpg") || 
                a.Name.EndsWith(".png") || 
                a.Name.EndsWith(".gif"))
    .ToList();

// Filter by name pattern
var reportsOnly = pdf.Attachments
    .Where(a => a.Name.StartsWith("Report_"))
    .ToList();
// Filter by file extension (assuming names include extensions)
var imageAttachments = pdf.Attachments
    .Where(a => a.Name.EndsWith(".jpg") || 
                a.Name.EndsWith(".png") || 
                a.Name.EndsWith(".gif"))
    .ToList();

// Filter by name pattern
var reportsOnly = pdf.Attachments
    .Where(a => a.Name.StartsWith("Report_"))
    .ToList();
' Filter by file extension (assuming names include extensions)
Dim imageAttachments = pdf.Attachments _
    .Where(Function(a) a.Name.EndsWith(".jpg") OrElse _
                   a.Name.EndsWith(".png") OrElse _
                   a.Name.EndsWith(".gif")) _
    .ToList()

' Filter by name pattern
Dim reportsOnly = pdf.Attachments _
    .Where(Function(a) a.Name.StartsWith("Report_")) _
    .ToList()
$vbLabelText   $csharpLabel

Icon Quote related to 如何按名稱或型別篩選附件?

我最喜歡的程式庫是IronPDF。它允許快速高效地操作PDF文件。它還有許多有價值的功能,例如導出到PDF/A格式和數位簽署PDF文件。

Milan Jovanovic related to 如何按名稱或型別篩選附件?

Milan Jovanovic

Microsoft MVP

查看案例研究
Icon Quote related to 如何按名稱或型別篩選附件?

IronOCR意味著我們每年可以從手動處理中節省$40,000,同時提高生產力,釋放資源以進行高影響的任務。我會強烈推薦它。

Brent Matzelle related to 如何按名稱或型別篩選附件?

Brent Matzelle

首席技術官,OPYN

查看案例研究
Icon Quote related to 如何按名稱或型別篩選附件?

IronSuite在我們的運營中扮演著至關重要的角色。這些工具增加了包括建立平面圖和改善庫存管理在內的業務效率。

David Jones related to 如何按名稱或型別篩選附件?

David Jones

首席軟體工程師,Agorus Build

查看案例研究

如何從 PDF 中移除附件?

要移除附件,請使用 RemoveAttachment 功能。 此方法需要附件的引用,可以從 Attachments 屬性檢索。 以下是如何使用上面的保存文件進行此操作:

:path=/static-assets/pdf/content-code-examples/how-to/add-remove-attachments-remove-attachment.cs
using IronPdf;
using System.Linq;

// Open existing PDF
PdfDocument pdf = PdfDocument.FromFile("addAttachment.pdf");

// Add attachment to the PDF
PdfAttachmentCollection retrieveAttachments = pdf.Attachments;

// Remove attachment from PDF
pdf.Attachments.RemoveAttachment(retrieveAttachments.First());

pdf.SaveAs("removeAttachment.pdf");
Imports IronPdf
Imports System.Linq

' Open existing PDF
Private pdf As PdfDocument = PdfDocument.FromFile("addAttachment.pdf")

' Add attachment to the PDF
Private retrieveAttachments As PdfAttachmentCollection = pdf.Attachments

' Remove attachment from PDF
pdf.Attachments.RemoveAttachment(retrieveAttachments.First())

pdf.SaveAs("removeAttachment.pdf")
$vbLabelText   $csharpLabel

移除附件並在 PDF 查看器中打開結果文件之後,您將看到附件不再出現:

PDF 查看器打開的附件面板,顯示 Hello World 文件和顯示附件按鈕

我移除附件後會發生什麼?

當您移除附件時:

  1. 附件資料會從 PDF 文件中完全移除
  2. 文件大小大約會減少至移除的附件大小
  3. PDF 結構中與該附件的任何引用都會被清理
  4. 一旦您保存 PDF,變更即為永久化

這類似於其他 PDF 修改操作,如移除頁面刪除內容

我可以一次移除多個附件嗎?

可以,您可以在一次操作中移除多個附件。 這裡有一個例子:

// Remove all attachments that match a pattern
var attachmentsToRemove = pdf.Attachments
    .Where(a => a.Name.StartsWith("temp_"))
    .ToList();

foreach (var attachment in attachmentsToRemove)
{
    pdf.Attachments.RemoveAttachment(attachment);
}

// Or remove all attachments at once
while (pdf.Attachments.Count > 0)
{
    pdf.Attachments.RemoveAttachment(pdf.Attachments.First());
}
// Remove all attachments that match a pattern
var attachmentsToRemove = pdf.Attachments
    .Where(a => a.Name.StartsWith("temp_"))
    .ToList();

foreach (var attachment in attachmentsToRemove)
{
    pdf.Attachments.RemoveAttachment(attachment);
}

// Or remove all attachments at once
while (pdf.Attachments.Count > 0)
{
    pdf.Attachments.RemoveAttachment(pdf.Attachments.First());
}
Imports System.Linq

' Remove all attachments that match a pattern
Dim attachmentsToRemove = pdf.Attachments _
    .Where(Function(a) a.Name.StartsWith("temp_")) _
    .ToList()

For Each attachment In attachmentsToRemove
    pdf.Attachments.RemoveAttachment(attachment)
Next

' Or remove all attachments at once
While pdf.Attachments.Count > 0
    pdf.Attachments.RemoveAttachment(pdf.Attachments.First())
End While
$vbLabelText   $csharpLabel

如何確認附件已成功移除?

您可以通過幾種方式確認附件的移除:

// Check the attachment count
int attachmentCountBefore = pdf.Attachments.Count;
pdf.Attachments.RemoveAttachment(targetAttachment);
int attachmentCountAfter = pdf.Attachments.Count;

// Verify the count decreased
if (attachmentCountAfter < attachmentCountBefore)
{
    Console.WriteLine("Attachment successfully removed");
}

// Check if specific attachment exists
bool attachmentExists = pdf.Attachments
    .Any(a => a.Name == "specificFile.txt");
// Check the attachment count
int attachmentCountBefore = pdf.Attachments.Count;
pdf.Attachments.RemoveAttachment(targetAttachment);
int attachmentCountAfter = pdf.Attachments.Count;

// Verify the count decreased
if (attachmentCountAfter < attachmentCountBefore)
{
    Console.WriteLine("Attachment successfully removed");
}

// Check if specific attachment exists
bool attachmentExists = pdf.Attachments
    .Any(a => a.Name == "specificFile.txt");
' Check the attachment count
Dim attachmentCountBefore As Integer = pdf.Attachments.Count
pdf.Attachments.RemoveAttachment(targetAttachment)
Dim attachmentCountAfter As Integer = pdf.Attachments.Count

' Verify the count decreased
If attachmentCountAfter < attachmentCountBefore Then
    Console.WriteLine("Attachment successfully removed")
End If

' Check if specific attachment exists
Dim attachmentExists As Boolean = pdf.Attachments _
    .Any(Function(a) a.Name = "specificFile.txt")
$vbLabelText   $csharpLabel

PDF 附件的最佳實踐

在使用 IronPDF 的 PDF 附件時,請考慮以下最佳實踐:

  1. 文件大小管理:注意附件的大小,因為它們會直接增加 PDF 文件的大小
  2. 命名約定:使用清晰、描述性的名稱來幫助使用者識別附件
  3. 安全考慮:當處理敏感附件時,考慮應用PDF 密碼和權限
  4. 性能:對於大型附件或多個文件,考慮使用非同步操作來保持應用程式的響應性

準備好看看您還能做什麼嗎? 查看我們的教程頁面:組織 PDF

常見問題

如何以程式化方式在 C# 中將檔案附加到 PDF?

IronPDF 提供了一個簡單的 AddAttachment() 方法將檔案嵌入到 PDF 中。首先,使用 File.ReadAllBytes() 將您的檔案載入為位元組陣列,然後在您的 PdfDocument 物件上使用 AddAttachment 方法。此方法接受檔名和位元組陣列作為參數。

可以將哪些型別的檔案附加到 PDF?

IronPDF 允許您將多種檔案型別附加到 PDF 中,包括圖像、文件、試算表和其他格式。這些附件直接嵌入到 PDF 檔案中,並可以通過任何標準 PDF 檢視器的附件面板進行存取。

如何載入現有的 PDF 以新增附件?

您可以使用 IronPDF 的 PdfDocument.FromFile() 方法載入現有的 PDF 。載入後,您可以使用 Attachments 屬性來管理附件,包括使用 AddAttachment() 新增附件或移除現有附件。

PDF 內容和 PDF 附件有什麼區別?

PDF 內容包括當您查看 PDF 時所見的可見文字、圖像和格式。附件是嵌入 PDF 內的單獨檔案,但不會出現在主文件檢視中。使用 IronPDF,附件可以在 PDF 檢視器的附件面板中存取,作為補充材料。

如何從 PDF 中移除附件?

IronPDF 提供了一個 RemoveAttachment() 方法以程式化方式移除嵌入的 PDF 附件。AddAttachment 方法返回一個 PdfAttachment 物件,您可以稍後參考以進行移除操作。

使用者在 PDF 檢視器中可在哪裡找到附件?

在使用 IronPDF 新增附件後,使用者可以通過 PDF 檢視器的工具欄存取它們。大多數 PDF 檢視器,包括 Google Chrome 的內建檢視器,顯示一個附件圖標或面板,其中嵌入的檔案可以打開或保存。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

準備開始了嗎?
Nuget 下載 19,936,792 | 版本: 2026.7 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想快速獲得證明嗎? PM > Install-Package IronPdf
執行範例 看您的HTML變成PDF。