如何在 C# 中匯出 PDF | IronPDF

C# 匯出為 PDF 程式碼範例教學

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

使用 IronPDF 透過 StreamBinaryData 等簡單方法,在 C# 中將 HTML 內容匯出為 PDF。 此 C# PDF 函式庫讓開發人員能夠透過程式化方式將 HTML 轉換為 PDF 文件,並將其傳送至網頁瀏覽器或儲存至磁碟。

IronPDF 是一款 C# PDF 函式庫,讓您能夠使用 C# 將 HTML 儲存為 PDF 檔案。 它還允許 C# / VB 開發人員透過程式化方式編輯 PDF 文件。 無論是生成報告、製作發票,還是轉換網頁,IronPDF 都能為 C# 應用程式提供強大的 PDF 生成解決方案。

快速入門:使用 IronPDF 在 C# 中將 HTML 匯出為 PDF

使用 IronPDF 在 C# 中將 HTML 內容匯出為 PDF。 本指南將向您展示如何僅透過幾行程式碼,將 HTML 轉換為 PDF 文件並儲存。 IronPDF 簡化了 PDF 生成流程,讓開發人員能夠將 PDF 匯出功能整合至其應用程式中。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronPdf

    PM > Install-Package IronPdf
  2. 請複製並執行此程式碼片段。

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>HelloPDF</h1>").SaveAs("myExportedFile.pdf");
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronPDF

    arrow pointer


PDF 有哪些不同的節省選項?

在 C# 中處理 PDF 文件時,IronPDF 提供了多種選項,供您儲存及匯出所生成的 PDF 檔案。 每種方法皆適用於不同的使用情境,從簡單的檔案儲存到在網頁應用程式中提供 PDF 檔案皆可。 以下各節將介紹在 C# 中匯出與儲存 PDF 的可用選項。

如何將 PDF 儲存至磁碟

請使用 PdfDocument.SaveAs 方法將您的 PDF 儲存至磁碟。 這是針對桌面應用程式,或當您需要將 PDF 永久儲存於伺服器時,最直接的方法。

// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
// Complete example for saving PDF to disk
using IronPdf;

// Initialize the Chrome PDF renderer
var renderer = new ChromePdfRenderer();

// Create HTML content with styling
string htmlContent = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; }
        .content { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Invoice #12345</h1>
    <div class='content'>
        <p>Date: " + DateTime.Now.ToString("yyyy-MM-dd") + @"</p>
        <p>Thank you for your business!</p>
    </div>
</body>
</html>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

// Save to disk with standard method
pdf.SaveAs("invoice_12345.pdf");

// Save with password protection for sensitive documents
pdf.Password = "secure123";
pdf.SaveAs("protected_invoice_12345.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此方法支援新增密碼保護功能。 請參閱以下文章,進一步了解如何對匯出的 PDF 文件進行數位簽名:《對 PDF 文件進行數位簽名》。若需其他安全性選項,請參閱我們關於 PDF 權限與密碼的指南。

如何在 C# 中將 PDF 檔案儲存至 MemoryStream (System.IO.MemoryStream)

IronPdf.PdfDocument.Stream 屬性會使用 System.IO.MemoryStream 將 PDF 儲存至記憶體中。 當您需要在不建立臨時檔案的情況下,於記憶體中處理 PDF 資料或將其傳遞給其他方法時,此方法是理想選擇。 進一步了解如何處理 PDF 記憶體流

// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
// Example: Save PDF to MemoryStream
using IronPdf;
using System.IO;

var renderer = new ChromePdfRenderer();

// Render HTML content
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>");

// Get the PDF as a MemoryStream
MemoryStream stream = pdf.Stream;

// Example: Upload to cloud storage or database
// UploadToCloudStorage(stream);

// Example: Email as attachment without saving to disk
// EmailService.SendWithAttachment(stream, "report.pdf");

// Remember to dispose of the stream when done
stream.Dispose();
Imports IronPdf
Imports System.IO

' Example: Save PDF to MemoryStream
Dim renderer As New ChromePdfRenderer()

' Render HTML content
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Monthly Report</h1><p>Sales figures...</p>")

' Get the PDF as a MemoryStream
Dim stream As MemoryStream = pdf.Stream

' Example: Upload to cloud storage or database
' UploadToCloudStorage(stream)

' Example: Email as attachment without saving to disk
' EmailService.SendWithAttachment(stream, "report.pdf")

' Remember to dispose of the stream when done
stream.Dispose()
$vbLabelText   $csharpLabel

如何儲存為二進位資料

IronPdf.PdfDocument.BinaryData 屬性會將 PDF 文件作為二進位資料匯出至記憶體中。 這對於資料庫儲存,或與需要位元組陣列的 API 整合時,特別有用。

這會將 PDF 輸出為 ByteArray,在 C# 中則表示為 byte []

// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
// Example: Convert PDF to binary data
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure rendering options for better quality
renderer.RenderingOptions = new ChromePdfRenderOptions()
{
    MarginTop = 20,
    MarginBottom = 20,
    MarginLeft = 10,
    MarginRight = 10,
    PaperSize = IronPdf.Rendering.PdfPaperSize.A4
};

// Render content to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>");

// Get binary data
byte[] binaryData = pdf.BinaryData;

// Example: Store in database
// database.StorePdfDocument(documentId, binaryData);

// Example: Send via API
// apiClient.UploadDocument(binaryData);
Imports IronPdf

' Example: Convert PDF to binary data
Dim renderer As New ChromePdfRenderer()

' Configure rendering options for better quality
renderer.RenderingOptions = New ChromePdfRenderOptions() With {
    .MarginTop = 20,
    .MarginBottom = 20,
    .MarginLeft = 10,
    .MarginRight = 10,
    .PaperSize = IronPdf.Rendering.PdfPaperSize.A4
}

' Render content to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Contract Document</h1>")

' Get binary data
Dim binaryData As Byte() = pdf.BinaryData

' Example: Store in database
' database.StorePdfDocument(documentId, binaryData)

' Example: Send via API
' apiClient.UploadDocument(binaryData)
$vbLabelText   $csharpLabel

若需處理涉及二進位資料操作的進階情境,請參閱我們關於將 PDF 轉換為 MemoryStream 的指南。

如何從網頁伺服器向瀏覽器提供服務

若要將 PDF 發佈至網頁,我們需要以二進位資料而非 HTML 的形式傳送該檔案。 這對於需要讓使用者直接在瀏覽器中下載或檢視 PDF 的網路應用程式而言至關重要。 IronPDF 可與 MVC 及傳統 ASP.NET 應用程式整合。

MVC PDF 匯出

在現代 MVC 應用程式中,使用 FileStreamResult 即可輕鬆提供 PDF 檔案。 此方法適用於 ASP.NET Core MVC 應用程式

// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
// MVC Controller method for PDF export
public IActionResult DownloadInvoice(int invoiceId)
{
    // Generate your HTML content
    string htmlContent = GenerateInvoiceHtml(invoiceId);

    // Create PDF using IronPDF
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Get the PDF stream
    MemoryStream stream = pdf.Stream;

    // Reset stream position
    stream.Position = 0;

    // Return file to browser - will prompt download
    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = $"invoice_{invoiceId}.pdf"
    };
}

// Alternative: Display PDF in browser instead of downloading
public IActionResult ViewInvoice(int invoiceId)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId));

    // Return PDF for browser viewing
    return File(pdf.BinaryData, "application/pdf");
}
Imports System.IO
Imports Microsoft.AspNetCore.Mvc
Imports IronPdf

' MVC Controller method for PDF export
Public Function DownloadInvoice(invoiceId As Integer) As IActionResult
    ' Generate your HTML content
    Dim htmlContent As String = GenerateInvoiceHtml(invoiceId)

    ' Create PDF using IronPDF
    Dim renderer As New ChromePdfRenderer()
    Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

    ' Get the PDF stream
    Dim stream As MemoryStream = pdf.Stream

    ' Reset stream position
    stream.Position = 0

    ' Return file to browser - will prompt download
    Return New FileStreamResult(stream, "application/pdf") With {
        .FileDownloadName = $"invoice_{invoiceId}.pdf"
    }
End Function

' Alternative: Display PDF in browser instead of downloading
Public Function ViewInvoice(invoiceId As Integer) As IActionResult
    Dim renderer As New ChromePdfRenderer()
    Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(GenerateInvoiceHtml(invoiceId))

    ' Return PDF for browser viewing
    Return File(pdf.BinaryData, "application/pdf")
End Function
$vbLabelText   $csharpLabel

ASP.NET PDF 匯出

對於傳統的 ASP.NET WebForms 應用程式,您可以透過 Response 物件直接提供 PDF 檔案:

// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
// ASP.NET WebForms PDF export
protected void ExportButton_Click(object sender, EventArgs e)
{
    // Create your PDF document
    var renderer = new ChromePdfRenderer();

    // Configure rendering options
    renderer.RenderingOptions = new ChromePdfRenderOptions()
    {
        PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        PrintHtmlBackgrounds = true,
        CreatePdfFormsFromHtml = true
    };

    // Generate PDF from current page or custom HTML
    PdfDocument MyPdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml());

    // Retrieves the PDF binary data
    byte[] Binary = MyPdfDocument.BinaryData;

    // Clears the existing response content
    Response.Clear();

    // Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream";

    // Add content disposition header for download
    Response.AddHeader("Content-Disposition", 
        "attachment; filename=report_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");

    // Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length);

    // Flushes the response to send the data to the client
    Response.Flush();

    // End the response
    Response.End();
}
' ASP.NET WebForms PDF export
Protected Sub ExportButton_Click(sender As Object, e As EventArgs)
    ' Create your PDF document
    Dim renderer As New ChromePdfRenderer()

    ' Configure rendering options
    renderer.RenderingOptions = New ChromePdfRenderOptions() With {
        .PaperSize = IronPdf.Rendering.PdfPaperSize.Letter,
        .PrintHtmlBackgrounds = True,
        .CreatePdfFormsFromHtml = True
    }

    ' Generate PDF from current page or custom HTML
    Dim MyPdfDocument As PdfDocument = renderer.RenderHtmlAsPdf(GetReportHtml())

    ' Retrieves the PDF binary data
    Dim Binary As Byte() = MyPdfDocument.BinaryData

    ' Clears the existing response content
    Response.Clear()

    ' Sets the response content type to 'application/octet-stream', suitable for PDF files
    Response.ContentType = "application/octet-stream"

    ' Add content disposition header for download
    Response.AddHeader("Content-Disposition", "attachment; filename=report_" & DateTime.Now.ToString("yyyyMMdd") & ".pdf")

    ' Writes the binary data to the response output stream
    Context.Response.OutputStream.Write(Binary, 0, Binary.Length)

    ' Flushes the response to send the data to the client
    Response.Flush()

    ' End the response
    Response.End()
End Sub
$vbLabelText   $csharpLabel

進階匯出情境

批次 PDF 匯出

處理多個 PDF 檔案時,您可以優化匯出流程:

// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
// Batch export multiple PDFs to a zip file
public void ExportMultiplePdfsAsZip(List<string> htmlDocuments, string zipFilePath)
{
    using (var zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create))
    {
        var renderer = new ChromePdfRenderer();

        for (int i = 0; i < htmlDocuments.Count; i++)
        {
            // Render each HTML document
            PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlDocuments[i]);

            // Add to zip archive
            var entry = zipArchive.CreateEntry($"document_{i + 1}.pdf");
            using (var entryStream = entry.Open())
            {
                pdf.Stream.CopyTo(entryStream);
            }
        }
    }
}
Imports System.IO.Compression

' Batch export multiple PDFs to a zip file
Public Sub ExportMultiplePdfsAsZip(htmlDocuments As List(Of String), zipFilePath As String)
    Using zipArchive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)
        Dim renderer = New ChromePdfRenderer()

        For i As Integer = 0 To htmlDocuments.Count - 1
            ' Render each HTML document
            Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlDocuments(i))

            ' Add to zip archive
            Dim entry = zipArchive.CreateEntry($"document_{i + 1}.pdf")
            Using entryStream = entry.Open()
                pdf.Stream.CopyTo(entryStream)
            End Using
        Next
    End Using
End Sub
$vbLabelText   $csharpLabel

基於使用者權限的條件式匯出

// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
// Export with different options based on user role
public byte[] ExportPdfWithPermissions(string htmlContent, UserRole userRole)
{
    var renderer = new ChromePdfRenderer();
    PdfDocument pdf = renderer.RenderHtmlAsPdf(htmlContent);

    // Apply security based on user role
    if (userRole == UserRole.Guest)
    {
        // Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = false;
        pdf.SecuritySettings.AllowUserCopyPasteContent = false;
    }
    else if (userRole == UserRole.Standard)
    {
        // Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = true;
        pdf.SecuritySettings.AllowUserEditing = false;
    }

    return pdf.BinaryData;
}
' Export with different options based on user role
Public Function ExportPdfWithPermissions(htmlContent As String, userRole As UserRole) As Byte()
    Dim renderer As New ChromePdfRenderer()
    Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(htmlContent)

    ' Apply security based on user role
    If userRole = UserRole.Guest Then
        ' Restrict printing and copying for guests
        pdf.SecuritySettings.AllowUserPrinting = False
        pdf.SecuritySettings.AllowUserCopyPasteContent = False
    ElseIf userRole = UserRole.Standard Then
        ' Allow printing but not editing
        pdf.SecuritySettings.AllowUserPrinting = True
        pdf.SecuritySettings.AllowUserEditing = False
    End If

    Return pdf.BinaryData
End Function
$vbLabelText   $csharpLabel

PDF 匯出最佳實務

在生產環境應用程式中匯出 PDF 時,請遵循以下最佳實務:

  1. 記憶體管理:針對大型 PDF 檔案或高流量應用程式,應妥善釋放 PDF 物件與資料流,以防止記憶體洩漏。 建議使用 async 方法以提升效能。
  2. 錯誤處理:在匯出 PDF 時,務必實施適當的錯誤處理機制,特別是在可能發生網路問題的網頁應用程式中。
  3. 壓縮:對於大型 PDF 檔案,請在提供給使用者之前使用 PDF 壓縮功能來減小檔案大小。
  4. 元資料:設定適當的 PDF 元資料(包括標題、作者及建立日期),以利文件管理。
  5. 跨平台相容性:確保您的匯出功能能在不同平台上正常運作。 IronPDF 支援 LinuxmacOS

結論

IronPDF 為 C# 應用程式提供全面的 PDF 匯出選項,從簡單的檔案儲存到複雜的網頁伺服器情境皆能涵蓋。 根據您的使用情境選用合適的匯出方式,可讓您在維持安全與效能標準的同時,高效地產生並傳送 PDF 文件給使用者。

常見問題

如何在 C# 中將 HTML 內容匯出為 PDF?

您可透過 IronPDF 的 ChromePdfRenderer 類別,在 C# 中將 HTML 匯出為 PDF。只需建立一個渲染器實例,使用 RenderHtmlAsPdf() 方法轉換 HTML 內容,然後透過 SaveAs() 方法儲存即可。IronPDF 讓您能輕鬆地將 HTML 字串、檔案或 URL 直接轉換為 PDF 文件。

using C# 儲存 PDF 有哪些不同的方法?

IronPDF 提供多種儲存 PDF 的方法:SaveAs() 用於儲存至磁碟、Stream 用於在 Web 應用程式中提供 PDF 而不建立臨時檔案,以及 BinaryData 用於將 PDF 取得為位元組陣列。IronPDF 中的每種方法皆適用於不同的使用情境,從簡單的檔案儲存到動態的 Web 傳輸皆可涵蓋。

我能否將 PDF 儲存至記憶體而非磁碟?

是的,IronPDF 允許您使用 System.IO.MemoryStream 將 PDF 儲存至記憶體中。此功能對於需要直接向使用者提供 PDF 而不需在伺服器上建立暫存檔的網頁應用程式非常實用。您可以使用 Stream 屬性,或將 PDF 轉換為二進位資料。

如何在儲存 PDF 時新增密碼保護?

IronPDF 允許透過在儲存前設定 PdfDocument 物件的 Password 屬性來啟用密碼保護。只需將密碼字串賦值給 pdf.Password,然後使用 SaveAs() 即可建立受保護的 PDF 檔案,該檔案需輸入密碼才能開啟。

我能否在不儲存至磁碟的情況下,直接將 PDF 傳送至網頁瀏覽器?

是的,IronPDF 允許您將 PDF 直接作為二進位資料傳送至網頁瀏覽器。您可以使用 BinaryData 屬性將 PDF 取得為位元組陣列,並透過您的網頁應用程式的回應串流傳送,從而無需暫存檔案。

有什麼最簡單的方法,能用一行指令將 HTML 轉換並儲存為 PDF?

IronPDF 提供一行代碼即可完成的解決方案:new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("您的 HTML").SaveAs("output.pdf")。這段代碼透過單一行指令,即可建立渲染器、將 HTML 轉換為 PDF,並將其儲存至磁碟。

Curtis Chau
技術撰稿人

Curtis Chau 擁有卡爾頓大學(Carleton University)的電腦科學學士學位,專精於前端開發,並精通 Node.js、TypeScript、JavaScript 及 React。他熱衷於打造直觀且美觀的用戶介面,喜歡運用現代框架,並創建結構完善、視覺上吸引人的手冊。

除了開發工作之外,Curtis 對物聯網(IoT)抱有濃厚興趣,致力於探索整合硬體與軟體的創新方法。閒暇時,他喜歡玩遊戲和開發 Discord 機器人,將對科技的熱愛與創意相結合。

審閱者:
Jeff Fritz
Jeffrey T. Fritz
首席程式經理 - .NET 社群團隊
Jeff 同時也是 .NET 與 Visual Studio 團隊的首席程式經理。他是 .NET Conf 虛擬會議系列的執行製作人,並主持每週播出兩次的開發者直播節目《Fritz and Friends》,在節目中他會與觀眾一起探討技術話題並共同編寫程式碼。Jeff 負責撰寫工作坊內容、準備簡報,並為 Microsoft Build、Microsoft Ignite、.NET Conf 以及 Microsoft MVP Summit 等微軟最大規模的開發者活動規劃內容。
準備開始了嗎?
Nuget 下載 19,014,616 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronPdf
執行範例 觀看您的 HTML 轉為 PDF。