How to Render HTML String to PDF in C# | IronPDF

Jak konwertować ciąg HTML na PDF w C

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

IronPDF konwertuje ciągi HTML na dokumenty PDF w C# przy użyciu silnika renderowania Chrome, wspierając cały HTML5, CSS3 i JavaScript w pojedynczej linii kodu dla podstawowej konwersji. Biblioteka oferuje potężne funkcje do tworzenia PDF-ów, zachowując doskonałą wierność renderowania.

IronPDF pozwala deweloperom na łatwe tworzenie dokumentów PDF w C#, F# i VB.NET dla .NET Core i .NET Framework. IronPDF wspiera renderowanie dowolnego ciągu HTML do PDF, a proces renderowania wykorzystuje w pełni funkcjonalną wersję silnika Google Chromium. To zapewnia, że zawartość HTML wygląda dokładnie tak samo, jak w nowoczesnej przeglądarce internetowej, co jest idealne do generowania raportów, faktur i dokumentów z dynamicznej zawartości HTML.

Szybki start: Przekonwertuj ciąg HTML na PDF w kilka sekund

Przekształć ciągi HTML na pliki PDF za pomocą IronPDF. Ten przewodnik pokazuje, jak przekonwertować ciąg HTML na dokument PDF w C# przy minimalnym kodzie. Idealne dla deweloperów, którzy muszą zintegrować możliwości renderowania PDF w swoich projektach.

  1. Install IronPDF with NuGet Package Manager

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

    IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("<p>Hello World</p>").SaveAs("string-to-pdf.pdf");
  3. Wdrożenie do testowania w środowisku produkcyjnym

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

    arrow pointer


Jak przekonwertować prosty ciąg HTML na PDF?

Oto przykład IronPDF renderujący ciąg HTML na PDF za pomocą metody RenderHtmlAsPdf. Parametr to ciąg HTML do renderowania jako PDF. Ta metoda jest częścią klasy ChromePdfRenderer, która zapewnia rozbudowaną kontrolę nad opcje renderowania dla potrzeb generacji 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

Metoda RenderHtmlAsPdf zwraca obiekt PdfDocument, który przechowuje informacje o PDF i oferuje metody manipulacji PDF, w tym scalanie PDF, dodawanie znaku wodnego i ustawianie opcji bezpieczeństwa.

PoradyW ASP.NET Core, Blazor lub usługach w tle, preferuj wersję asynchroniczną RenderHtmlAsPdfAsync, aby uniknąć blokowania wątków. Zwracany PdfDocument implementuje IDisposable, więc owiń go w blok using dla scenariuszy o wysokim przepływie. ChromePdfRenderer jest bezpieczny dla wątków i może być zainicjalizowany raz i ponownie używany w wielu żądaniach dla lepszej wydajności.

Gdy ciąg HTML pochodzi z zewnętrznego źródła i należy wyłączyć dostęp do lokalnego dysku lub żądania cross-origin, należy ustawić IronPdf.Installation.EnableWebSecurity na true przed renderowaniem. To jest globalne ustawienie statyczne, a nie właściwość instancji na rendererze.

// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
// Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = true;
' Enable web security before rendering untrusted HTML
IronPdf.Installation.EnableWebSecurity = True
$vbLabelText   $csharpLabel

Dla skomplikowanej zawartości HTML zawierającej stylizację CSS, wzbogacaj swoje ciągi HTML stylem w linii lub odnośnikiem do zewnętrznych arkuszy stylów przy użyciu funkcji Base URLs & Asset Encoding:

// Example with inline CSS
var styledHtml = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; border-bottom: 2px solid #0066cc; }
        p { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Professional Report</h1>
    <p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";

using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
// Example with inline CSS
var styledHtml = @"
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; border-bottom: 2px solid #0066cc; }
        p { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Professional Report</h1>
    <p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>";

using var styledPdf = renderer.RenderHtmlAsPdf(styledHtml);
styledPdf.SaveAs("styled-output.pdf");
Dim styledHtml As String = "
<html>
<head>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; }
        h1 { color: #333; border-bottom: 2px solid #0066cc; }
        p { line-height: 1.6; }
    </style>
</head>
<body>
    <h1>Professional Report</h1>
    <p>This PDF was generated from HTML with custom styling.</p>
</body>
</html>"

Using styledPdf = renderer.RenderHtmlAsPdf(styledHtml)
    styledPdf.SaveAs("styled-output.pdf")
End Using
$vbLabelText   $csharpLabel

Jak wygląda wygenerowany plik PDF?

To jest plik wygenerowany przez kod:

Generowany PDF zachowuje dokładne formatowanie i stylizację z twojego HTML, co czyni go idealnym do generowania raportów PDF lub konwersji zawartości webowej na dokumenty gotowe do druku.

Jak mogę uwzględnić zewnętrzne zasoby przy konwersji HTML do PDF?

Ten przykład pokazuje, jak IronPDF ładuje zewnętrzne zasoby obrazu z opcjonalnego BasePath. Ustawienie właściwości BaseUrlOrPath podaje względną ścieżkę do pliku lub kontekst URL dla hiperłącza, obrazów, CSS i plików JavaScript. Jest to niezbędne przy pracy z obrazami w PDF lub gdy potrzebujesz odwołać się do zewnętrznych zasobów.

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

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

// Advanced Example with HTML Assets
// Load external html assets: Images, CSS and JavaScript.
// An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
var myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");
myAdvancedPdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Advanced Example with HTML Assets
' Load external html assets: Images, CSS and JavaScript.
' An optional BasePath 'C:\site\assets\' is set as the file location to load assets from
Private myAdvancedPdf = renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", "C:\site\assets\")
myAdvancedPdf.SaveAs("html-with-assets.pdf")
$vbLabelText   $csharpLabel

Dla zaawansowanych scenariuszy obejmujących skomplikowane układy lub dynamiczną zawartość, wykorzystaj wsparcie IronPDF dla renderowania JavaScript:

// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
    <script>
        window.onload = function() {
            document.getElementById('dynamic').innerHTML = 
                'Generated on: ' + new Date().toLocaleString();
        };
    </script>
</head>
<body>
    <h1>Dynamic Content Example</h1>
    <div id='dynamic'></div>
</body>
</html>";

// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
// Example with JavaScript-generated content
var jsHtml = @"
<html>
<head>
    <script>
        window.onload = function() {
            document.getElementById('dynamic').innerHTML = 
                'Generated on: ' + new Date().toLocaleString();
        };
    </script>
</head>
<body>
    <h1>Dynamic Content Example</h1>
    <div id='dynamic'></div>
</body>
</html>";

// Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500); // milliseconds
using var dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, @"C:\site\");
dynamicPdf.SaveAs("dynamic-content.pdf");
Imports System

' Example with JavaScript-generated content
Dim jsHtml As String = "
<html>
<head>
    <script>
        window.onload = function() {
            document.getElementById('dynamic').innerHTML = 
                'Generated on: ' + new Date().toLocaleString();
        };
    </script>
</head>
<body>
    <h1>Dynamic Content Example</h1>
    <div id='dynamic'></div>
</body>
</html>"

' Configure rendering to wait for JavaScript execution
renderer.RenderingOptions.WaitFor.RenderDelay(500) ' milliseconds
Using dynamicPdf = renderer.RenderHtmlAsPdf(jsHtml, "C:\site\")
    dynamicPdf.SaveAs("dynamic-content.pdf")
End Using
$vbLabelText   $csharpLabel

Pracując z zewnętrznymi zasobami, może zajść potrzeba obsługi uwierzytelniania lub specjalnych nagłówków. IronPDF wspiera to poprzez funkcjonalność HTTP Request Header, pozwalając na dołączenie tokenów autoryzacji lub niestandardowych nagłówków przy pobieraniu zasobów.

Dlaczego ustawienie BasePath jest ważne dla zasobów zewnętrznych?

To jest plik wygenerowany przez kod:

Prawidłowe ustawienie BasePath zapewnia prawidłowe rozwiązywanie wszystkich względnych odniesień w twoim HTML. Bez tego IronPDF nie jest w stanie zlokalizować zewnętrznych zasobów takich jak obrazy, arkusze stylów czy skrypty. Jest to szczególnie ważne gdy:

  1. Konwersja HTML, która odnosi się do zasobów lokalnego systemu plików
  2. Praca z systemami zarządzania treścią, które używają względnych URL-i
  3. Migracja istniejącej zawartości webowej do formatu PDF
  4. Tworzenie szablonów, które używają wspólnych zasobów

Dla zasobów webowych, użyj pełnego URL jako ścieżki bazowej:

// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
    "<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>", 
    "https://mywebsite.com"
);
// Using a web URL as base path
var webBasedPdf = renderer.RenderHtmlAsPdf(
    "<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>", 
    "https://mywebsite.com"
);
' Using a web URL as base path
Dim webBasedPdf = renderer.RenderHtmlAsPdf(
    "<link rel='stylesheet' href='/styles/main.css'><h1>Web Content</h1>", 
    "https://mywebsite.com"
)
$vbLabelText   $csharpLabel

Aby uzyskać większą kontrolę nad procesem generacji PDF, należy zapoznać się z obszerną dokumentacją IronPDF na temat niestandardowych marginesów, orientacji strony oraz kompresji PDF, aby zoptymalizować pliki wyjściowe dla różnych przypadków użycia.

Często Zadawane Pytania

How do I convert a simple HTML string to PDF in C#?

You can convert an HTML string to PDF using IronPDF's ChromePdfRenderer class with the RenderHtmlAsPdf method. Simply instantiate the renderer, pass your HTML string to the method, and save the resulting PdfDocument object. IronPDF uses a Chrome rendering engine to ensure perfect fidelity.

What rendering engine does the HTML to PDF conversion use?

IronPDF uses a fully functional version of the Google Chromium engine for rendering HTML to PDF. This ensures that your HTML content, including HTML5, CSS3, and JavaScript, appears exactly as it would in a modern web browser.

Can I convert HTML with CSS styling to PDF?

Yes, IronPDF supports converting HTML with CSS styling to PDF. You can use inline styles directly in your HTML string or reference external stylesheets using the Base URLs & Asset Encoding feature to ensure proper rendering of styled content.

What is the quickest way to convert HTML to PDF?

The quickest way is using IronPDF's static method: IronPdf.ChromePdfRenderer.StaticRenderHtmlAsPdf("Your HTML").SaveAs("output.pdf"). This single line of code converts your HTML string and saves it as a PDF file.

How do I handle external assets when converting HTML strings?

IronPDF allows you to configure the BasePath for external assets in your PDF. This ensures that images, stylesheets, and other resources referenced in your HTML are properly loaded during the conversion process.

Can I customize the PDF output when converting from HTML?

Yes, IronPDF provides extensive RenderingOptions to fine-tune your PDF output. You can control page size, margins, headers, footers, and many other aspects of the generated PDF through the ChromePdfRenderer class.

What can I do with the generated PDF after conversion?

IronPDF's PdfDocument object provides numerous methods for PDF manipulation, including merging PDFs, adding watermarks, setting security options, and more. The converted PDF can be saved to disk, streamed, or further processed as needed.

How do I handle security when converting HTML from external sources?

When converting HTML from external sources, IronPDF allows you to set the EnableWebSecurity property to true on the ChromePdfRenderer. This disables local disk access and cross-origin requests for enhanced security.

Curtis Chau
Autor tekstów technicznych

Curtis Chau posiada tytuł licencjata z informatyki (Uniwersytet Carleton) i specjalizuje się w front-endowym rozwoju, z ekspertką w Node.js, TypeScript, JavaScript i React. Pasjonuje się tworzeniem intuicyjnych i estetycznie przyjemnych interfejsów użytkownika, Curtis cieszy się pracą z nowoczesnymi frameworkami i tworzeniem dobrze zorganizowanych, atrakcyjnych wizualnie podrę...

Czytaj więcej
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.