如何在 .NET Core 中產生 PDF 文件

How to Convert HTML to PDF in .NET Core

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

由於 PDF 格式的嚴格標準,從各種格式轉換為 PDF 可能具有挑戰性。 在許多情況下,轉換可能無法一對一匹配,特別是當涉及到 HTML 和 CSS 樣式時。 然而,在當今的數位環境中,能夠轉換 URL 和表單(包括那些帶有 HTML 和 CSS 的)是至關重要的。 這就是 IronPDF 突出的地方,它提供直觀的特點,使開發者能夠以高保真度將多種格式轉換為 PDF,通常只需幾行代碼即可。

使用 IronPDF,您可以輕鬆地將 HTML、DOCX、RTF、Markdown,甚至圖像轉換為 PDF,確保文檔的完整性得以保持。 它還支持從流行的框架如 Razor、CSHTML、ASPX 和 XAML 的動態網頁轉換,消除兼容性問題,使 IronPDF 成為您的全面 PDF 轉換解決方案。

除了簡單的轉換外,IronPDF 還提供強大的自定義選項。 您可以通過自定義邊距、頁眉和頁尾調整頁碼,並調整灰階設置以減小文件大小。此外,您還可以通過增強功能來改善文檔,例如目錄、自動分頁符和縮放到所需文檔尺寸的內容。

在本教程中,我們將探索這些功能以及更多,提供代碼示例並強調 IronPDF 的關鍵特點。 準備好改變您的 PDF 轉換過程,讓您能夠輕鬆使用 IronPDF 轉換、自定義和優化您的 PDF 文檔。

快速入門: 使用 IronPDF 將 HTML 轉換為 PDF

開始使用 IronPDF ,在 .NET Core 中輕鬆將 HTML 轉換為 PDF。 只需一行代碼,您就可以使用 IronPDF 功能強大的 API 從 HTML 字串生成完美的 PDF。 本指南將展示如何快速將 IronPDF 集成到您的項目中,實現無縫的 PDF 生成,設置時間最少。無論您是在轉換 HTML、URLs 還是 Razor 頁面,IronPDF 都簡化了這一過程,使其易於各級開發者使用。 立即開始轉換並探索更多高級功能。

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello, PDF!</h1>");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer

目錄

立即開始在您的項目中使用 IronPDF 並免費試用。

第一步:
green arrow pointer
NuGet 用 NuGet 安裝

PM >  Install-Package IronPdf

NuGet 查看 https://www.nuget.org/packages/IronPdf 以快速安裝。超過 1000 萬次下載,它正在用 C# 改變 PDF 開發。 您還可以下載 DLLWindows 安裝程序

多功能 PDF 轉換

從 HTML 字串生成 PDF

要從 HTML 字串轉換為 PDF,我們可以使用 RenderHtmlAsPdf 方法快速將 HTML 字串轉換為像素完美的 PDF。

:path=/static-assets/pdf/content-code-examples/how-to/html-string-to-pdf.cs
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a HTML string using C#
var pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from a HTML string using C#
Private pdf = renderer.RenderHtmlAsPdf("<h1>Hello World</h1>")

' Export to a file or Stream
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

從 HTML 文件生成 PDF

使用 RenderHtmlAsPdf 方法輕鬆地將 HTML 文件轉換為 PDF,並快速保存像素完美的 PDF。

:path=/static-assets/pdf/content-code-examples/how-to/html-file-to-pdf.cs
using IronPdf;
using IronPdf.Engines.Chrome;
using IronPdf.Rendering;


var renderer = new ChromePdfRenderer
{
    RenderingOptions = new ChromePdfRenderOptions
    {
        CssMediaType = PdfCssMediaType.Print,
        MarginBottom = 0,
        MarginLeft = 0,
        MarginRight = 0,
        MarginTop = 0,
        Timeout = 120,
    },
};
renderer.RenderingOptions.WaitFor.RenderDelay(50);

// Create a PDF from an existing HTML file using C#
var pdf = renderer.RenderHtmlFileAsPdf("example.html");

// Export to a file or Stream
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports IronPdf.Engines.Chrome
Imports IronPdf.Rendering


Private renderer = New ChromePdfRenderer With {
	.RenderingOptions = New ChromePdfRenderOptions With {
		.CssMediaType = PdfCssMediaType.Print,
		.MarginBottom = 0,
		.MarginLeft = 0,
		.MarginRight = 0,
		.MarginTop = 0,
		.Timeout = 120
	}
}
renderer.RenderingOptions.WaitFor.RenderDelay(50)

' Create a PDF from an existing HTML file using C#
Dim pdf = renderer.RenderHtmlFileAsPdf("example.html")

' Export to a file or Stream
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

從 URL 生成 PDF

只需幾行代碼,用 RenderUrlAsPdf 快速將 URL 轉換為 PDF。 輸入 URL 作為參數並輕鬆保存。

:path=/static-assets/pdf/content-code-examples/how-to/url-to-pdf.cs
using IronPdf;

// Instantiate Renderer
var renderer = new ChromePdfRenderer();

// Create a PDF from a URL or local file path
var pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Export to a file or Stream
pdf.SaveAs("url.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Create a PDF from a URL or local file path
Private pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

' Export to a file or Stream
pdf.SaveAs("url.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將圖像轉換為 PDF

是否有想要以 PDF 顯示的圖像? 使用我們的 ImageToPdfConverter 類並調用 ImageToPdf 方法快速進行轉換。

:path=/static-assets/pdf/content-code-examples/how-to/image-to-pdf-convert-one-image.cs
using IronPdf;

string imagePath = "meetOurTeam.jpg";

// Convert an image to a PDF
PdfDocument pdf = ImageToPdfConverter.ImageToPdf(imagePath);

// Export the PDF
pdf.SaveAs("imageToPdf.pdf");
Imports IronPdf

Private imagePath As String = "meetOurTeam.jpg"

' Convert an image to a PDF
Private pdf As PdfDocument = ImageToPdfConverter.ImageToPdf(imagePath)

' Export the PDF
pdf.SaveAs("imageToPdf.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

從 PDF 提取圖像

對於上述例子的相反操作,我們首先將輸入轉換為 PDF,然後使用 RasterizeToImageFiles 方法將 PDF 轉換為圖像。

:path=/static-assets/pdf/content-code-examples/how-to/rasterize-pdf-to-images-rasterize.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render PDF from web URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Export images from PDF
pdf.RasterizeToImageFiles("wikipage_*.png");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將 DOCX 轉換為 PDF

是否曾需要輕鬆將 DOCX 文件(如履歷)轉換為 PDF? IronPDF 可以滿足您的需求。 只需調用 RenderDocxAsPDF 進行轉換。

:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");

// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()

' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")

' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將 RTF 轉換為 PDF

要將 RTF 文件轉換為 PDF,我們用 RTF 文件作為輸入調用 RenderRtfFileAsPdf

:path=/static-assets/pdf/content-code-examples/how-to/rtf-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render from RTF file
PdfDocument pdf = renderer.RenderRtfFileAsPdf("sample.rtf");

// Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Render from RTF file
Private pdf As PdfDocument = renderer.RenderRtfFileAsPdf("sample.rtf")

' Save the PDF
pdf.SaveAs("pdfFromRtfFile.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將 MD 轉換為 PDF

要將 MD 轉換成 PDF,我們可以用 MD 文件作為輸入調用 RenderMarkdownFileAsPdf 方法。

:path=/static-assets/pdf/content-code-examples/how-to/md-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render from markdown file
PdfDocument pdf = renderer.RenderMarkdownFileAsPdf("sample.md");

// Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Render from markdown file
Private pdf As PdfDocument = renderer.RenderMarkdownFileAsPdf("sample.md")

' Save the PDF
pdf.SaveAs("pdfFromMarkdownFile.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將 XML 轉換為 PDF

雖然將 XML 轉換為 PDF 可能非常挑戰,但 IronPDF 仍迎接挑戰,並幫助在幾個步驟內將 XML 轉換為 PDF。 我們從 XLST 模板開始,然後透過 XLST 變換將 XML 轉換為 PDF。 以下是幫助您開始的代碼片段的縮短版本。

// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";

// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
";

// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();

// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}

// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
// XSLT template that defines the transformation from XML to HTML
string xslt = @"<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
";

// XML data to transform
string xml = @"<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
";

// Create an instance of XslCompiledTransform
XslCompiledTransform transform = new XslCompiledTransform();

// Load the XSLT from a string
using (XmlReader reader = XmlReader.Create(new StringReader(xslt)))
{
    transform.Load(reader);
}

// Transform the XML to HTML
StringWriter results = new StringWriter();
using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
{
    transform.Transform(reader, null, results);
}

// Create a renderer for converting HTML to PDF
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
// Options, headers, and footers may be set here if needed
// Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf");
' XSLT template that defines the transformation from XML to HTML
Dim xslt As String = "<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>
<xsl:template match='/'>
<html>
<style>
td{
  text-align: center;
  padding: 20px;
  border: 1px solid #CDE7F0;
}
th{
  color: white;
  padding: 20px;
}
</style>
<body style='font-family: Arial, Helvetica Neue, Helvetica, sans-serif;'>
  <table style='border-collapse: collapse;'>
    <thead>
      <tr>
        <th colspan='3'>
          <img style='margin: auto;' src='https://ironsoftware.com/img/svgs/ironsoftware-logo-black.svg'/>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr bgcolor='#9acd32'>
        <th bgcolor='#32ab90'>Title</th>
        <th bgcolor='#f49400'>Feature</th>
        <th bgcolor='#2a95d5'>Compatible</th>
      </tr>
      <xsl:for-each select='catalog/cd'>
      <tr>
        <td style='font-weight: bold;'><xsl:value-of select='title'/></td>
        <td style='background-color: #eff8fb; color: #2a95d5; font-weight: bold;'><xsl:value-of select='feature'/></td>
        <td><xsl:value-of select='compatible'/></td>
      </tr>
      </xsl:for-each>
    </tbody>
  </table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
"

' XML data to transform
Dim xml As String = "<?xml version='1.0' encoding='UTF-8'?>
<catalog>
  <cd>
    <title>IronPDF</title>
    <feature>Generate, format and manipulate PDFs</feature>
    <compatible>Microsoft Windows, Linux (Debian, CentOS, Ubuntu), MacOS, Docker (Windows, Linux, Azure), Azure (VPS, Webapps, Websites, Functions), AWS</compatible>
  </cd>
  <cd>
    <title>IronOCR</title>
    <feature>OCR engine, input, result</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
  <cd>
    <title>IronBarcode</title>
    <feature>Format, read and write Barcode</feature>
    <compatible>Microsoft Windows, Linux, MacOS, Docker, Azure, AWS</compatible>
  </cd>
</catalog>
"

' Create an instance of XslCompiledTransform
Dim transform As New XslCompiledTransform()

' Load the XSLT from a string
Using reader As XmlReader = XmlReader.Create(New StringReader(xslt))
	transform.Load(reader)
End Using

' Transform the XML to HTML
Dim results As New StringWriter()
Using reader As XmlReader = XmlReader.Create(New StringReader(xml))
	transform.Transform(reader, Nothing, results)
End Using

' Create a renderer for converting HTML to PDF
Dim renderer As New IronPdf.ChromePdfRenderer()
' Options, headers, and footers may be set here if needed
' Render our XML as a PDF via XSLT transformation
renderer.RenderHtmlAsPdf(results.ToString()).SaveAs("Final.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

將 PDF 轉換為 HTML

除了將各種格式轉換為 PDF 之外,IronPDF 還支持將 PDF 轉換為 HTML 的相反操作。 這裡有一個快速代碼片段來顯示這項功能。

:path=/static-assets/pdf/content-code-examples/how-to/pdf-to-html.cs
using IronPdf;
using System;

PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Convert PDF to HTML string
string html = pdf.ToHtmlString();
Console.WriteLine(html);

// Convert PDF to HTML file
pdf.SaveAsHtml("myHtml.html");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

動態網頁到 PDFs

您需要您的動態網頁被保存並轉換為 PDF 同時保留布局和格式嗎? 選擇 IronPDF,它可以快速將多種流行的動態網頁框架轉換為 PDFs。

從 ASPX 頁面生成 PDF

以下是將 ASPX 頁面作為 PDF 轉換的一段簡短代碼片段。

:path=/static-assets/pdf/content-code-examples/how-to/aspx-to-pdf-2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IronPdf;

namespace AspxToPdfTutorial
{
    public partial class Invoice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser);
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports IronPdf

Namespace AspxToPdfTutorial
	Partial Public Class Invoice
		Inherits System.Web.UI.Page

		Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
			IronPdf.AspxToPdf.RenderThisPageAsPdf(IronPdf.AspxToPdf.FileBehavior.InBrowser)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

XAML 轉換為 PDF (MAUI)

對於希望構建跨平台應用的開發者,.NET MAUI 是框架中一個受歡迎的選擇。 IronPDF 全力支持將 XAML 轉換為 PDF,且只需幾個步驟。

:path=/static-assets/pdf/content-code-examples/how-to/xaml-to-pdf-maui-mainpage-xaml-cs.cs
using IronPdf.Extensions.Maui;

namespace mauiSample;

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void PrintToPdf(object sender, EventArgs e)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Apply HTML header
        renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter()
        {
            HtmlFragment = "<h1>Header</h1>",
        };

        // Render PDF from Maui Page
        PdfDocument pdf = renderer.RenderContentPageToPdf<MainPage, App>().Result;

        pdf.SaveAs(@"C:\Users\lyty1\Downloads\contentPageToPdf.pdf");
    }
}
Imports IronPdf.Extensions.Maui

Namespace mauiSample

	Partial Public Class MainPage
		Inherits ContentPage

		Public Sub New()
			InitializeComponent()
		End Sub

		Private Sub PrintToPdf(ByVal sender As Object, ByVal e As EventArgs)
			Dim renderer As New ChromePdfRenderer()

			' Apply HTML header
			renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter() With {.HtmlFragment = "<h1>Header</h1>"}

			' Render PDF from Maui Page
			Dim pdf As PdfDocument = renderer.RenderContentPageToPdf(Of MainPage, App)().Result

			pdf.SaveAs("C:\Users\lyty1\Downloads\contentPageToPdf.pdf")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

生成 PDF 報告

當談到生成 PDF 報告時,精確的尺寸和格式至關重要。 因此,IronPDF 允許您只需幾個步驟就能無縫生成 PDFs。

:path=/static-assets/pdf/content-code-examples/how-to/csharp-pdf-reports-render-html-file.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

renderer.RenderHtmlFileAsPdf("report.html").SaveAs("report.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

在 Blazor 伺服器中建立 PDF

IronPDF 支持 .NET 6,由於它包含如 Blazor 這類專案類型,這段代碼片段提供了一個如何在 Blazor Server 中建立 PDFs 的簡短示例。

@code {

    // Model to bind user input
    private InputHTMLModel _InputMsgModel = new InputHTMLModel();

    private async Task SubmitHTML()
    {
        // Set your IronPDF license key
        IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

        // Create a renderer to convert HTML to PDF
        var render = new IronPdf.ChromePdfRenderer();

        // Render the HTML input into a PDF document
        var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);

        var fileName = "iron.pdf";

        // Create a stream reference for the PDF content
        using var streamRef = new DotNetStreamReference(stream: doc.Stream);

        // Invoke JavaScript function to download the PDF in the browser
        await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
    }

    public class InputHTMLModel
    {
        public string HTML { get; set; } = "My new message";
    }
}
@code {

    // Model to bind user input
    private InputHTMLModel _InputMsgModel = new InputHTMLModel();

    private async Task SubmitHTML()
    {
        // Set your IronPDF license key
        IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

        // Create a renderer to convert HTML to PDF
        var render = new IronPdf.ChromePdfRenderer();

        // Render the HTML input into a PDF document
        var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);

        var fileName = "iron.pdf";

        // Create a stream reference for the PDF content
        using var streamRef = new DotNetStreamReference(stream: doc.Stream);

        // Invoke JavaScript function to download the PDF in the browser
        await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
    }

    public class InputHTMLModel
    {
        public string HTML { get; set; } = "My new message";
    }
}
code
If True Then

	' Model to bind user input
	private InputHTMLModel _InputMsgModel = New InputHTMLModel()

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	private async Task SubmitHTML()
'	{
'		' Set your IronPDF license key
'		IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";
'
'		' Create a renderer to convert HTML to PDF
'		var render = New IronPdf.ChromePdfRenderer();
'
'		' Render the HTML input into a PDF document
'		var doc = render.RenderHtmlAsPdf(_InputMsgModel.HTML);
'
'		var fileName = "iron.pdf";
'
'		' Create a stream reference for the PDF content
'		var streamRef = New DotNetStreamReference(stream: doc.Stream);
'
'		' Invoke JavaScript function to download the PDF in the browser
'		await JS.InvokeVoidAsync("SubmitHTML", fileName, streamRef);
'	}

'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	public class InputHTMLModel
'	{
'		public string HTML
'		{
'			get;
'			set;
'		} = "My new message";
'	}
End If
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

Razor 轉換為 PDF (Blazor Servers)

除了能夠在 Blazor 伺服器中生成 PDFs,IronPDF 還支持從 Blazor 頁面中的 Razor 元件生成 PDF 文檔。 使得 PDF 文件和頁面的創建更加流暢。

[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();

protected override async Task OnInitializedAsync()
{
    persons = new List<PersonInfo>
    {
        new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
        new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
        new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
}
private async void PrintToPdf()
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Apply text footer
    renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} - {time}",
            DrawDividerLine = true,
            RightText = "Page {page} of {total-pages}",
            Font = IronSoftware.Drawing.FontTypes.Arial,
            FontSize = 11
        };

    Parameters.Add("persons", persons);

    // Render razor component to PDF
    PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);

    File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
[Parameter]
public IEnumerable<PersonInfo> persons { get; set; }
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();

protected override async Task OnInitializedAsync()
{
    persons = new List<PersonInfo>
    {
        new PersonInfo { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
        new PersonInfo { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
        new PersonInfo { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
}
private async void PrintToPdf()
{
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Apply text footer
    renderer.RenderingOptions.TextFooter = new TextHeaderFooter()
        {
            LeftText = "{date} - {time}",
            DrawDividerLine = true,
            RightText = "Page {page} of {total-pages}",
            Font = IronSoftware.Drawing.FontTypes.Arial,
            FontSize = 11
        };

    Parameters.Add("persons", persons);

    // Render razor component to PDF
    PdfDocument pdf = renderer.RenderRazorComponentToPdf<Person>(Parameters);

    File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData);
}
<Parameter>
Public Property persons() As IEnumerable(Of PersonInfo)
Public Property Parameters() As New Dictionary(Of String, Object)()

Protected Overrides Async Function OnInitializedAsync() As Task
	persons = New List(Of PersonInfo) From {
		New PersonInfo With {
			.Name = "Alice",
			.Title = "Mrs.",
			.Description = "Software Engineer"
		},
		New PersonInfo With {
			.Name = "Bob",
			.Title = "Mr.",
			.Description = "Software Engineer"
		},
		New PersonInfo With {
			.Name = "Charlie",
			.Title = "Mr.",
			.Description = "Software Engineer"
		}
	}
End Function
Private Async Sub PrintToPdf()
	Dim renderer As New ChromePdfRenderer()

	' Apply text footer
	renderer.RenderingOptions.TextFooter = New TextHeaderFooter() With {
		.LeftText = "{date} - {time}",
		.DrawDividerLine = True,
		.RightText = "Page {page} of {total-pages}",
		.Font = IronSoftware.Drawing.FontTypes.Arial,
		.FontSize = 11
	}

	Parameters.Add("persons", persons)

	' Render razor component to PDF
	Dim pdf As PdfDocument = renderer.RenderRazorComponentToPdf(Of Person)(Parameters)

	File.WriteAllBytes("razorComponentToPdf.pdf", pdf.BinaryData)
End Sub
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

CSHTML 轉換為 PDF

將 CSHTML(Razor)轉換為 PDF 可以讓您直接從您的網頁應用中生成專業、準備打印的文檔。 這對於發票、報告、合同或任何動態內容都很有用。 IronPDF 支持 Razor Pages、MVC Core 與 MVC Framework,以及無頭渲染,使得 PDF 生成能夠無縫集成到您的 .NET 應用中,只需幾行代碼即可。

CSHTML 轉換為 PDF (Razor Pages)

using IronPdf.Razor.Pages;

public IActionResult OnPostAsync()
{
    persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };

    ViewData["personList"] = persons;

    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render Razor Page to PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    Response.Headers.Add("Content-Disposition", "inline");

    return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
using IronPdf.Razor.Pages;

public IActionResult OnPostAsync()
{
    persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };

    ViewData["personList"] = persons;

    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render Razor Page to PDF document
    PdfDocument pdf = renderer.RenderRazorToPdf(this);

    Response.Headers.Add("Content-Disposition", "inline");

    return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf");
}
Imports IronPdf.Razor.Pages

Public Function OnPostAsync() As IActionResult
	persons = New List(Of Person) From {
		New Person With {
			.Name = "Alice",
			.Title = "Mrs.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Bob",
			.Title = "Mr.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Charlie",
			.Title = "Mr.",
			.Description = "Software Engineer"
		}
	}

	ViewData("personList") = persons

	Dim renderer As New ChromePdfRenderer()

	' Render Razor Page to PDF document
	Dim pdf As PdfDocument = renderer.RenderRazorToPdf(Me)

	Response.Headers.Add("Content-Disposition", "inline")

	Return File(pdf.BinaryData, "application/pdf", "razorPageToPdf.pdf")
End Function
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

CSHTML 轉換為 PDF (MVC Core)

public async Task<IActionResult> Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Render View to PDF document
        PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
        Response.Headers.Add("Content-Disposition", "inline");

        // Output PDF document
        return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
    }
    return View(persons);
}
public async Task<IActionResult> Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (_httpContextAccessor.HttpContext.Request.Method == HttpMethod.Post.Method)
    {
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Render View to PDF document
        PdfDocument pdf = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons);
        Response.Headers.Add("Content-Disposition", "inline");

        // Output PDF document
        return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf");
    }
    return View(persons);
}
Public Async Function Persons() As Task(Of IActionResult)
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
	Dim persons_Conflict = New List(Of Person) From {
		New Person With {
			.Name = "Alice",
			.Title = "Mrs.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Bob",
			.Title = "Mr.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Charlie",
			.Title = "Mr.",
			.Description = "Software Engineer"
		}
	}
	If _httpContextAccessor.HttpContext.Request.Method = HttpMethod.Post.Method Then
		Dim renderer As New ChromePdfRenderer()

		' Render View to PDF document
		Dim pdf As PdfDocument = renderer.RenderRazorViewToPdf(_viewRenderService, "Views/Home/Persons.cshtml", persons_Conflict)
		Response.Headers.Add("Content-Disposition", "inline")

		' Output PDF document
		Return File(pdf.BinaryData, "application/pdf", "viewToPdfMVCCore.pdf")
	End If
	Return View(persons_Conflict)
End Function
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

CSHTML 轉換為 PDF (MVC Framework)

public ActionResult Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (HttpContext.Request.HttpMethod == "POST")
    {
        // Provide the path to your view file
        var viewPath = "~/Views/Home/Persons.cshtml";
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Render Razor view to PDF document
        PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
        Response.Headers.Add("Content-Disposition", "inline");

        // View the PDF
        return File(pdf.BinaryData, "application/pdf");
    }
    return View(persons);
}
public ActionResult Persons()
{
    var persons = new List<Person>
    {
    new Person { Name = "Alice", Title = "Mrs.", Description = "Software Engineer" },
    new Person { Name = "Bob", Title = "Mr.", Description = "Software Engineer" },
    new Person { Name = "Charlie", Title = "Mr.", Description = "Software Engineer" }
    };
    if (HttpContext.Request.HttpMethod == "POST")
    {
        // Provide the path to your view file
        var viewPath = "~/Views/Home/Persons.cshtml";
        ChromePdfRenderer renderer = new ChromePdfRenderer();

        // Render Razor view to PDF document
        PdfDocument pdf = renderer.RenderView(this.HttpContext, viewPath, persons);
        Response.Headers.Add("Content-Disposition", "inline");

        // View the PDF
        return File(pdf.BinaryData, "application/pdf");
    }
    return View(persons);
}
Public Function Persons() As ActionResult
'INSTANT VB NOTE: The local variable persons was renamed since Visual Basic will not allow local variables with the same name as their enclosing function or property:
	Dim persons_Conflict = New List(Of Person) From {
		New Person With {
			.Name = "Alice",
			.Title = "Mrs.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Bob",
			.Title = "Mr.",
			.Description = "Software Engineer"
		},
		New Person With {
			.Name = "Charlie",
			.Title = "Mr.",
			.Description = "Software Engineer"
		}
	}
	If HttpContext.Request.HttpMethod = "POST" Then
		' Provide the path to your view file
		Dim viewPath = "~/Views/Home/Persons.cshtml"
		Dim renderer As New ChromePdfRenderer()

		' Render Razor view to PDF document
		Dim pdf As PdfDocument = renderer.RenderView(Me.HttpContext, viewPath, persons_Conflict)
		Response.Headers.Add("Content-Disposition", "inline")

		' View the PDF
		Return File(pdf.BinaryData, "application/pdf")
	End If
	Return View(persons_Conflict)
End Function
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

CSHTML 轉換為 PDF (Headlessly)

app.MapGet("/PrintPdf", async () =>
{
    // Set your IronPDF license key
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Enable detailed logging for troubleshooting
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    // Render the Razor view to an HTML string
    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    // Create a new instance of ChromePdfRenderer 
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the HTML string as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    // Return the PDF file as a response
    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", async () =>
{
    // Set your IronPDF license key
    IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01";

    // Enable detailed logging for troubleshooting
    IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All;

    // Render the Razor view to an HTML string
    string html = await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml");

    // Create a new instance of ChromePdfRenderer 
    ChromePdfRenderer renderer = new ChromePdfRenderer();

    // Render the HTML string as a PDF document
    PdfDocument pdf = renderer.RenderHtmlAsPdf(html, "./wwwroot");

    // Return the PDF file as a response
    return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf");
});
app.MapGet("/PrintPdf", Async Function()
	' Set your IronPDF license key
	IronPdf.License.LicenseKey = "IRONPDF-MYLICENSE-KEY-1EF01"

	' Enable detailed logging for troubleshooting
	IronPdf.Logging.Logger.LoggingMode = IronPdf.Logging.Logger.LoggingModes.All

	' Render the Razor view to an HTML string
	Dim html As String = Await RazorTemplateEngine.RenderAsync("Views/Home/Data.cshtml")

	' Create a new instance of ChromePdfRenderer
	Dim renderer As New ChromePdfRenderer()

	' Render the HTML string as a PDF document
	Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, "./wwwroot")

	' Return the PDF file as a response
	Return Results.File(pdf.BinaryData, "application/pdf", "razorViewToPdf.pdf")
End Function)
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

網頁無障礙

TLS 網站與系統登入

IronPDF 提供了一種簡單的解決方案來轉換需要身份驗證的網頁。 使用其渲染選項,用戶可以通過 ChromeHttpLoginCredntials 屬性繞過使用者名稱和密碼。

:path=/static-assets/pdf/content-code-examples/how-to/logins-username-password.cs
using IronPdf;
using System;

ChromePdfRenderer renderer = new ChromePdfRenderer
{
    // setting login credentials to bypass basic authentication
    LoginCredentials = new ChromeHttpLoginCredentials()
    {
        NetworkUsername = "testUser",
        NetworkPassword = "testPassword"
    }
};

var uri = new Uri("http://localhost:51169/Invoice");

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf(uri);

// Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf");
Imports IronPdf
Imports System

Private renderer As New ChromePdfRenderer With {
	.LoginCredentials = New ChromeHttpLoginCredentials() With {
		.NetworkUsername = "testUser",
		.NetworkPassword = "testPassword"
	}
}

Private uri = New Uri("http://localhost:51169/Invoice")

' Render web URL to PDF
Private pdf As PdfDocument = renderer.RenderUrlAsPdf(uri)

' Export PDF
pdf.SaveAs("UrlToPdfExample.Pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

Cookies

將 cookies 應用於額外的登錄請求以確保您的會話被保存! 這將使得在鎖定域內渲染其他資源變得更加容易,所有這些都通過 IronPDF 完成。

:path=/static-assets/pdf/content-code-examples/how-to/cookies-apply-cookies.cs
using IronPdf;

// Instantiate ChromePdfRenderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global;

ChromeHttpLoginCredentials credentials = new ChromeHttpLoginCredentials() {
    NetworkUsername = "testUser",
    NetworkPassword = "testPassword"
};

string uri = "http://localhost:51169/Invoice";

// Apply cookies
renderer.ApplyCookies(uri, credentials);
Imports IronPdf

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

renderer.RenderingOptions.RequestContext = IronPdf.Rendering.RequestContexts.Global

Dim credentials As New ChromeHttpLoginCredentials() With {
	.NetworkUsername = "testUser",
	.NetworkPassword = "testPassword"
}

Dim uri As String = "http://localhost:51169/Invoice"

' Apply cookies
renderer.ApplyCookies(uri, credentials)
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

HTTP 請求頭

除了 cookies,IronPDF 還允許用戶自定義他們的 HTTP 請求頭,帶有授權令牌和其他常見相關字段。

:path=/static-assets/pdf/content-code-examples/how-to/http-request-header.cs
using IronPdf;
using System.Collections.Generic;

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HttpRequestHeaders = new Dictionary<string, string>
{
    { "Authorization", "Bearer test-token-123" }
};

// Render PDF from authenticated page
var pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer");
pdf.SaveAs("output.pdf");
Imports IronPdf
Imports System.Collections.Generic

Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.HttpRequestHeaders = New Dictionary(Of String, String) From {
	{"Authorization", "Bearer test-token-123"}
}

' Render PDF from authenticated page
Dim pdf = renderer.RenderUrlAsPdf("https://httpbin.org/bearer")
pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

定制化 PDF 轉換

渲染選項

IronPDF 允許用戶自定義其生成的 PDF 的外觀和格式。 ChromePdfRender 類用於將各種輸入轉換為 PDFs,還包含 RenderingOptions 屬性,讓用戶控制輸出看起來如何。

:path=/static-assets/pdf/content-code-examples/how-to/rendering-options-render.cs
using IronPdf;

// Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
// to render HTML/CSS as a PDF document.
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Configure rendering options
// Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = true;

// Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
    // HTML fragment to add a header at the top of every page in the PDF.
    HtmlFragment = "<h1>Header Content</h1>"
};

// Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150);

// Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0;

// Define a Markdown string that will be rendered as a PDF.
// Markdown text allows basic formatting like bold and italic styles.
string md = "This is some **bold** and *italic* text.";

// Render the Markdown string to a PDF document.
// The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
PdfDocument pdf = renderer.RenderMarkdownStringAsPdf(md);

// Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf");
Imports IronPdf

' Instantiate a ChromePdfRenderer object, which uses a headless version of the Chrome browser
' to render HTML/CSS as a PDF document.
Private renderer As New ChromePdfRenderer()

' Configure rendering options
' Enable printing of HTML backgrounds to ensure all styles are visible.
renderer.RenderingOptions.PrintHtmlBackgrounds = True

' Set HTML header content using HtmlHeaderFooter.
renderer.RenderingOptions.HtmlHeader = New HtmlHeaderFooter With {.HtmlFragment = "<h1>Header Content</h1>"}

' Set a custom paper size for the PDF in millimeters (width and height).
renderer.RenderingOptions.SetCustomPaperSizeinMilimeters(150, 150)

' Set the top margin to zero to start the content from the very top of the page.
renderer.RenderingOptions.MarginTop = 0

' Define a Markdown string that will be rendered as a PDF.
' Markdown text allows basic formatting like bold and italic styles.
Dim md As String = "This is some **bold** and *italic* text."

' Render the Markdown string to a PDF document.
' The library will convert Markdown syntax into equivalent HTML before rendering it as a PDF.
Dim pdf As PdfDocument = renderer.RenderMarkdownStringAsPdf(md)

' Save the generated PDF to a file named "renderingOptions.pdf."
pdf.SaveAs("renderingOptions.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

設置自定義邊距

您可以進一步調整輸出 PDF 的外觀,通過調整邊距,讓您能夠精確控制佈局和間距。

:path=/static-assets/pdf/content-code-examples/how-to/custom-margins-set-margins.cs
ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.MarginTop = 40;
renderer.RenderingOptions.MarginLeft = 20;
renderer.RenderingOptions.MarginRight = 20;
renderer.RenderingOptions.MarginBottom = 40;
Dim renderer As New ChromePdfRenderer()

renderer.RenderingOptions.MarginTop = 40
renderer.RenderingOptions.MarginLeft = 20
renderer.RenderingOptions.MarginRight = 20
renderer.RenderingOptions.MarginBottom = 40
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

灰階

要生成灰階 PDF,我們需要將 RenderingOptions 中的 GrayScale 屬性設為 true。

:path=/static-assets/pdf/content-code-examples/how-to/color-grayscale-grayscale.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set GrayScale to true
renderer.RenderingOptions.GrayScale = true;

PdfDocument pdf = renderer.RenderUrlAsPdf("https://ironsoftware.com/");
pdf.CopyPage(0).SaveAs("test.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

精細化 PDF 佈局

添加目錄

使用 IronPDF 創建動態目錄,以幫助讀者輕鬆瀏覽您的文檔。 IronPDF 自動處理目錄,並為如 h1h2 的標題設置超連結。 此外,您還可以使用 HTML 和 CSS 樣式自定義目錄的樣式。

:path=/static-assets/pdf/content-code-examples/how-to/table-of-contents.cs
using IronPdf;

// Instantiate Renderer
ChromePdfRenderer renderer = new ChromePdfRenderer();

// Configure render options
renderer.RenderingOptions = new ChromePdfRenderOptions
{
    // Enable table of content feature
    TableOfContents = TableOfContentsTypes.WithPageNumbers,
};

PdfDocument pdf = renderer.RenderHtmlFileAsPdf("tableOfContent.html");

pdf.SaveAs("tableOfContents.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New ChromePdfRenderer()

' Configure render options
renderer.RenderingOptions = New ChromePdfRenderOptions With {.TableOfContents = TableOfContentsTypes.WithPageNumbers}

Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("tableOfContent.html")

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

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

分頁符

在不同的部分之間添加分頁符,以清晰地分隔內容並提高文檔的可讀性。 使用 IronPDF,只需使用 HTML div style= page-break-after 即可實現該效果。

:path=/static-assets/pdf/content-code-examples/how-to/html-to-pdf-page-breaks-page-break.cs
using IronPdf;

const string html = @"
  <table style='border: 1px solid #000000'>
    <tr>
      <th>Company</th>
      <th>Product</th>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronPDF</td>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronOCR</td>
    </tr>
  </table>

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

  <img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>";

var renderer = new ChromePdfRenderer();

var pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("Page_Break.pdf");
Imports IronPdf

Private Const html As String = "
  <table style='border: 1px solid #000000'>
    <tr>
      <th>Company</th>
      <th>Product</th>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronPDF</td>
    </tr>
    <tr>
      <td>Iron Software</td>
      <td>IronOCR</td>
    </tr>
  </table>

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

  <img src='https://ironpdf.com/img/products/ironpdf-logo-text-dotnet.svg'>"

Private renderer = New ChromePdfRenderer()

Private pdf = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("Page_Break.pdf")
$vbLabelText   $csharpLabel

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

適合紙張大小 & 縮放

需要幫助確定內容的尺寸以適應指定的紙張大小嗎?IronPDF 提供了 UseChromeDefault,模仿了 Google Chrome 的打印預覽是如何縮放內容以適應頁面的。

:path=/static-assets/pdf/content-code-examples/how-to/viewport-zoom-default-chrome.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering();

// Render web URL to PDF
PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

pdf.SaveAs("chromeDefault.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

' Chrome default rendering
renderer.RenderingOptions.PaperFit.UseChromeDefaultRendering()

' Render web URL to PDF
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

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

欲獲得此代碼片段的詳細說明並探索其附加功能,請參考我們的綜合 指南

結論

上述示例展示了您使用 IronPDF 將各種格式轉換為 PDFs 時可以解鎖的令人印象深刻的能力和特色。

如果您想提出功能請求或對 IronPDF 或許可有一般性問題,請 聯繫我們的支持團隊。 我們將很樂意幫助您。

常見問題解答

如何在.NET Core中將HTML轉換為PDF?

若要在 .NET Core 中將 HTML 轉換為 PDF,請使用 IronPDF 庫。首先,透過 NuGet 安裝該程式庫。然後,建立ChromePdfRenderer實例,並使用RenderHtmlAsPdf方法將 HTML 字串轉換為 PDF 格式。

如何將即時網址轉換為PDF文件?

您可以使用 IronPDF 將即時 URL 轉換為 PDF 文檔,方法是從 NuGet 安裝庫,建立ChromePdfRenderer實例,然後使用要轉換的網頁 URL 呼叫RenderUrlAsPdf方法。

將 Razor 視圖轉換為 PDF 的步驟是什麼?

若要將 Razor 視圖轉換為 PDF,請將視圖渲染為 HTML 字串,然後將其傳遞給 IronPDF 的RenderHtmlAsPdf方法。這樣就可以使用完整的資料綁定,從 MVC 視圖建立動態 PDF。

能否修改現有的PDF文件?

是的,可以使用 IronPDF 修改現有的 PDF 檔案。使用PdfDocument.FromFile載入 PDF 文件,然後進行合併、新增頁首/頁尾或變更安全性設定等修改。

渲染 PDF 檔案有哪些選項?

IronPDF 透過ChromePdfRenderOptions提供多種渲染選項。您可以自訂紙張大小、方向、邊距等,確保您的 PDF 符合特定的版面和樣式要求。

如何在 Docker 環境中部署 PDF 檔案?

透過在 Dockerfile 中配置 Linux 依賴項,即可在 Docker 環境中部署 PDF 檔案。使用 IronPDF 的IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig可以自動處理容器化應用程式中的依賴項。

是否可以在PDF文件中加入數位簽名?

是的,可以使用PdfSignature類別為 PDF 檔案添加數位簽章。透過使用Sign方法和憑證文件,您可以確保文件的真實性和完整性。

IronPDF 為 PDF 檔案提供哪些安全功能?

IronPDF 提供強大的安全功能,包括密碼保護、加密和存取控制。您可以透過SecuritySettings屬性設定這些功能,以管理檢視、列印和編輯權限。

如何從PDF文件中提取文字和圖像?

IronPDF 的ExtractAllTextExtractAllImages方法可用於從 PDF 文件中擷取文字和影像。這些方法允許處理整個文件或特定頁面的資料。

如何為PDF文件添加浮水印?

可以使用 IronPDF 的Watermark屬性和HtmlStamp物件為 PDF 檔案新增浮水印。對於更進階的需求, HtmlStamper類別支援基於 HTML 的圖章,並可自訂樣式。

IronPDF 與 .NET 10 相容嗎?如何在 .NET 10 專案中使用它?

是的——IronPDF 完全支援 .NET 10,這是其跨平台、現代 .NET 版本支援的一部分。要在 .NET 10 專案中使用它,請安裝IronPdf NuGet 包,在專案文件中將其引用為net10.0 ,然後即可像在早期 .NET 版本中一樣使用ChromePdfRenderer等類別和RenderHtmlAsPdf等方法。在渲染或處理 PDF 時,您可以受益於 .NET 10 固有的效能提升、記憶體使用最佳化和執行時間改進。

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 18

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 18
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 38

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 38
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 48

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 48
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

審核人

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'name'

Filename: sections/author_component.php

Line Number: 70

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 70
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'title'

Filename: sections/author_component.php

Line Number: 84

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 84
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Warning

Message: Illegal string offset 'comment'

Filename: sections/author_component.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/views/main/sections/author_component.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 63
Function: view

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 64
Function: main_view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

準備好開始了嗎?
Nuget 下載 16,133,208 | 版本: 2025.11 剛剛發布