跳至頁尾內容
使用IRONPDF

如何用C#從PDF提取資料

IronPDF讓C#開發者在僅需5個步驟內,使用簡單的Windows Forms應用程式,透過安裝NuGet套件和少量程式碼將HTML轉換為專業的PDF文件。

C#開發者可以使用IronPDF從HTML生成PDF。 本文將展示使用.NET Framework建立的C# Windows Forms應用程式的過程。

請按照這些步驟在Visual Studio 2019中建立專案。

如何為PDF生成建立Visual Studio專案?

首先,打開Visual Studio 2019

Visual Studio 2019啟動窗口顯示選擇克隆倉庫、開啟專案或方案、打開本地文件夾或建立新專案的選項

點擊"建立新專案"。

現在,從範本中選擇"Windows Forms App",然後按"下一步"。 將會出現以下窗口:

Visual Studio

輸入專案名稱"使用IronPDF建立PDF"。

Visual Studio新專案配置窗口顯示專案名稱為

點擊"建立"按鈕。 專案將如下面所示建立。

Visual Studio IDE在設計視圖中顯示空白的Windows Form,解決方案資源管理器顯示名為

為什麼我應該在本教程中使用Windows Forms?

Windows Forms提供直接的可視環境,適合初學者學習C#中的PDF生成。 它提供了拖放設計器,讓您可以輕鬆建立使用者介面,而無需大量使用HTML或Web開發知識。 Windows Forms的事件驅動編程模型與初學開發者對應用程式流程的思考方式非常契合,非常適合用來演示IronPDF的核心HTML到PDF功能

對於生產應用,您可以考慮使用ASP.NET Core進行基於Web的PDF生成用於批處理的控制台應用程式。 然而,Windows Forms仍然是內部工具、桌面工具和需要快速可視化反饋開發的學習環境中的理想選擇。

哪個版本的Visual Studio最合適?

Visual Studio 2019或更新版本提供了IronPDF開發的最佳體驗。 這些版本包含改進的NuGet套件管理、更好的IntelliSense支持現代C#功能,以及增強的除錯能力,有助於解決PDF生成問題。

儘管Visual Studio 2022提供了最新的功能和性能改進,但Visual Studio 2019仍然廣泛使用且完全支持。 兩個版本都可以無縫使用IronPDF的NuGet套件。 對於使用Visual Studio Code的開發者,您仍然可以使用IronPDF,儘管您將需要使用命令行介面進行套件管理,並且失去一些本教程中顯示的可視化設計功能。

我可以用.NET Core代替.NET Framework嗎?

當然可以! IronPDF完全支持.NET Core,.NET 5,.NET 6,和.NET 7+。 事實上,使用.NET Core或更新版本具有多種優勢,包括跨平台相容性、更好的性能和最新C#語言功能。

要使用.NET Core,只需在建立專案時選擇合適的目標框架。 本教程中的程式碼範例在所有支持的框架中都同樣適用。 為了部署的靈活性,.NET Core應用程式可以在Linux和macOS上運行,除了Windows之外,這使其非常適合用於雲部署和容器化環境。

如何使用NuGet包管理器安裝IronPDF?

  • 首先,點擊工具欄上的"工具"按鈕。
  • 將會打開一個選單。 現在點擊"NuGet包管理器"選項。
  • 將會打開另一個子選單。 現在點擊名為"套件管理控制台"的選項。

Visual Studio顯示工具選單展開,包括NuGet包管理子選單,突出顯示

您將在命令行下獲得新介面。在其中寫下安裝IronPDF套件的命令。

Install-Package IronPdf

Visual Studio 2019 IDE顯示套件管理控制台,IronPDF安裝命令準備執行

輸入命令後按Enter。 確保您的電腦/筆記本電腦已連接網路。 IronPDF包將自動新增到您現有的專案中。

Visual Studio 2019 IDE顯示IronPDF程式庫文件,包含HTML到PDF轉換的C#程式碼範例,以及顯示成功安裝IronPDF的套件管理控制台

上方螢幕顯示已將套件成功新增到您的專案中。

有哪些安裝IronPDF的替代方法?

除了套件管理控制台,您還有多種選擇來安裝IronPDF

  1. NuGet包管理器使用者介面:右鍵單擊您的專案,選擇"管理NuGet套件",搜索"IronPDF",然後點擊安裝。 非常適合喜歡GUI介面的初學者。

  2. PackageReference 在.csproj文件中:對於現代.NET專案,您可以直接將IronPDF新增到專案文件中:

    <PackageReference Include="IronPdf" Version="*" />
    <PackageReference Include="IronPdf" Version="*" />
    XML
  3. .NET CLI:對於偏好命令行工具或使用Visual Studio Code的開發者:

    dotnet add package IronPdf
  4. 手動下載:您可以直接從IronPDF網站下載DLL並將其作為參考新增,但此方法使更新更加困難。

為什麼安裝時需要Internet連接?

NuGet需要網路連接才能從NuGet.org儲存庫下載IronPDF及其依賴項。 該包包括核心IronPDF程式庫以及HTML轉PDF所需的Chrome渲染引擎二進制文件

對於離線安裝,您可以:

請注意,IronPDF的渲染引擎需要在首次使用時下載的額外運行時組件,所以初次PDF生成同樣從網路連接中獲益。

我如何驗證安裝是否成功?

安裝後,通過檢查這些指標來驗證IronPDF是否正常工作:

  1. 引用節點:在解決方案資源管理器中展開引用節點。 您應該能看到"IronPDF"列在您的專案引用中。

  2. IntelliSense應能識別命名空間而無錯誤。

  3. 簡單測試程式碼:新增此基本測試以驗證功能:
    
    using IronPdf;
    
    using IronPdf;
    Imports IronPdf
    $vbLabelText   $csharpLabel

// Quick verification test var renderer = new ChromePdfRenderer(); var pdf = renderer.RenderHtmlAsPdf("

Test

"); // If no exceptions occur, IronPDF is installed correctly


4. **套件管理器**:在套件管理控制台運行`Get-Package IronPdf`以查看版本資訊。

如果遇到問題,請參閱[故障排除指南](/troubleshooting/quick-ironpdf-troubleshooting/)或檢查您的[系統是否符合要求](/get-started/windows/)。

## 如何設計用於PDF生成的使用者介面?

現在新增一個標籤,並將文字設置為"使用IronPDF從HTML建立PDF"。

![Visual Studio IDE顯示Windows Forms應用程式,其中表單設計器顯示標籤,內容為](/static-assets/pdf/blog/5-steps-to-generate-a-pdf-file-in-c-sharp/5-steps-to-generate-a-pdf-file-in-c-sharp-8.webp)

接下來,從工具箱中新增一個Rich Text Box和一個按鈕。 設置按鈕文字為"轉換"。

![Windows Form應用程式介面顯示文字輸入區和用於建立PDF的轉換按鈕](/static-assets/pdf/blog/5-steps-to-generate-a-pdf-file-in-c-sharp/5-steps-to-generate-a-pdf-file-in-c-sharp-9.webp)

### 為什麼使用`TextBox`?

一個`RichTextBox`提供了多項優勢,適用於[PDF生成場景中的HTML輸入](/how-to/html-string-to-pdf/):

1. **多行支持**:HTML通常包含多行,而`TextBox`需要設置Multiline = true。

2. **格式保持**:雖然輸入的是普通HTML,但`RichTextBox`保持了縮排和換行等格式,在開發過程中讓HTML更易讀。

3. **較大容量**:`RichTextBox`可以處理較大文字量,這在處理完整HTML文件而非片段時非常實用。

4. **具備語法高亮潛力**:儘管在此基本範例中未實施,`RichTextBox`可以擴展以提供HTML語法高亮,改善開發者的使用體驗。

對於生產應用程式,考慮使用專用HTML編輯控制或與外部編輯器整合以提升使用者體驗。

### 新增哪些其他控件可以增強使用者介面?

要建立更強大的PDF生成應用程式,考慮新增這些控件:

1. **`WebBrowser`控件**:在轉換前顯示HTML預覽,幫助使用者看到他們的PDF將會怎樣。這模擬了[IronPDF的Chrome渲染引擎](/how-to/pixel-perfect-html-to-pdf/)。

2. **`ProgressBar`**:顯示大型文件或[批處理操作](/how-to/async/)的轉換進度。

3. **`ComboBox`用於範本**:提供預定義HTML範本,適用於常見的文件型別,如發票或報告。

4. **`PropertyGrid`**:允許使用者修改[PDF渲染設置](/how-to/custom-paper-size/),如頁面大小、邊距和方向。

5. **`TabControl`**:將輸入HTML、預覽和[PDF設置](/how-to/rendering-options/)分隔成組織良好的標籤。

範例,新增顯示反饋的狀態帶:
```csharp
// Add to your form
StatusStrip statusStrip = new StatusStrip();
ToolStripStatusLabel statusLabel = new ToolStripStatusLabel("Ready");
statusStrip.Items.Add(statusLabel);
this.Controls.Add(statusStrip);

我應如何命名控件以符合最佳實踐?

遵循一致的命名約定可以提高程式碼的可讀性和維護性。 以下是您的PDF生成表單的推薦做法:

  1. 使用描述性前綴

    • RichTextBox
    • btnConvert用於轉換按鈕
    • lblTitle用於標題標籤
  2. 保持一致:選擇camelCase或PascalCase並在整個專案中保持一致。

  3. 避免預設名稱:用有意義的名稱替換rtbHtmlInput

  4. 分組相關控件:對於複雜的表單,使用前綴將功能分組:

    • pdfOrientation用於PDF特定設置
    • htmlPreview用於HTML相關控件
  5. 考慮可存取性:為螢幕閱讀器設置AccessibleName

良好的命名使您的程式碼自我說明,並有助於實現如表單資料提取等功能時。

我如何編寫程式碼將HTML轉換為PDF?

雙擊"轉換"按鈕。 將打開帶有轉換按鈕單擊事件的程式碼窗口。

Visual Studio IDE顯示C# Windows Forms程式碼,部分Form1類包含空的btnConvert_Click事件處理器,用於使用IronPDF建立PDF

.cs文件的頂部新增導入IronPDF程式庫的程式碼。

首先,新增以下程式碼以使用IronPDF程式庫方法。

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

以下是目前為止btnConvert_Click事件的初始程式碼,目前空白:

private void btnConvert_Click(object sender, EventArgs e)
{

}
private void btnConvert_Click(object sender, EventArgs e)
{

}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)

End Sub
$vbLabelText   $csharpLabel

現在在按鈕點擊事件中寫以下程式碼:

private void btnConvert_Click(object sender, EventArgs e)
{
    // Declare an HtmlToPdf object
    var HtmlLine = new HtmlToPdf();

    // Get HTML text from the user
    string strHtml = txtHtml.Text;

    // Create SaveFileDialog to choose the save path for the PDF file
    SaveFileDialog saveFileDialog = new SaveFileDialog
    {
        InitialDirectory = @"D:\",
        Title = "Save PDF",
        CheckPathExists = true,
        DefaultExt = "pdf",
        Filter = "pdf files (*.pdf)|*.pdf",
        FilterIndex = 2,
        RestoreDirectory = true
    };

    // If the user presses Save
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // Get the file path from the user
        string filePath = saveFileDialog.FileName;

        // Convert HTML to PDF and save at the specified path
        using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
        PDF.SaveAs(filePath);

        // Clear the TextBox and show a message confirming the successful creation
        txtHtml.Text = "";
        MessageBox.Show("File created successfully.");
    }
}
private void btnConvert_Click(object sender, EventArgs e)
{
    // Declare an HtmlToPdf object
    var HtmlLine = new HtmlToPdf();

    // Get HTML text from the user
    string strHtml = txtHtml.Text;

    // Create SaveFileDialog to choose the save path for the PDF file
    SaveFileDialog saveFileDialog = new SaveFileDialog
    {
        InitialDirectory = @"D:\",
        Title = "Save PDF",
        CheckPathExists = true,
        DefaultExt = "pdf",
        Filter = "pdf files (*.pdf)|*.pdf",
        FilterIndex = 2,
        RestoreDirectory = true
    };

    // If the user presses Save
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        // Get the file path from the user
        string filePath = saveFileDialog.FileName;

        // Convert HTML to PDF and save at the specified path
        using var PDF = HtmlLine.RenderHtmlAsPdf(strHtml);
        PDF.SaveAs(filePath);

        // Clear the TextBox and show a message confirming the successful creation
        txtHtml.Text = "";
        MessageBox.Show("File created successfully.");
    }
}
Private Sub btnConvert_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Declare an HtmlToPdf object
	Dim HtmlLine = New HtmlToPdf()

	' Get HTML text from the user
	Dim strHtml As String = txtHtml.Text

	' Create SaveFileDialog to choose the save path for the PDF file
	Dim saveFileDialog As New SaveFileDialog With {
		.InitialDirectory = "D:\",
		.Title = "Save PDF",
		.CheckPathExists = True,
		.DefaultExt = "pdf",
		.Filter = "pdf files (*.pdf)|*.pdf",
		.FilterIndex = 2,
		.RestoreDirectory = True
	}

	' If the user presses Save
	If saveFileDialog.ShowDialog() = DialogResult.OK Then
		' Get the file path from the user
		Dim filePath As String = saveFileDialog.FileName

		' Convert HTML to PDF and save at the specified path
		Dim PDF = HtmlLine.RenderHtmlAsPdf(strHtml)
		PDF.SaveAs(filePath)

		' Clear the TextBox and show a message confirming the successful creation
		txtHtml.Text = ""
		MessageBox.Show("File created successfully.")
	End If
End Sub
$vbLabelText   $csharpLabel

解釋:

  • 建立了一個HtmlToPdf物件以利用IronPDF的轉換功能。
  • 從文字框中檢索HTML輸入。
  • 使用SaveFileDialog用於提示使用者確定生成PDF的保存位置。
  • 如果使用者選擇文件位置並按下保存,則獲得路徑。
  • 然後使用RenderHtmlAsPdf將HTML輸入渲染為PDF並保存到選擇的路徑。
  • 保存后,文字框被清除,並彈出消息框確認PDF建立。

此程式碼應新增哪些錯誤處理?

對於生產PDF生成應用程式來說,強健的錯誤處理至關重要。 這是經過增強的版本,具有全面的錯誤處理:

private void btnConvert_Click(object sender, EventArgs e)
{
    try
    {
        // Validate input
        if (string.IsNullOrWhiteSpace(txtHtml.Text))
        {
            MessageBox.Show("Please enter HTML content.", "Validation Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        var renderer = new ChromePdfRenderer();
        string strHtml = txtHtml.Text;

        SaveFileDialog saveFileDialog = new SaveFileDialog
        {
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            Title = "Save PDF",
            CheckPathExists = true,
            DefaultExt = "pdf",
            Filter = "pdf files (*.pdf)|*.pdf",
            FilterIndex = 1,
            RestoreDirectory = true
        };

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // Show progress cursor
                Cursor.Current = Cursors.WaitCursor;

                using var pdf = renderer.RenderHtmlAsPdf(strHtml);
                pdf.SaveAs(saveFileDialog.FileName);

                txtHtml.Text = "";
                MessageBox.Show("PDF created successfully!", "Success", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (IronPdf.Exceptions.IronPdfProductException ex)
            {
                // Handle licensing issues
                MessageBox.Show($"Licensing error: {ex.Message}", "License Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"An error occurred: {ex.Message}", "Error", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        // Log the full exception for debugging
        System.Diagnostics.Debug.WriteLine(ex.ToString());
    }
}
private void btnConvert_Click(object sender, EventArgs e)
{
    try
    {
        // Validate input
        if (string.IsNullOrWhiteSpace(txtHtml.Text))
        {
            MessageBox.Show("Please enter HTML content.", "Validation Error", 
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }

        var renderer = new ChromePdfRenderer();
        string strHtml = txtHtml.Text;

        SaveFileDialog saveFileDialog = new SaveFileDialog
        {
            InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            Title = "Save PDF",
            CheckPathExists = true,
            DefaultExt = "pdf",
            Filter = "pdf files (*.pdf)|*.pdf",
            FilterIndex = 1,
            RestoreDirectory = true
        };

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                // Show progress cursor
                Cursor.Current = Cursors.WaitCursor;

                using var pdf = renderer.RenderHtmlAsPdf(strHtml);
                pdf.SaveAs(saveFileDialog.FileName);

                txtHtml.Text = "";
                MessageBox.Show("PDF created successfully!", "Success", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (IronPdf.Exceptions.IronPdfProductException ex)
            {
                // Handle licensing issues
                MessageBox.Show($"Licensing error: {ex.Message}", "License Error", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show($"An error occurred: {ex.Message}", "Error", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        // Log the full exception for debugging
        System.Diagnostics.Debug.WriteLine(ex.ToString());
    }
}
Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click
    Try
        ' Validate input
        If String.IsNullOrWhiteSpace(txtHtml.Text) Then
            MessageBox.Show("Please enter HTML content.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If

        Dim renderer As New ChromePdfRenderer()
        Dim strHtml As String = txtHtml.Text

        Dim saveFileDialog As New SaveFileDialog With {
            .InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            .Title = "Save PDF",
            .CheckPathExists = True,
            .DefaultExt = "pdf",
            .Filter = "pdf files (*.pdf)|*.pdf",
            .FilterIndex = 1,
            .RestoreDirectory = True
        }

        If saveFileDialog.ShowDialog() = DialogResult.OK Then
            Try
                ' Show progress cursor
                Cursor.Current = Cursors.WaitCursor

                Using pdf = renderer.RenderHtmlAsPdf(strHtml)
                    pdf.SaveAs(saveFileDialog.FileName)
                End Using

                txtHtml.Text = ""
                MessageBox.Show("PDF created successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch ex As IronPdf.Exceptions.IronPdfProductException
                ' Handle licensing issues
                MessageBox.Show($"Licensing error: {ex.Message}", "License Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Finally
                Cursor.Current = Cursors.Default
            End Try
        End If
    Catch ex As Exception
        MessageBox.Show($"An error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ' Log the full exception for debugging
        System.Diagnostics.Debug.WriteLine(ex.ToString())
    End Try
End Sub
$vbLabelText   $csharpLabel

關鍵錯誤處理改進:

  • 在處理之前的輸入驗證
  • 特定處理IronPDF授權異常
  • 使用游標變化指示進度
  • 進行正確的異常日誌記錄以除錯
  • 使用者友好的錯誤資訊

我如何自定義PDF設置如頁面大小?

IronPDF通過ChromePdfRenderOptions類提供廣泛的自定義功能。 以下是如何實現常見的自定義:

private void ConvertWithCustomSettings()
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions
    {
        // Page setup
        PaperSize = PdfPaperSize.A4,
        PaperOrientation = PdfPaperOrientation.Portrait,
        MarginTop = 25,    // millimeters
        MarginBottom = 25,
        MarginLeft = 20,
        MarginRight = 20,

        // Rendering behavior
        EnableJavaScript = true,
        RenderDelay = 500, // milliseconds
        CreatePdfFormsFromHtml = true,

        // Headers and footers
        TextHeader = new TextHeaderFooter
        {
            CenterText = "My Document",
            FontSize = 12,
            DrawDividerLine = true
        },
        TextFooter = new TextHeaderFooter
        {
            RightText = "Page {page} of {total-pages}",
            FontSize = 10
        }
    };

    // Apply custom CSS for print
    renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

    // Generate PDF with custom settings
    var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
    pdf.SaveAs("custom-output.pdf");
}
private void ConvertWithCustomSettings()
{
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions
    {
        // Page setup
        PaperSize = PdfPaperSize.A4,
        PaperOrientation = PdfPaperOrientation.Portrait,
        MarginTop = 25,    // millimeters
        MarginBottom = 25,
        MarginLeft = 20,
        MarginRight = 20,

        // Rendering behavior
        EnableJavaScript = true,
        RenderDelay = 500, // milliseconds
        CreatePdfFormsFromHtml = true,

        // Headers and footers
        TextHeader = new TextHeaderFooter
        {
            CenterText = "My Document",
            FontSize = 12,
            DrawDividerLine = true
        },
        TextFooter = new TextHeaderFooter
        {
            RightText = "Page {page} of {total-pages}",
            FontSize = 10
        }
    };

    // Apply custom CSS for print
    renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

    // Generate PDF with custom settings
    var pdf = renderer.RenderHtmlAsPdf(txtHtml.Text);
    pdf.SaveAs("custom-output.pdf");
}
Private Sub ConvertWithCustomSettings()
    Dim renderer = New ChromePdfRenderer()

    ' Configure rendering options
    renderer.RenderingOptions = New ChromePdfRenderOptions With {
        ' Page setup
        .PaperSize = PdfPaperSize.A4,
        .PaperOrientation = PdfPaperOrientation.Portrait,
        .MarginTop = 25,    ' millimeters
        .MarginBottom = 25,
        .MarginLeft = 20,
        .MarginRight = 20,

        ' Rendering behavior
        .EnableJavaScript = True,
        .RenderDelay = 500, ' milliseconds
        .CreatePdfFormsFromHtml = True,

        ' Headers and footers
        .TextHeader = New TextHeaderFooter With {
            .CenterText = "My Document",
            .FontSize = 12,
            .DrawDividerLine = True
        },
        .TextFooter = New TextHeaderFooter With {
            .RightText = "Page {page} of {total-pages}",
            .FontSize = 10
        }
    }

    ' Apply custom CSS for print
    renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print

    ' Generate PDF with custom settings
    Dim pdf = renderer.RenderHtmlAsPdf(txtHtml.Text)
    pdf.SaveAs("custom-output.pdf")
End Sub
$vbLabelText   $csharpLabel

要了解更高級的自定義選項,請探索自定義紙張大小自定義邊距視口設置

為什麼在PDF生成中使用using語句?

PDF生成中的正確資源管理中,using語句至關重要:

  1. 自動處置:PDF文件可能消耗大量記憶體,尤其是包含圖片或大量內容時。 using語句確保在使用後妥善處置PDF物件。

  2. 文件句柄釋放:如果未正確處置,文件句柄可能保持鎖定,防止在PDF文件上執行後續操作。

  3. 記憶體管理:IronPDF的渲染引擎使用原生資源,必須釋放以防止長時間運行的應用程式中的記憶體洩漏。

以下是模式比較:

// Recommended approach with using
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
} // Resources automatically released here

// Alternative with try-finally (more verbose)
PdfDocument pdf = null;
try
{
    pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
finally
{
    pdf?.Dispose();
}
// Recommended approach with using
using (var pdf = renderer.RenderHtmlAsPdf(html))
{
    pdf.SaveAs("output.pdf");
} // Resources automatically released here

// Alternative with try-finally (more verbose)
PdfDocument pdf = null;
try
{
    pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs("output.pdf");
}
finally
{
    pdf?.Dispose();
}
' Recommended approach with Using
Using pdf = renderer.RenderHtmlAsPdf(html)
    pdf.SaveAs("output.pdf")
End Using ' Resources automatically released here

' Alternative with Try-Finally (more verbose)
Dim pdf As PdfDocument = Nothing
Try
    pdf = renderer.RenderHtmlAsPdf(html)
    pdf.SaveAs("output.pdf")
Finally
    If pdf IsNot Nothing Then
        pdf.Dispose()
    End If
End Try
$vbLabelText   $csharpLabel

對於異步操作,在C# 8.0+中使用await using

await using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
await using var pdf = await renderer.RenderHtmlAsPdfAsync(html);
Await Using pdf = Await renderer.RenderHtmlAsPdfAsync(html)
$vbLabelText   $csharpLabel

哪些常見HTML標籤效果最好?

IronPDF的Chrome渲染引擎支持所有現代HTML5標籤,但有些標籤在PDF生成中表現特別好:

文件結構:

<html>
<head>
    <meta charset="UTF-8">
    <style>
        @media print { /* PDF-specific styles */ }
        body { font-family: Arial, sans-serif; }
        .page-break { page-break-after: always; }
    </style>
</head>
<body>
    <h1>Document Title</h1>
    <div class="page-break"></div>
    <h2>New Page Content</h2>
</body>
</html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        @media print { /* PDF-specific styles */ }
        body { font-family: Arial, sans-serif; }
        .page-break { page-break-after: always; }
    </style>
</head>
<body>
    <h1>Document Title</h1>
    <div class="page-break"></div>
    <h2>New Page Content</h2>
</body>
</html>
HTML

PDF中表現最好的標籤:

  • <h6>:建立清晰的文件層次結構
  • <table>:非常適合結構化資料和發票
  • <img>:支持內嵌圖片和base64資料
  • <div>搭配CSS:精細的佈局控制
  • <span>:標準文字格式化
  • <ol>:整潔的列表格式

特別考量:

如何測試PDF生成應用程式?

當您運行專案時,您將看到以下螢幕:

Windows表單應用程式,包含一個文字輸入區域,內有簡單PDF文件的HTML程式碼及一個轉換按鈕

RichTextBox輸入HTML程式碼,例如:

<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
<h1>A Simple PDF File</h1><br><h6>Heading 6</h6>
HTML

點擊"轉換"。 您將獲得保存文件對話框。

Windows保存PDF對話框顯示文件瀏覽器,選擇了Work驅動器並將HtmlToPDF作為文件名

一旦您點擊保存按鈕,文件將以名稱和位置保存到指定路徑。

我應該首先測試哪些HTML元素?

從這些逐步複雜的HTML範例開始,以了解IronPDF的渲染能力

基本文字格式化:

<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .highlight { background-color: yellow; }
        .important { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h1>Test Document</h1>
    <p>This is <strong>bold</strong> and <em>italic</em> text.</p>
    <p class="highlight">Highlighted text example.</p>
    <p class="important">Important notice!</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        .highlight { background-color: yellow; }
        .important { color: red; font-weight: bold; }
    </style>
</head>
<body>
    <h1>Test Document</h1>
    <p>This is <strong>bold</strong> and <em>italic</em> text.</p>
    <p class="highlight">Highlighted text example.</p>
    <p class="important">Important notice!</p>
</body>
</html>
HTML

帶有樣式的表格:

<table style="border-collapse: collapse; width: 100%;">
    <tr style="background-color: #f2f2f2;">
        <th style="border: 1px solid #ddd; padding: 8px;">Product</th>
        <th style="border: 1px solid #ddd; padding: 8px;">Price</th>
    </tr>
    <tr>
        <td style="border: 1px solid #ddd; padding: 8px;">IronPDF</td>
        <td style="border: 1px solid #ddd; padding: 8px;">$999</td>
    </tr>
</table>
<table style="border-collapse: collapse; width: 100%;">
    <tr style="background-color: #f2f2f2;">
        <th style="border: 1px solid #ddd; padding: 8px;">Product</th>
        <th style="border: 1px solid #ddd; padding: 8px;">Price</th>
    </tr>
    <tr>
        <td style="border: 1px solid #ddd; padding: 8px;">IronPDF</td>
        <td style="border: 1px solid #ddd; padding: 8px;">$999</td>
    </tr>
</table>
HTML

高級功能:


<img src="___PROTECTED_URL_118___" width="200" alt="Company Logo">

<div style="page-break-after: always;"></div>

<ul>
    <li>First item</li>
    <li>Second item</li>
</ul>

<img src="___PROTECTED_URL_118___" width="200" alt="Company Logo">

<div style="page-break-after: always;"></div>

<ul>
    <li>First item</li>
    <li>Second item</li>
</ul>
HTML

測試這些元素以確保您的HTML到PDF轉換按預期運作。

如果PDF未生成應如何除錯?

當PDF生成失敗時,請按照這種系統的除錯方法操作:

  1. 啟用日誌記錄:

    IronPdf.Logging.Logger.EnableDebugging = true;
    IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt";
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
    IronPdf.Logging.Logger.EnableDebugging = true;
    IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt";
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;
    IronPdf.Logging.Logger.EnableDebugging = True
    IronPdf.Logging.Logger.LogFilePath = "IronPdfLog.txt"
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All
    $vbLabelText   $csharpLabel
  2. 檢查HTML有效性:

    // Validate HTML before conversion
    private bool IsValidHtml(string html)
    {
    try
    {
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        return doc.ParseErrors.Count() == 0;
    }
    catch
    {
        return false;
    }
    }
    // Validate HTML before conversion
    private bool IsValidHtml(string html)
    {
    try
    {
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(html);
        return doc.ParseErrors.Count() == 0;
    }
    catch
    {
        return false;
    }
    }
    ' Validate HTML before conversion
    Private Function IsValidHtml(html As String) As Boolean
        Try
            Dim doc As New HtmlAgilityPack.HtmlDocument()
            doc.LoadHtml(html)
            Return doc.ParseErrors.Count() = 0
        Catch
            Return False
        End Try
    End Function
    $vbLabelText   $csharpLabel
  3. 使用Chrome DevTools

    • 將您的HTML保存到文件並在Chrome中打開
    • 按F12檢查JavaScript錯誤
    • 查看控制檯中是否有問題
    • 使用Chrome的列印預覽查看如何渲染
  4. 常見問題和解決方案:

  5. 測試最小範例:
    // Start with the simplest possible HTML
    var testHtml = "<h1>Test</h1>";
    var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(testHtml);
    pdf.SaveAs("test.pdf");
    // Start with the simplest possible HTML
    var testHtml = "<h1>Test</h1>";
    var pdf = new ChromePdfRenderer().RenderHtmlAsPdf(testHtml);
    pdf.SaveAs("test.pdf");
    ' Start with the simplest possible HTML
    Dim testHtml = "<h1>Test</h1>"
    Dim pdf = New ChromePdfRenderer().RenderHtmlAsPdf(testHtml)
    pdf.SaveAs("test.pdf")
    $vbLabelText   $csharpLabel

運行應用程式時有哪些常見問題?

以下是初學開發者最常遇到的問題及其解決方案:

  1. "IronPdf.Exceptions.IronPdfDeploymentException"

  2. "存取被拒絕"錯誤:

    • 不要保存到受保護的目錄(例如C:\, Program Files)
    • 使用Environment.SpecialFolder獲取安全路徑
    • 檢查IIS許可權(適用於Web應用)
  3. 大文件尺寸

    • 應用PDF壓縮
      pdf.CompressImages(90); // 90% quality
      pdf.CompressImages(90); // 90% quality
      pdf.CompressImages(90) ' 90% quality
      $vbLabelText   $csharpLabel
  4. 性能慢

  5. 內容丟失

對於持續存在的問題,請參閱綜合故障排除指南

最終的PDF輸出看起來如何?

輸出PDF文件將如以下所示:

顯示簡單PDF文件的截圖,顯示標題

如何提高PDF質量?

通過這些專業技術來增強您的PDF輸出質量:

  1. 高解析度渲染:

    renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    renderer.RenderingOptions.ImageQuality = 95; // Higher quality for images
    renderer.RenderingOptions.DPI = 300; // Print-quality resolution
    renderer.RenderingOptions.PrintHtmlBackgrounds = true;
    renderer.RenderingOptions.ImageQuality = 95; // Higher quality for images
    renderer.RenderingOptions.DPI = 300; // Print-quality resolution
    renderer.RenderingOptions.PrintHtmlBackgrounds = True
    renderer.RenderingOptions.ImageQuality = 95 ' Higher quality for images
    renderer.RenderingOptions.DPI = 300 ' Print-quality resolution
    $vbLabelText   $csharpLabel
  2. 專業樣式設計:

    <style>
    @page {
        size: A4;
        margin: 2cm;
    }
    body {
        font-family: 'Segoe UI', Tahoma, sans-serif;
        line-height: 1.6;
        color: #333;
    }
    h1 {
        color: #2c3e50;
        border-bottom: 2px solid #3498db;
        padding-bottom: 10px;
    }
    </style>
    <style>
    @page {
        size: A4;
        margin: 2cm;
    }
    body {
        font-family: 'Segoe UI', Tahoma, sans-serif;
        line-height: 1.6;
        color: #333;
    }
    h1 {
        color: #2c3e50;
        border-bottom: 2px solid #3498db;
        padding-bottom: 10px;
    }
    </style>
    HTML
  3. 新增視覺元素:

  4. 針對不同用途進行優化:

為什麼輸出看起來與預期不同?

有多種因素可能導致HTML預覽與PDF輸出之間的渲染差異:

  1. CSS媒體型別:PDF預設使用列印媒體。 新增特定於列印的樣式:

    @media print {
    .no-print { display: none; }
    body { font-size: 12pt; }
    }
  2. 字體可用性嵌入自定義字體以確保一致性:

    @font-face {
    font-family: 'MyFont';
    src: url('data:font/woff2;base64,...') format('woff2');
    }
  3. 動態內容JavaScript渲染的內容需要時間載入:

    renderer.RenderingOptions.RenderDelay = 2000; // Wait 2 seconds
    renderer.RenderingOptions.RenderDelay = 2000; // Wait 2 seconds
    renderer.RenderingOptions.RenderDelay = 2000 ' Wait 2 seconds
    $vbLabelText   $csharpLabel
  4. 瀏覽器差異:IronPDF使用Chromium,請在Chrome中進行測試以獲取準確預覽。 了解Chrome渲染器

  5. 解析度和縮放:顯示器DPI與列印DPI不同。 使用視口設置以確保一致的渲染。

要實現像素完美的渲染,請遵循HTML到PDF最佳實踐指導

在本教程之後的下一步驟是什麼?

上面的教程解釋了如何使用IronPDF程式庫從HTML建立PDF。

如需更多資訊,請存取IronPDF官方網站。 該程式庫還提供支持完全自定義PDF文件編程合併和拆分文件或僅檢查顯示各種功能的範例程式碼的其他功能。

您可以使用30天試用金鑰進行評估。 目前有絕佳的優惠,您可以以兩個產品的價格獲得五個Iron Software產品。 存取此IronPDF授權資訊以了解更多關於授權的資訊。

我應該學習哪些高級功能?

在掌握基本HTML到PDF轉換之後,探索以下高級功能:

  1. PDF表單:建立可填寫的表單以收集資料:

    // Create interactive form fields
    pdf.Form.Fields.Add(new PdfTextField("name", "Enter your name", 100, 100));
    // Create interactive form fields
    pdf.Form.Fields.Add(new PdfTextField("name", "Enter your name", 100, 100));
    ' Create interactive form fields
    pdf.Form.Fields.Add(New PdfTextField("name", "Enter your name", 100, 100))
    $vbLabelText   $csharpLabel
  2. 數位簽名:為文件新增安全性和真實性

  3. PDF操作

  4. 高級渲染

  5. 性能優化
    • Web應用程式的异步渲染
    • 批量處理多個文件
    • 高效記憶體流傳輸

從與您的專案要求最相關的功能開始。

我如何從試用版過渡到生產版?

從試用過渡到生產需要以下幾個重要步驟:

  1. 選擇合適的授權

    • Lite:單個開發者,單個專案
    • Plus:單個開發者, 多個專案
    • Professional:小團隊(最多3名開發者)
    • Unlimited:Enterprise團隊
  2. 應用您的授權金鑰
    
    // In application startup
    IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
    
    // In application startup
    IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
    $vbLabelText   $csharpLabel

// Or via configuration // appsettings.json (for .NET Core) { "IronPdf.License.LicenseKey": "YOUR-LICENSE-KEY" }



3. **移除試用水印**:授權版本會自動從所有生成的PDF中移除試用水印。

4. **性能考慮事項**:
   - 使用生產規模資料進行測試
   - 實現[適當的錯誤處理](/troubleshooting/engineering-support-for-ironpdf/)
   - 設置[日誌記錄以進行監控](/how-to/custom-logging/)

5. **部屬檢查清單**:
   - 驗證[伺服器要求](/get-started/windows/)
   - 在目標[部屬平台上進行測試](/get-started/azure/)
   - 如果適用,配置[IIS](/troubleshooting/ironpdf-and-iis/)
   - 設置[持續整合](/get-started/installation-overview/)

如需詳細的授權指南,請參閱[授權FAQ](/licensing/)。

### 我可以在哪裡找到更複雜的範例?

通過以下資源擴展您的IronPDF知識:

1. **[程式碼範例程式庫](/examples/)**:
   - [發票生成](/how-to/csharp-pdf-reports/)
   - [報告建立](/how-to/csharp-pdf-reports/)
   - [批量處理](/examples/parallel/)

2. **[教程系列](/tutorials/)**:
   - [完整HTML到PDF指南](/tutorials/html-to-pdf/)
   - [從頭建立PDF](/tutorials/csharp-create-pdf-complete-tutorial/)
   - [高級PDF編輯](/tutorials/csharp-edit-pdf-complete-tutorial/)

3. **[整合指南](/how-to/html-string-to-pdf/)**:
   - [ASP.NET MVC integration](/how-to/cshtml-to-pdf-mvc-core/)
   - [Blazor應用程式](/how-to/blazor-tutorial/)
   - [Azure部署](/how-to/azure/)

4. **[API文件](/object-reference/api/)**:
   - 全面的類別參考
   - 方法簽名和參數
   - 每個功能的程式碼片段

5. **社群資源**:
   - [Stack Overflow IronPDF tag](https://stackoverflow.com/questions/tagged/ironpdf)
   - [GitHub examples](https://github.com/iron-software)
   - 通過[幫助中心](/)獲得技術支援

從最接近您的使用案例的範例開始,然後根據需要逐步探索更高級的功能。

常見問題

我如何在C#中將HTML轉換為PDF?

您可以使用IronPDF的RenderHtmlAsPdf方法將HTML字串轉換為PDF。只需建立一個HtmlToPdf物件並呼叫該方法即可將HTML渲染為PDF文件。

設置Visual Studio專案以進行PDF生成涉及哪些步驟?

首先打開Visual Studio 2019,選擇'建立新專案',選擇'Windows Forms App',並設置您的專案名稱。然後,通過NuGet安裝IronPDF來開始整合PDF生成功能。

我如何在Visual Studio中安裝PDF生成程式庫?

您可以導航至Visual Studio的封裝管理器控制台並執行命令:Install-Package IronPdf來安裝IronPDF。

為生成PDF應包括哪些組件在表單中?

包括一個指導標籤、一個用于HTML輸入的富文字框和一個標記為'轉換'的按鈕,讓使用者可以點擊以生成PDF。

我如何實現PDF文件建立的後端程式碼?

使用IronPDF聲明一個HtmlToPdf物件。從文字框中獲取HTML輸入,提示使用者保存PDF,並用RenderHtmlAsPdf方法渲染HTML。

在PDF程式庫中HtmlToPdf物件的功能是什麼?

HtmlToPdf物件在IronPDF中用於使用程式庫的全面轉換功能將HTML內容轉變為PDF文件。

我如何驗證我的PDF生成專案是否正常運行?

在Visual Studio中執行專案,將HTML輸入至RichTextBox,然後點擊'轉換'。接著,使用SaveFileDialog選擇PDF文件的保存位置,確保轉換成功完成。

PDF程式庫提供了哪些高級功能?

IronPDF允許建立完全自定義的PDF,以及通過程式合併和拆分文件。程式庫還提供各種功能的範例程式碼。

在購買之前我能否試用PDF程式庫?

可以,IronPDF的官方網站提供30天的試用金鑰,讓您在購買之前探索其功能。

我可以在哪裡找到PDF程式庫的授權詳細資訊?

IronPDF的詳細授權資訊可以在其網站的IronPDF Licensing Information頁面上找到,其中包括選項和當前優惠。

IronPDF與.NET 10相容嗎?

是的 — IronPDF已支持所有現代.NET版本,並符合計劃於2025年11月發布的.NET 10版本。它可以無須任何額外方法直接在.NET 10專案中運行。(ironpdf.com/blog/using-ironpdf/5-steps-to-generate-a-pdf-file-in-c-sharp/)

Curtis Chau
技術作家

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

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

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話