Jak generować pliki PDF w .NET Core

Convert HTML to PDF in .NET Core using C# with IronPDF

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

Generowanie wysokiej jakości PDFów bezpośrednio z HTML to często wymagana funkcja w nowoczesnych aplikacjach .NET – raporty, faktury i bilety wymagają doskonałej jakości wyjściowej, która odpowiada interfejsowi użytkownika. IronPDF usprawnia ten proces, udostępniając jedno API C# do renderowania HTML, widoków Razor oraz całych stron internetowych do dokumentów PDF zgodnych z normami. Po zakończeniu tego przewodnika, programista będzie w stanie konwertować URL, surowy HTML lub widoki MVC w projekcie ASP.NET Core i wdrożyć ten sam kod na Windows, Linux, Docker lub w środowiskach bezserwerowych.

PoradyW przypadku problemów układu, IronPDF dostarcza debugger typu headless-Chrome, który pomaga zdiagnozować błędy CSS, JavaScript i zapytań medialnych przed wygenerowaniem PDF. Przejrzyj dedykowany przewodnik HTML-do-PDF dla szczegółowych technik.

Szybki start: Tworzenie PDF z HTML w .NET Core

Bez trudu zamień HTML na PDF w .NET Core przy użyciu biblioteki IronPDF. Ten przewodnik dostarcza prosty przykład, aby szybko zacząć, renderując zawartość HTML do wysokiej jakości PDF przy minimalnym kodzie. Idealny dla programistów, którzy chcą łatwo zintegrować tworzenie PDFów z ich aplikacjami.

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf
  2. Skopiuj i uruchom ten fragment kodu.

    var pdf = new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello World</h1>");
  3. Wdrożenie do testowania w środowisku produkcyjnym

    Rozpocznij używanie IronPDF w swoim projekcie już dziś z darmową wersją próbną

    arrow pointer

Lista kontrolna szybkiego startu

  1. ZainstalujInstall-Package IronPdf
  2. Renderuj URLChromePdfRenderer.RenderUrlAsPdf()
  3. Renderuj surowy HTMLChromePdfRenderer.RenderHtmlAsPdf()
  4. Eksportuj widok RazorChromePdfRenderer.RenderHtmlAsPdfAsync()
  5. Dostosuj wyjście – użyj ChromePdfRenderer.RenderingOptions

Co obejmuje ten tutorial

  • Konwersja URL, ciągu HTML oraz widoku Razor
  • Konfiguracja papieru, marginesów i typu mediów
  • Wdrożenie międzyplatformowe (Windows, Linux, Docker)
  • Postprocessing: scalanie, znak wodny, ochrona hasłem i cyfrowe podpisywanie PDFów
  • Przykład end-to-end: aplikacja MVC rezerwacji biletów

Jak zainstalować bibliotekę PDF w .NET Core?

Instalacja biblioteki w projekcie .NET 8 wymaga jednej linijki kodu i jest kompatybilna z wersją .NET 9 preview oraz nadchodzącym wydaniem .NET 10. Użyj Konsoli Menedżera Pakietów NuGet, a menedżer pakietów sam rozwiąże wszystkie zależności dla Windows, Linux, Docker i środowisk bezserwerowych.

PM> Install-Package IronPdf             # .NET 8 LTS and higher
PM> Install-Package IronPdf             # .NET 8 LTS and higher
SHELL

Zwróć uwagęPotrzebujesz CLI? Ten sam kod działa z dotnet add package IronPdf w folderze projektu.

Po zainstalowaniu, potwierdź działanie, konwertując dowolny publiczny URL:

// Program.cs — .NET 8 LTS
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render a live website to PDF
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://example.com");

// Persist to disk
pdf.SaveAs("website-snapshot.pdf");
// Program.cs — .NET 8 LTS
using IronPdf;

var renderer = new ChromePdfRenderer();

// Render a live website to PDF
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://example.com");

// Persist to disk
pdf.SaveAs("website-snapshot.pdf");
' Program.cs — .NET 8 LTS
Imports IronPdf

Private renderer = New ChromePdfRenderer()

' Render a live website to PDF
Private PdfDocument As using

' Persist to disk
pdf.SaveAs("website-snapshot.pdf")
$vbLabelText   $csharpLabel

Jak to działa

  • ChromePdfRenderer uruchamia w tle instancję Chromium w trybie piaskownicy — nie jest wymagane oddzielne instalowanie Chrome.
  • RenderUrlAsPdf przechwytuje w pełni wyrenderowany DOM, łącznie z treściami napędzanymi przez JavaScript, zapytaniami CSS i czcionkami.
  • Powstały PdfDocument udostępnia metody pomocnicze do scalania, ochrony hasłem czy cyfrowego podpisu — zdolności omówione później w tym tutorialu.

Po więcej szczegółów na temat niuansów wdrożeniowych (Azure App Service, AWS Lambda, on-prem Linux) zobacz dedykowany przewodnik instalacji oraz strony zaawansowanej konfiguracji NuGet. Wewnętrzne wskazówki CI/CD dla Docker i klastrów K8s omówiono w najlepszych praktykach wdrażania Docker.


Jak usługa .NET Core może przekształcić adres URL strony internetowej na PDF?

Jedno wywołanie RenderUrlAsPdf wystarcza: przekaż dowolny publicznie dostępny URL, a IronPDF zwróci w pełni wyrenderowany, zgodny z normami PDF. Kod poniżej jest skierowany na .NET 8 LTS i kompiluje się bez zmian w .NET 9 preview oraz nadchodzącym wydaniu .NET 10 w 2025 roku.

Krok po kroku przykład

// Program.cs — .NET 8 LTS-compatible
using IronPdf;

// 1. Activate a license (or trial key)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

// 2. Create a reusable renderer instance
var renderer = new ChromePdfRenderer
{
    RenderingOptions =
    {
        // Force A4 portrait output and apply @media print styles
        PaperSize    = PdfPaperSize.A4,
        CssMediaType = PdfCssMediaType.Print
    }
};

// 3. Convert Microsoft Docs home page to PDF
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://learn.microsoft.com/");

// 4. Save the PDF or stream it from a Web API
pdf.SaveAs("docs-offline-copy.pdf");
// Program.cs — .NET 8 LTS-compatible
using IronPdf;

// 1. Activate a license (or trial key)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";

// 2. Create a reusable renderer instance
var renderer = new ChromePdfRenderer
{
    RenderingOptions =
    {
        // Force A4 portrait output and apply @media print styles
        PaperSize    = PdfPaperSize.A4,
        CssMediaType = PdfCssMediaType.Print
    }
};

// 3. Convert Microsoft Docs home page to PDF
using PdfDocument pdf = renderer.RenderUrlAsPdf("https://learn.microsoft.com/");

// 4. Save the PDF or stream it from a Web API
pdf.SaveAs("docs-offline-copy.pdf");
' Program.cs — .NET 8 LTS-compatible
Imports IronPdf

' 1. Activate a license (or trial key)
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"

' 2. Create a reusable renderer instance
Dim renderer = New ChromePdfRenderer With {
	.RenderingOptions = {
		PaperSize = PdfPaperSize.A4,
		CssMediaType = PdfCssMediaType.Print
	}
}

' 3. Convert Microsoft Docs home page to PDF
Using pdf As PdfDocument = renderer.RenderUrlAsPdf("https://learn.microsoft.com/")
	
	' 4. Save the PDF or stream it from a Web API
	pdf.SaveAs("docs-offline-copy.pdf")
End Using
$vbLabelText   $csharpLabel

Dlaczego to działa

  • ChromePdfRenderer uruchamia w tle instancję Chromium w trybie piaskownicy — nie wymaga zależności od systemowego Chrome, utrzymując obrazy Docker smukłe.
  • RenderUrlAsPdf czeka na zakończenie DOM i JavaScript przed wykonaniem zrzutu, dzięki czemu jednorazowe aplikacje renderują się poprawnie.
  • Ustawienie CssMediaType na Print mówi silnikowi, aby używał zasad specyficznych dla wydruku, zgodnych z wyjściem Print → Save as PDF przeglądarki.
  • Powstały PdfDocument można zaszyfrować, cyfrowo podpisać, złączyć lub rastrować — zdolności omówione w późniejszych sekcjach.

PoradyDebugowanie pixel-perfect: włącz renderer.LoggingOptions.DebugMode = true i postępuj zgodnie z przewodnikiem debugowania headless-Chrome, aby sprawdzić w czasie rzeczywistym narzędzia deweloperskie podczas renderowania.

Powiązane zasoby


Jak przekształcić surowy HTML na PDF w .NET Core?

Przekierowanie ciągu HTML — lub wyrenderowanego znaczników widoku Razor — do ChromePdfRenderer.RenderHtmlAsPdf natychmiast generuje zgodny z normami PDF. Metoda uruchamia wbudowany silnik Chromium IronPDF, więc nie jest wymagana instalacja zewnętrznej przeglądarki ani zależności WebView. Ten sam kod, który poniżej pokazano, kompiluje się w .NET 8 LTS dzisiaj i pozostaje kompatybilny z wersją .NET 9 i zaplanowanym wydaniem .NET 10 w listopadzie 2025 roku.

Przykład — generowanie PDF z fragmentu HTML

// Program.cs — compatible with .NET 8 and newer
using IronPdf;

// Sample HTML fragment (could also be read from a file, Razor view, or CMS)
const string html = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quarterly Report</title>
  <style>
     body { font-family:'Segoe UI', sans-serif; margin:1.2rem; }
     header { margin-bottom:2rem; }
     h1 { color:#3056d3; }
     table { width:100%; border-collapse:collapse; margin-top:1rem; }
     th,td { border:1px solid #ddd; padding:0.5rem; text-align:right; }
     tr:nth-child(even){ background-color:#f8f9fa; }
  </style>
</head>
<body>
  <header><h1>Q2 Revenue Summary</h1></header>
  <table>
    <thead><tr><th>Product</th><th>Revenue ($)</th></tr></thead>
    <tbody>
      <tr><td>IronPDF for .NET</td><td>1,200,000</td></tr>
      <tr><td>IronOCR for .NET</td><td>890,000</td></tr>
      <tr><td>IronXL for .NET</td><td>610,000</td></tr>
    </tbody>
  </table>
</body>
</html>
""";

// 1. Create a renderer once and reuse it across conversions
var renderer = new ChromePdfRenderer
{
    RenderingOptions =
    {
        PaperSize    = PdfPaperSize.A4,                  // ISO-standard paper size
        PaperOrientation = PdfPaperOrientation.Portrait,
        CssMediaType = PdfCssMediaType.Screen,           // Respect on-screen CSS
        RenderDelay  = 100,                              // Wait 100 ms for JS/animations
        FallbackEncoding = "utf-8"                       // Handle non-ASCII correctly
    }
};

// 2. Render the HTML fragment
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// 3. Persist to disk or return via ASP.NET Core FileStreamResult
pdf.SaveAs("q2-report.pdf");
// Program.cs — compatible with .NET 8 and newer
using IronPdf;

// Sample HTML fragment (could also be read from a file, Razor view, or CMS)
const string html = """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Quarterly Report</title>
  <style>
     body { font-family:'Segoe UI', sans-serif; margin:1.2rem; }
     header { margin-bottom:2rem; }
     h1 { color:#3056d3; }
     table { width:100%; border-collapse:collapse; margin-top:1rem; }
     th,td { border:1px solid #ddd; padding:0.5rem; text-align:right; }
     tr:nth-child(even){ background-color:#f8f9fa; }
  </style>
</head>
<body>
  <header><h1>Q2 Revenue Summary</h1></header>
  <table>
    <thead><tr><th>Product</th><th>Revenue ($)</th></tr></thead>
    <tbody>
      <tr><td>IronPDF for .NET</td><td>1,200,000</td></tr>
      <tr><td>IronOCR for .NET</td><td>890,000</td></tr>
      <tr><td>IronXL for .NET</td><td>610,000</td></tr>
    </tbody>
  </table>
</body>
</html>
""";

// 1. Create a renderer once and reuse it across conversions
var renderer = new ChromePdfRenderer
{
    RenderingOptions =
    {
        PaperSize    = PdfPaperSize.A4,                  // ISO-standard paper size
        PaperOrientation = PdfPaperOrientation.Portrait,
        CssMediaType = PdfCssMediaType.Screen,           // Respect on-screen CSS
        RenderDelay  = 100,                              // Wait 100 ms for JS/animations
        FallbackEncoding = "utf-8"                       // Handle non-ASCII correctly
    }
};

// 2. Render the HTML fragment
using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);

// 3. Persist to disk or return via ASP.NET Core FileStreamResult
pdf.SaveAs("q2-report.pdf");
' Program.cs — compatible with .NET 8 and newer
Imports IronPdf

' Sample HTML fragment (could also be read from a file, Razor view, or CMS)
Private Const html As String = "<!DOCTYPE html>
<html lang=""en"">
<head>
  <meta charset=""utf-8"">
  <title>Quarterly Report</title>
  <style>
     body { font-family:'Segoe UI', sans-serif; margin:1.2rem; }
     header { margin-bottom:2rem; }
     h1 { color:#3056d3; }
     table { width:100%; border-collapse:collapse; margin-top:1rem; }
     th,td { border:1px solid #ddd; padding:0.5rem; text-align:right; }
     tr:nth-child(even){ background-color:#f8f9fa; }
  </style>
</head>
<body>
  <header><h1>Q2 Revenue Summary</h1></header>
  <table>
    <thead><tr><th>Product</th><th>Revenue ($)</th></tr></thead>
    <tbody>
      <tr><td>IronPDF for .NET</td><td>1,200,000</td></tr>
      <tr><td>IronOCR for .NET</td><td>890,000</td></tr>
      <tr><td>IronXL for .NET</td><td>610,000</td></tr>
    </tbody>
  </table>
</body>
</html>"

' 1. Create a renderer once and reuse it across conversions
Private renderer = New ChromePdfRenderer With {
	.RenderingOptions = {
		PaperSize = PdfPaperSize.A4,
		PaperOrientation = PdfPaperOrientation.Portrait,
		CssMediaType = PdfCssMediaType.Screen,
		RenderDelay = 100,
		FallbackEncoding = "utf-8"
	}
}

' 2. Render the HTML fragment
Private PdfDocument As using

' 3. Persist to disk or return via ASP.NET Core FileStreamResult
pdf.SaveAs("q2-report.pdf")
$vbLabelText   $csharpLabel

Co demonstracje kod

  • Wbudowany Chromium -- IronPDF dołącza silnik Chromium, zapewniając parytet HTML5, CSS3 i JavaScript z nowoczesnymi przeglądarkami.
  • Pojedyncza zależność -- lekka instalacja NuGet obejmuje Windows, Linux, Docker i Azure/AWS bez dodatkowych bibliotek systemowych.
  • Opcje renderowania -- PaperSize, CssMediaType i RenderDelay odzwierciedlają ustawienia wydruku przeglądarki, dzięki czemu PDFy odpowiadają układom ekranowym.
  • Przyszłościowe wsparcie -- Powierzchnia API jest taka sama w .NET 8, .NET 9 STS i nadchodzącym .NET 10, więc utrzymanie długoterminowe jest minimalne.
  • Haki post-processing -- PdfDocument odkrywa pomocne metody do scalania, ochrony hasłem i cyfrowe podpisy — każde omówione później w tym przewodniku.

Dalsza lektura: zobacz przewodnik krok po kroku HTML-do-PDF tutorial i pełną ChromePdfRenderer dokumentację API.


Jak można eksportować widok ASP .NET Core MVC do PDF?

IronPDF renderuje w pełni przetworzony widok Razor ( .cshtml ) w ten sam sposób, jak przeglądarka, i struje wynik jako PdfDocument. Przepływ pracy poniżej utrzymuje czystość logiki kontrolera, nie wymaga wtyczek przeglądarki i działa w .NET 8 LTS, .NET 9 preview i zaplanowanym wydaniu .NET 10 w listopadzie 2025 roku.

Przykład kontrolera end-to-end

// TicketsController.cs — .NET 8 LTS / MVC
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using YourApp.Models;           // TicketViewModel

public class TicketsController : Controller
{
    private readonly ChromePdfRenderer _renderer;

    public TicketsController()
    {
        _renderer = new ChromePdfRenderer
        {
            RenderingOptions =
            {
                PaperSize        = PdfPaperSize.A5,            // Compact ticket size
                PaperOrientation = PdfPdfOrientation.Portrait,
                FitToPaperWidth  = true,
                CssMediaType     = PdfCssMediaType.Print,
                Margins = new PdfMargins(5, 10, 5, 10)         // mm
            }
        };
    }

    // GET /Tickets/Print/42
    public async Task<IActionResult> Print(int id)
    {
        TicketViewModel vm = await _service.GetTicketAsync(id);

        // 1. Render the Razor view to an HTML string
        string html  = await RazorTemplateEngine.RenderViewAsync(
                           HttpContext, "~/Views/Tickets/Print.cshtml", vm);

        // 2. Convert HTML → PDF
        using PdfDocument pdf = _renderer.RenderHtmlAsPdf(html);

        // 3. Stream back as a file
        return File(pdf.BinaryData, "application/pdf",
                    $"ticket-{id}.pdf");
    }
}
// TicketsController.cs — .NET 8 LTS / MVC
using IronPdf;
using Microsoft.AspNetCore.Mvc;
using YourApp.Models;           // TicketViewModel

public class TicketsController : Controller
{
    private readonly ChromePdfRenderer _renderer;

    public TicketsController()
    {
        _renderer = new ChromePdfRenderer
        {
            RenderingOptions =
            {
                PaperSize        = PdfPaperSize.A5,            // Compact ticket size
                PaperOrientation = PdfPdfOrientation.Portrait,
                FitToPaperWidth  = true,
                CssMediaType     = PdfCssMediaType.Print,
                Margins = new PdfMargins(5, 10, 5, 10)         // mm
            }
        };
    }

    // GET /Tickets/Print/42
    public async Task<IActionResult> Print(int id)
    {
        TicketViewModel vm = await _service.GetTicketAsync(id);

        // 1. Render the Razor view to an HTML string
        string html  = await RazorTemplateEngine.RenderViewAsync(
                           HttpContext, "~/Views/Tickets/Print.cshtml", vm);

        // 2. Convert HTML → PDF
        using PdfDocument pdf = _renderer.RenderHtmlAsPdf(html);

        // 3. Stream back as a file
        return File(pdf.BinaryData, "application/pdf",
                    $"ticket-{id}.pdf");
    }
}
Imports IronPdf
Imports Microsoft.AspNetCore.Mvc
Imports YourApp.Models ' TicketViewModel

Public Class TicketsController
    Inherits Controller

    Private ReadOnly _renderer As ChromePdfRenderer

    Public Sub New()
        _renderer = New ChromePdfRenderer With {
            .RenderingOptions = New PdfRenderingOptions With {
                .PaperSize = PdfPaperSize.A5, ' Compact ticket size
                .PaperOrientation = PdfPdfOrientation.Portrait,
                .FitToPaperWidth = True,
                .CssMediaType = PdfCssMediaType.Print,
                .Margins = New PdfMargins(5, 10, 5, 10) ' mm
            }
        }
    End Sub

    ' GET /Tickets/Print/42
    Public Async Function Print(id As Integer) As Task(Of IActionResult)
        Dim vm As TicketViewModel = Await _service.GetTicketAsync(id)

        ' 1. Render the Razor view to an HTML string
        Dim html As String = Await RazorTemplateEngine.RenderViewAsync(
            HttpContext, "~/Views/Tickets/Print.cshtml", vm)

        ' 2. Convert HTML → PDF
        Using pdf As PdfDocument = _renderer.RenderHtmlAsPdf(html)
            ' 3. Stream back as a file
            Return File(pdf.BinaryData, "application/pdf", $"ticket-{id}.pdf")
        End Using
    End Function
End Class
$vbLabelText   $csharpLabel

Co ilustruje ten kod

  • Brak tymczasowych plików -- widok Razor jest renderowany w pamięci, a następnie przekazywany bezpośrednio do RenderHtmlAsPdf, unikając I/O dysku i warunków wyścigowych w folderze tymczasowym.
  • Wydruk wielkości biletu -- PaperSize = A5 i wąskie marginesy utrzymują wydruki biletów do druku w domu kompaktowe.
  • Spójne style wydruku -- CssMediaType = Print stosuje te same zasady CSS, które przeglądarki używają w @media print.
  • Binary streaming -- pdf.BinaryData strumieniuje dokument bez dotykania systemu plików; idealne dla punktów końcowych API i funkcji Lambda.
  • Reużywalny renderer -- ChromePdfRenderer jest tworzony raz na kontroler, a następnie używany wielokrotnie, minimalizując koszty obsługi procesów.

PaperSize, PaperOrientation, FitToPaperWidth

Margins, Header, Footer, Watermark

Kolejny krok: dodaj szyfrowanie, podpisy cyfrowe, lub złącz wiele biletów w jeden plik. Zobacz przykład łączenia i przewodnik podpisu cyfrowego.


Jak mogę dostosować rozmiar papieru, marginesy, nagłówki, znaki wodne i zabezpieczenia przed renderowaniem?

IronPDF udostępnia jeden obiekt ChromePdfRenderOptions, który kontroluje każdy aspekt wyjścia — wymiary papieru, orientację, nagłówki i stopki, czasowanie JavaScript, znaki wodne, szyfrowanie i podpisy cyfrowe — wszystko bez dodatkowych wtyczek przeglądarki.

Próbka kodu — zastosowanie wielu opcji naraz

// AdvancedOptions.cs — .NET 8 compatible
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure everything in one place
renderer.RenderingOptions = new ChromePdfRenderOptions
{
    // 1. Page layout
    PaperSize        = PdfPaperSize.A4,                     // ISO size
    PaperOrientation = PdfPdfOrientation.Portrait,
    Margins          = new PdfMargins { Top = 20, Bottom = 25, Left = 15, Right = 15 }, // mm

    // 2. Timing & media
    CssMediaType     = PdfCssMediaType.Print,               // Respect @media print
    EnableJavaScript = true,
    RenderDelay      = 200,                                 // Wait 200 ms for animations

    // 3. Headers & footers (HTML gives full design freedom)
    HtmlHeader       = "<header style='font:14px Segoe UI'>Invoice — {{date}}</header>",
    HtmlFooter       = "<footer style='text-align:right;font-size:10px'>Page {{page}} / {{total-pages}}</footer>",

    // 4. Watermark
    Watermark        = new HtmlStamp
    {
        HtmlTemplate = "<div style='font-size:50px;color:#cccccc;opacity:0.3;'>CONFIDENTIAL</div>",
        VerticalAlignment = VerticalAlignment.Center,
        HorizontalAlignment = HorizontalAlignment.Center
    },

    // 5. Security
    SecurityOptions = new PdfSecurityOptions
    {
        OwnerPassword = "StrongOwnerPwd!",
        UserPassword  = "ReadOnly",
        AllowUserPrinting = false,
        AllowUserCopyPasteContent = false
    }
};

// Render any HTML
using PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Advanced Options Demo</h1>");

// Digitally sign with a PFX certificate (optional)
pdf.SignAndStamp("./certs/company.pfx", "Iron Software", "Bangkok", "Approval");

// Save
pdf.SaveAs("advanced-options-demo.pdf");
// AdvancedOptions.cs — .NET 8 compatible
using IronPdf;

var renderer = new ChromePdfRenderer();

// Configure everything in one place
renderer.RenderingOptions = new ChromePdfRenderOptions
{
    // 1. Page layout
    PaperSize        = PdfPaperSize.A4,                     // ISO size
    PaperOrientation = PdfPdfOrientation.Portrait,
    Margins          = new PdfMargins { Top = 20, Bottom = 25, Left = 15, Right = 15 }, // mm

    // 2. Timing & media
    CssMediaType     = PdfCssMediaType.Print,               // Respect @media print
    EnableJavaScript = true,
    RenderDelay      = 200,                                 // Wait 200 ms for animations

    // 3. Headers & footers (HTML gives full design freedom)
    HtmlHeader       = "<header style='font:14px Segoe UI'>Invoice — {{date}}</header>",
    HtmlFooter       = "<footer style='text-align:right;font-size:10px'>Page {{page}} / {{total-pages}}</footer>",

    // 4. Watermark
    Watermark        = new HtmlStamp
    {
        HtmlTemplate = "<div style='font-size:50px;color:#cccccc;opacity:0.3;'>CONFIDENTIAL</div>",
        VerticalAlignment = VerticalAlignment.Center,
        HorizontalAlignment = HorizontalAlignment.Center
    },

    // 5. Security
    SecurityOptions = new PdfSecurityOptions
    {
        OwnerPassword = "StrongOwnerPwd!",
        UserPassword  = "ReadOnly",
        AllowUserPrinting = false,
        AllowUserCopyPasteContent = false
    }
};

// Render any HTML
using PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Advanced Options Demo</h1>");

// Digitally sign with a PFX certificate (optional)
pdf.SignAndStamp("./certs/company.pfx", "Iron Software", "Bangkok", "Approval");

// Save
pdf.SaveAs("advanced-options-demo.pdf");
Imports IronPdf

Dim renderer As New ChromePdfRenderer()

' Configure everything in one place
renderer.RenderingOptions = New ChromePdfRenderOptions With {
    ' 1. Page layout
    .PaperSize = PdfPaperSize.A4, ' ISO size
    .PaperOrientation = PdfPdfOrientation.Portrait,
    .Margins = New PdfMargins With {.Top = 20, .Bottom = 25, .Left = 15, .Right = 15}, ' mm

    ' 2. Timing & media
    .CssMediaType = PdfCssMediaType.Print, ' Respect @media print
    .EnableJavaScript = True,
    .RenderDelay = 200, ' Wait 200 ms for animations

    ' 3. Headers & footers (HTML gives full design freedom)
    .HtmlHeader = "<header style='font:14px Segoe UI'>Invoice — {{date}}</header>",
    .HtmlFooter = "<footer style='text-align:right;font-size:10px'>Page {{page}} / {{total-pages}}</footer>",

    ' 4. Watermark
    .Watermark = New HtmlStamp With {
        .HtmlTemplate = "<div style='font-size:50px;color:#cccccc;opacity:0.3;'>CONFIDENTIAL</div>",
        .VerticalAlignment = VerticalAlignment.Center,
        .HorizontalAlignment = HorizontalAlignment.Center
    },

    ' 5. Security
    .SecurityOptions = New PdfSecurityOptions With {
        .OwnerPassword = "StrongOwnerPwd!",
        .UserPassword = "ReadOnly",
        .AllowUserPrinting = False,
        .AllowUserCopyPasteContent = False
    }
}

' Render any HTML
Using pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Advanced Options Demo</h1>")
    ' Digitally sign with a PFX certificate (optional)
    pdf.SignAndStamp("./certs/company.pfx", "Iron Software", "Bangkok", "Approval")

    ' Save
    pdf.SaveAs("advanced-options-demo.pdf")
End Using
$vbLabelText   $csharpLabel

Dlaczego te opcje mają znaczenie

  • PaperSize, Margins i CssMediaType odwzorowują dialog wydruku przeglądarki, dzięki czemu układy ekranowe i pdf są identyczne na Windows, Linux i Docker.
  • Nagłówki i stopki HTML wspierają tokeny Razor, CSS i JavaScript — przydatne do dynamicznych numerów stron lub brandingu.
  • HtmlStamp pozwala na stworzenie markowych znaków wodnych z pełną kontrolą HTML + CSS za pomocą jednej linii kodu.
  • Opcje zabezpieczeń umożliwiają szyfrowanie 128-bitowe, hasła właściciela/użytkownika i szczegółowe uprawnienia bez użycia narzędzi firm trzecich.
  • Podpisy cyfrowe dodają kryptograficzne pieczęcie bezpośrednio w kodzie, zachowując legalną autentyczność i dowód naruszenia.
  • Pomocnicy do ekstrakcji takie jak ExtractAllText i ExtractAllImages odwracają proces, gdy analiza jest wymagana.

Szybki przegląd — Popularne ustawienia

PaperSize, PaperOrientation, Margins, CssMediaType, RenderDelay

HtmlHeader, HtmlFooter, dynamiczne zastępniki Razor, tokeny numerów stron

Watermark, HtmlStamp, przezroczystość, wyrównanie

SecurityOptions, SignAndStamp, hasła właściciela/użytkownika, zapieczętowanie certyfikatem

Następne zadania: złącz kilka PDFów, wyciągnij tekst i obrazy, i wdrażaj na Docker lub bezserwerowo. Przejdź do sekcji wdrożeniowej, aby zapewnić zgodność międzyplatformową.


Jak mogę wdrożyć kod generacji PDF na Docker w Linux i Windows?

IronPDF dostarczany jest jako pojedynczy samodzielny pakiet NuGet, więc konteneryzacja aplikacji ASP.NET Core (lub konsolowej) jest prosta na zarówno Windows jak i Linux. Kluczem jest skopiowanie opublikowanych binariów do smukłego obrazu wykonawczego i, w przypadku Linux, dodanie dwóch natywnych bibliotek wymaganych przez IronPDF (libnss3 i libatk1.0-0).

Wieloetapowy Dockerfile (Ubuntu 22.04)

Zwróć uwagęDlaczego wieloetapowy? Obraz SDK (etap 1) kompiluje projekt; końcowy obraz wykonawczy (etap 2) pozostaje smukły — < 120 MB — ponieważ narzędzia kompilacyjne są odrzucane.

####### ---------- stage 1 ----------
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY ["MyPdfApp.csproj", "."]
RUN dotnet restore

COPY . .
RUN dotnet publish -c Release -o /app/publish

####### ---------- stage 2 ----------
FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy
######## Install two native libs required by Chromium
RUN apt-get update && \
    apt-get install -y --no-install-recommends libnss3 libatk1.0-0 && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyPdfApp.dll"]

Zwróć uwagęKontenery Windows? Zastąp drugi etap mcr.microsoft.com/dotnet/aspnet:8.0-windowsservercore-ltsc2022 — nie są potrzebne dodatkowe pakiety, ponieważ DLL-e Chromium są dołączone.

Skrypt walidacji end-to-end

docker build -t pdf-demo .
docker run --rm -p 8080:80 pdf-demo
######### ↳ Navigate to http://localhost:8080/api/pdf?url=https://example.com
docker build -t pdf-demo .
docker run --rm -p 8080:80 pdf-demo
######### ↳ Navigate to http://localhost:8080/api/pdf?url=https://example.com
SHELL
  • Akcja API wewnętrznie wywołuje ChromePdfRenderer.RenderUrlAsPdf tak jak w Sekcji2.
  • IronPDF uruchamia swój proces Chromium w trybie piaskownicy wewnątrz kontenera — nie jest wymagany serwer X, ponieważ renderuje w trybie headless.
  • Zużycie pamięci pozostaje poniżej 200 MB nawet podczas dużych renderów.

PoradyWskazówka dotycząca rozwiązywania problemów: Jeśli dzienniki kontenera pokazują błąd "libnss3.so not found", potwierdź obecność zarówno libnss3 jak i libatk1.0-0. Obrazy Alpine nie są obsługiwane, ponieważ biblioteka musl C nie zawiera wymaganych symboli.

Zasoby wewnętrzne


Jak mogę otworzyć, połączyć, oznaczyć znakiem wodnym i wyciągnąć zawartość z istniejących PDF w .NET Core?

IronPDF traktuje każdy PDF — niezależnie od tego, czy został wygenerowany przez IronPDF, Adobe® Acrobat, czy narzędzia firm trzecich — jako pełnoprawny obiekt @@-CODE-367-@@, który może być otwarty, edytowany, zabezpieczony i ponownie zapisany bez utraty jakości. Ta sama powierzchnia API działa na .NET 8 LTS dzisiaj i kompiluje się bez zmian na wersji .NET 9 preview oraz nadchodzącym wydaniu .NET 10.

Przykład zjednoczony — otwórz → połącz → oznakuj znakiem wodnym → wyciągnij

// ManipulateExistingPdf.cs — .NET 8 LTS compatible
using IronPdf;
using System.Linq;

// Step 1: Open two existing files (password-protected PDFs are supported)
PdfDocument invoice  = PdfDocument.FromFile("invoice.pdf", "ReadOnly");   // open with user pwd
PdfDocument tAndCs   = PdfDocument.FromFile("terms.pdf");                 // no pwd required

// Step 2: Merge them (invoice pages first, then T&Cs)
PdfDocument mergedPdf = PdfDocument.Merge(invoice, tAndCs);               // 1-liner merge

// Step 3: Apply a diagonal CONFIDENTIAL watermark to every page
mergedPdf.ApplyStamp(
    "<div style='font-size:60px;color:#d9534f;opacity:0.2;transform:rotate(-45deg);"
  + "width:100%;text-align:center;'>CONFIDENTIAL</div>",
    verticalAlignment   : VerticalAlignment.Center,
    horizontalAlignment : HorizontalAlignment.Center);

// Step 4: Extract all text and the first image for audit purposes
string fullText = mergedPdf.ExtractAllText();
var    image    = mergedPdf.ExtractAllImages().FirstOrDefault();

// Step 5: Save or stream
mergedPdf.SaveAs("invoice-with-terms.pdf");
// ManipulateExistingPdf.cs — .NET 8 LTS compatible
using IronPdf;
using System.Linq;

// Step 1: Open two existing files (password-protected PDFs are supported)
PdfDocument invoice  = PdfDocument.FromFile("invoice.pdf", "ReadOnly");   // open with user pwd
PdfDocument tAndCs   = PdfDocument.FromFile("terms.pdf");                 // no pwd required

// Step 2: Merge them (invoice pages first, then T&Cs)
PdfDocument mergedPdf = PdfDocument.Merge(invoice, tAndCs);               // 1-liner merge

// Step 3: Apply a diagonal CONFIDENTIAL watermark to every page
mergedPdf.ApplyStamp(
    "<div style='font-size:60px;color:#d9534f;opacity:0.2;transform:rotate(-45deg);"
  + "width:100%;text-align:center;'>CONFIDENTIAL</div>",
    verticalAlignment   : VerticalAlignment.Center,
    horizontalAlignment : HorizontalAlignment.Center);

// Step 4: Extract all text and the first image for audit purposes
string fullText = mergedPdf.ExtractAllText();
var    image    = mergedPdf.ExtractAllImages().FirstOrDefault();

// Step 5: Save or stream
mergedPdf.SaveAs("invoice-with-terms.pdf");
' ManipulateExistingPdf.cs — .NET 8 LTS compatible
Imports IronPdf
Imports System.Linq

' Step 1: Open two existing files (password-protected PDFs are supported)
Private invoice As PdfDocument = PdfDocument.FromFile("invoice.pdf", "ReadOnly") ' open with user pwd
Private tAndCs As PdfDocument = PdfDocument.FromFile("terms.pdf") ' no pwd required

' Step 2: Merge them (invoice pages first, then T&Cs)
Private mergedPdf As PdfDocument = PdfDocument.Merge(invoice, tAndCs) ' 1-liner merge

' Step 3: Apply a diagonal CONFIDENTIAL watermark to every page
mergedPdf.ApplyStamp("<div style='font-size:60px;color:#d9534f;opacity:0.2;transform:rotate(-45deg);" & "width:100%;text-align:center;'>CONFIDENTIAL</div>", verticalAlignment := VerticalAlignment.Center, horizontalAlignment := HorizontalAlignment.Center)

' Step 4: Extract all text and the first image for audit purposes
Dim fullText As String = mergedPdf.ExtractAllText()
Dim image = mergedPdf.ExtractAllImages().FirstOrDefault()

' Step 5: Save or stream
mergedPdf.SaveAs("invoice-with-terms.pdf")
$vbLabelText   $csharpLabel

Dlaczego to ma znaczenie

  • Otwórz i połączPdfDocument.FromFile ładuje dowolny zgodny z normami PDF, w tym zaszyfrowane pliki, podczas gdy PdfDocument.Merge łączy dowolną liczbę dokumentów w jednym wywołaniu.
  • Znak wodnyApplyStamp (alias HtmlStamp) umieszcza w pełni stylizowane nakładki HTML/CSS — logo, kod QR lub tekst ukośny — na wybranych stronach bez rastrowania.
  • Ekstrakcja zawartościExtractAllText i ExtractAllImages wyciągają surowy tekst UTF-8 lub strumienie obrazów binarnych do archiwizacji lub pipeline'ów AI.
  • Gotowe do podpisów cyfrowych — ten sam PdfDocument można zapieczętować za pomocą SignAndStamp, co tworzy zgodne z RFC 3161 skróty zgodne z ISO 32000-2 wymagania cyfrowego podpisu.
  • Zgodność ze standardami otwartymi — IronPDF zachowuje oryginalną strukturę PDF (czcionki, warstwy, metadane XMP), dzięki czemu wyjście pozostaje kompatybilne z Adobe® Reader i innymi ISO 32000-1 przeglądarkami.
  • Przyszłościowe — API unika asemblerów interop i wywołań Win32 GDI, więc kod działa bez zmian na Windows, Linux, Docker i nadchodzących SKU .NET 10 bezserwerowy.

Potrzebujesz podzielić, obrócić lub usunąć strony? Zobacz tutorial edycji na poziomie strony dla operacji zróżnicowanych.


Jak można zaszyfrować i cyfrowo podpisać PDF w .NET Core?

IronPDF zabezpiecza dokument w dwóch krokach: szyfrowanie oparte na AES (hasła użytkownika/właściciela + szczegółowe uprawnienia) i cyfrowe podpisy X.509, które zamykają plik kryptograficznym skrótem. Oba API żyją na tym samym obiekcie PdfDocument, więc przepływ pracy jest identyczny na .NET 8 LTS dzisiaj i kompiluje się bez zmian na .NET 9 preview i nadchodzącej wersji .NET 10.

Przykład — zastosuj AES 256-bitów, zablokuj prawa do wydruku i dodaj widoczny podpis

// SecureAndSign.cs — .NET 8 LTS compatible
using IronPdf;

// Step 1: Load an existing PDF (or produce one with RenderHtmlAsPdf)
PdfDocument pdf = PdfDocument.FromFile("financial-report.pdf");

// Step 2: Configure AES-256 encryption & permissions
pdf.SecuritySettings = new PdfSecuritySettings
{
    EncryptionAlgorithm   = PdfEncryptionAlgorithm.AES256Bit,
    OwnerPassword         = "IronAdmin!2025",
    UserPassword          = "ReadOnly",
    AllowUserPrinting     = PdfPrintSecurity.Disabled,
    AllowUserCopyPasteContent = false,
    AllowUserAnnotations  = false
};

// Step 3: Digitally sign with a PFX certificate
pdf.SignAndStamp(
    certificatePath : "./certs/ironsoftware.pfx",
    authority       : "Iron Software Ltd.",
    location        : "Chicago, IL",
    reason          : "Final approval"
);

// Step 4: Persist or stream
pdf.SaveAs("financial-report-secured-signed.pdf");
// SecureAndSign.cs — .NET 8 LTS compatible
using IronPdf;

// Step 1: Load an existing PDF (or produce one with RenderHtmlAsPdf)
PdfDocument pdf = PdfDocument.FromFile("financial-report.pdf");

// Step 2: Configure AES-256 encryption & permissions
pdf.SecuritySettings = new PdfSecuritySettings
{
    EncryptionAlgorithm   = PdfEncryptionAlgorithm.AES256Bit,
    OwnerPassword         = "IronAdmin!2025",
    UserPassword          = "ReadOnly",
    AllowUserPrinting     = PdfPrintSecurity.Disabled,
    AllowUserCopyPasteContent = false,
    AllowUserAnnotations  = false
};

// Step 3: Digitally sign with a PFX certificate
pdf.SignAndStamp(
    certificatePath : "./certs/ironsoftware.pfx",
    authority       : "Iron Software Ltd.",
    location        : "Chicago, IL",
    reason          : "Final approval"
);

// Step 4: Persist or stream
pdf.SaveAs("financial-report-secured-signed.pdf");
' SecureAndSign.cs — .NET 8 LTS compatible
Imports IronPdf

' Step 1: Load an existing PDF (or produce one with RenderHtmlAsPdf)
Private pdf As PdfDocument = PdfDocument.FromFile("financial-report.pdf")

' Step 2: Configure AES-256 encryption & permissions
pdf.SecuritySettings = New PdfSecuritySettings With {
	.EncryptionAlgorithm = PdfEncryptionAlgorithm.AES256Bit,
	.OwnerPassword = "IronAdmin!2025",
	.UserPassword = "ReadOnly",
	.AllowUserPrinting = PdfPrintSecurity.Disabled,
	.AllowUserCopyPasteContent = False,
	.AllowUserAnnotations = False
}

' Step 3: Digitally sign with a PFX certificate
pdf.SignAndStamp(certificatePath := "./certs/ironsoftware.pfx", authority := "Iron Software Ltd.", location := "Chicago, IL", reason := "Final approval")

' Step 4: Persist or stream
pdf.SaveAs("financial-report-secured-signed.pdf")
$vbLabelText   $csharpLabel

Kulisy działania

  • Szyfrowanie AES-256 -- IronPDF opakowuje ładunek przy użyciu zatwierdzonych przez NIST kluczy AES, blokując nieautoryzowane otwarcie, drukowanie lub kopiowanie/wklejanie.
  • Granulacja uprawnień -- właściwości, takie jak AllowUserPrinting i AllowUserFormData przełączają prawa na akcję; wymagane jest hasło właściciela, aby jakiekolwiek ograniczenie mogło mieć skutek.
  • Podpisy cyfrowe -- SignAndStamp umieszcza znacznik czasu RFC 3161 i ciąg certyfikatów, tworząc niewidoczne dowody naruszeń uznawane przez Adobe® Acrobat i inne przeglądarki zgodne z ISO 32000-2.
  • API jednego przystanku -- zarówno szyfrowanie, jak i podpisywanie modyfikują tę samą instancję PdfDocument, unikając wielu przejść plików i zachowując wewnętrzne czcionki, warstwy i metadane.

PoradyWskazówka dotycząca rozwiązywania problemów: jeśli Adobe Reader raportuje "invalid signature", upewnij się, że PFX zawiera zaufany certyfikat root i że łańcuchy location są czyste ASCII.

Podstawowe ustawienia zabezpieczeń

PdfSecuritySettingsOwnerPassword, UserPassword, EncryptionAlgorithm, AllowUserPrinting

PdfDocument.SignAndStamp — ścieżka PFX, authority, location, reason, timestamp

Zasoby wewnętrzne dla głębszych analiz


Jak zoptymalizować i skalować wydajność konwersji HTML na PDF w .NET Core?

Silnik Chromium IronPDF zwykle renderuje większość stron w < 1 s na nowoczesnym sprzęcie, ale przepustowość można zwielokrotnić przez zgrupowanie renderów, włączenie wielowątkowości i zmniejszenie obciążenia headless-Chrome. Poniższe wskazówki są równie ważne dla wszystkich wersji .NET.

1. Grupowe renderowanie na tle wątków

// BatchRender.cs — Thread-safe on .NET 8+
using IronPdf;
using System.Threading.Tasks;

var htmlSources = Directory.GetFiles("./html", "*.html");
var renderer    = new ChromePdfRenderer();                 // reuse 1 instance

Parallel.ForEach(htmlSources, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, file =>
{
    string html = File.ReadAllText(file);
    using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(Path.ChangeExtension(file, ".pdf"));
});
// BatchRender.cs — Thread-safe on .NET 8+
using IronPdf;
using System.Threading.Tasks;

var htmlSources = Directory.GetFiles("./html", "*.html");
var renderer    = new ChromePdfRenderer();                 // reuse 1 instance

Parallel.ForEach(htmlSources, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, file =>
{
    string html = File.ReadAllText(file);
    using PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
    pdf.SaveAs(Path.ChangeExtension(file, ".pdf"));
});
' BatchRender.cs — Thread-safe on .NET 8+
Imports IronPdf
Imports System.Threading.Tasks

Private htmlSources = Directory.GetFiles("./html", "*.html")
Private renderer = New ChromePdfRenderer() ' reuse 1 instance

Parallel.ForEach(htmlSources, New ParallelOptions With {.MaxDegreeOfParallelism = Environment.ProcessorCount}, Sub(file)
	Dim html As String = File.ReadAllText(file)
	Using pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
		pdf.SaveAs(Path.ChangeExtension(file, ".pdf"))
	End Using
End Sub)
$vbLabelText   $csharpLabel

2. Zmniejsz koszt uruchomienia headless-Chrome

IronPDF dostarcza własną wersję Chromium, ale każdy render niesie ze sobą niewielki podatek startowy. Pooling pomaga, a Linux containers muszą zawierać dwa natywne biblioteki:

RUN apt-get update && \
    apt-get install -y --no-install-recommends libnss3 libatk1.0-0

Missing either library manifests as a libnss3.so not found error in Docker logs.

Recommended Chrome flags (automatically applied by IronPDF) include --disable-gpu and --no-sandbox to reduce memory and root-user issues in containers.

3. Czekaj na późny JavaScript z RenderDelay lub WaitFor

Strony, które animują liczniki lub pobierają dane po DOMContentLoaded mogą wymagać krótkiego opóźnienia:

renderer.RenderingOptions.RenderDelay = 200;        // ms
// OR: renderer.RenderingOptions.JavaScript = "WaitFor('window.doneLoading')";
renderer.RenderingOptions.RenderDelay = 200;        // ms
// OR: renderer.RenderingOptions.JavaScript = "WaitFor('window.doneLoading')";
renderer.RenderingOptions.RenderDelay = 200 ' ms
' OR: renderer.RenderingOptions.JavaScript = "WaitFor('window.doneLoading')";
$vbLabelText   $csharpLabel

Zobacz dedykowany przewodnik WaitFor dla niestandardowych obietnic i odpytywania DOM.

4. Włącz logowanie debugowania dla jednego usługi

renderer.LoggingOptions.DebugMode        = true;
renderer.LoggingOptions.LogsToConsole    = true;
renderer.LoggingOptions.LogFilePath      = "./logs/ironpdf-debug.log";
renderer.LoggingOptions.DebugMode        = true;
renderer.LoggingOptions.LogsToConsole    = true;
renderer.LoggingOptions.LogFilePath      = "./logs/ironpdf-debug.log";
renderer.LoggingOptions.DebugMode = True
renderer.LoggingOptions.LogsToConsole = True
renderer.LoggingOptions.LogFilePath = "./logs/ironpdf-debug.log"
$vbLabelText   $csharpLabel

Ślady Live DevTools ujawniają brakujące czcionki, obrazy 404 i zdarzenia czasowe bez ponownej kompilacji kodu.

5. Ponownie używaj szablonów PDF zamiast ponownego renderowania

Dla przebiegów faktury, stwórz szablon PDF z zastępną jak [[name]] i wykonaj zamianę tekstu zamiast odbudowy sanowitego HTML. Jest to 10x szybsze i lekkie dla pamięci.

Lista kontrolna szybkiego tuningu

Parallel.ForEach, async/await, ponowne użycie pojedynczego ChromePdfRenderer

Użyj aspnet:8.0-jammy; zainstaluj libnss3 + libatk1.0-0; flagi --no-sandbox, --disable-gpu

RenderDelay, WaitFor(), zaloguj DevTools timelinę dla wolnych hydratacji SPA

Dalsza lektura


Gdzie mogę pobrać bezpłatną wersję próbną, wybrać licencję i znaleźć pomoc ekspertów? {#anchor-10-resources}

30-dniowy klucz próbny jest wydawany natychmiast z formularza Rozpocznij darmową próbę i odblokowuje każdą funkcję — w tym HTML-do-PDF, cyfrowe podpisy i szyfrowanie — bez znaków wodnych.

Po ocenieniu biblioteki, wybierz wieczystą licencję programisty, wdrożenia, lub enterprises; każdy plan zawiera bezpłatne aktualizacje, prawa do użytkowania w deweloperskich, stagingowych i produkcyi oraz 30-dniową gwarancję zwrotu pieniędzy. Zastosowanie klucza to jedna linia kodu (IronPdf.License.LicenseKey = "YOUR-KEY";) i może być zautomatyzowane w pipeline CI/CD.

Kompleksowa dokumentacja— przewodniki szybkiego startu, dokumentacja API i samouczki wideo — jest dostępna w portalu dokumentacji i aktualizowana dla każdej wersji .NET.

Pytania inżynieryjne otrzymują odpowiedź w ciągu jednego dnia roboczego poprzez czat na żywo, e-mail lub telefon od zespołu wsparcia z Chicago.

Centrum Wspomagania Wydajności zawiera FAQ dotyczące tuningu i wdrażania.

Szybkie linki

Zasoby URL Dlaczego to ma znaczenie
Uzyskaj 30-dniowy klucz próbny https://ironpdf.com/demos/ Odblokowuje wszystkie funkcje bez znaków wodnych
Licencjonowanie i cennik https://ironpdf.com/licensing/ Plany wieczyste lub subskrypcyjne; Iron Suite pakietuje 10 bibliotek
Dokumentacja API https://ironpdf.com/object-reference/api/ Pełna dokumentacja klas, np. ChromePdfRenderer
Portal dokumentacji https://ironpdf.com/docs/ Przewodniki, samouczki, przykłady projektów
Centrum pomocy przy wydajności https://ironpdf.com/troubleshooting/ironpdf-performance-assistance/ Wskazówki dotyczące optymalizacji i skalowania
Kontakt ze wsparciem https://ironsoftware.com/contact-us/ Czat na żywo, e-mail, wsparcie telefoniczne

Następne kroki

  1. Sklonuj repozytorium przykladowe, które demonstruje wszystkie glówne funkcje—from MVC view rendering to AES-256 encryption.
  2. Podlacz klucz probny do istniejacego rozwiazania i uruchom testy jednostkowe, aby zweryfikowac zgodnosc miedzyplatformowa.
  3. Zarezerwuj demonstracje na zywo z zespołem inżynieryjnym w celu uzyskania rekomendacji specyficznych dla projektu.

Dzieki tym zasobom kazdy zespół .NET moze dostarczyc do produkcji idealnie zgodne z pikselami PDF-y—lokalnie, w Dockerze lub serverless—w ciagu jednego sprintu.

Często Zadawane Pytania

Jak przekonwertować HTML na PDF w .NET Core?

You can convert HTML to PDF in .NET Core by using the IronPDF library. First, install the IronPDF NuGet package, then create a ChromePdfRenderer instance. Use the RenderHtmlAsPdf method to convert HTML strings into PDFs.

How do I convert a website URL to a PDF document?

To convert a website URL to a PDF document, install the IronPDF NuGet package, create a ChromePdfRenderer instance, and use the RenderUrlAsPdf method to render the URL into a PDF. The result can be saved using the SaveAs method.

What is the best way to convert Razor views to PDFs?

The best way to convert Razor views to PDFs is by using IronPDF. First, render the Razor view to an HTML string, then pass this string to the RenderHtmlAsPdf method to create a PDF document.

How can I enhance the security of my PDF documents?

Enhance PDF security using IronPDF by applying AES-256 encryption, setting passwords, and controlling user permissions. Configure these settings through the SecuritySettings property to restrict actions like printing and editing.

What options are available for customizing PDF rendering?

IronPDF provides various rendering options through the ChromePdfRenderOptions class, including setting paper size, orientation, margins, and applying CSS media types. You can also add headers, footers, and watermarks for customized document output.

How do I deploy a PDF generation application in a Docker container?

To deploy a PDF generation application in a Docker container, configure Linux dependencies in your Dockerfile and set user permissions. Utilize IronPdf.Installation.LinuxAndDockerDependenciesAutoConfig for automatic dependency management.

How can I add watermarks to a PDF using C#?

You can add watermarks to PDFs using IronPDF by utilizing the Watermark property with HtmlStamp objects. For advanced options, the HtmlStamper class allows for custom positioning and transparency effects.

Can I add digital signatures to PDF documents?

Yes, you can add digital signatures to PDFs using IronPDF's PdfSignature class. Use the Sign method on a PdfDocument and provide a certificate file to ensure document integrity and authenticity.

How can I optimize PDF generation performance in .NET Core?

Optimize PDF generation performance by re-using a thread-safe ChromePdfRenderer instance, enabling multi-threading, and trimming unnecessary headless-Chrome startup flags. These practices help improve the efficiency of your application.

Does the .NET Core HTML-to-PDF example in this tutorial also work with .NET 10?

Yes. IronPDF is fully compatible with .NET 10, so you can use the ChromePdfRenderer HTML-to-PDF example from this tutorial in .NET 10 projects without changing the core code. The main difference is that you target .NET 10 when creating the project, then install the latest IronPdf package from NuGet to generate pixel-perfect PDFs from HTML, Razor views, or URLs.

Jacob Mellor, Dyrektor Technologiczny @ Team Iron
Dyrektor ds. technologii

Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczą...

Czytaj więcej
Sprawdzone przez
Jeff Fritz
Jeffrey T. Fritz
Główny Menedżer Programu - Zespół .NET Community
Jeff jest również Głównym Menedżerem Programu dla zespołów .NET i Visual Studio. Jest producentem wykonawczym wirtualnej serii konferencji .NET Conf i prowadzi 'Fritz and Friends', transmisję na żywo dla deweloperów emitowaną dwa razy w tygodniu, gdzie rozmawia o technologii i pisze kod razem z widzami. Jeff pisze warsztaty, prezentacje i planuje treści dla największych wydarzeń Microsoft dla deweloperów, w tym Microsoft Build, Microsoft Ignite, .NET Conf i Microsoft MVP Summit.
Gotowy, aby rozpocząć?
Nuget Pliki do pobrania 18,135,201 | Wersja: 2026.4 just released
Still Scrolling Icon

Wciąż przewijasz?

Czy chcesz szybko dowodu? PM > Install-Package IronPdf
Uruchom przykład i zobacz, jak Twój kod HTML zamienia się w plik PDF.