How to use Web Assets and Optimize PDFs in C#

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

With over 100 features, IronPDF is designed to simplify PDF generation and manipulation tasks for .NET developers. This library is a one-stop solution for all your PDF needs, eliminating the need to install any third-party tools or Adobe Acrobat.

One crucial aspect that IronPDF covers is its extensive support for web assets. These tools allow the seamless use of HTML, JavaScript, web fonts, and more within your PDF documents. With this, you can create truly unique PDF documents.

IronPDF also provides impressive performance when generating and working with PDF files. This ensures smooth PDF operations without straining your system, especially when working with performance-intensive PDF tasks such as processing large batches, big files, and more.

Quickstart: Integrate Web Assets and Optimize PDFs Efficiently

This quick start guide demonstrates how to enhance your PDFs by adding web assets like images and fonts using IronPDF. With just a few lines of code, you can significantly improve the performance and visual quality of your PDF documents. Whether you're embedding a company logo or custom fonts, IronPDF makes the process fast and straightforward, ensuring your PDFs are both optimized and visually engaging.

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.

    new IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("<h1>Hello Performance</h1>").CompressImages(50).Flatten().SaveAs("fast‑optimized.pdf");
  3. Deploy to test on your live environment

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

Table of Contents

NuGet Instalar con NuGet

PM >  Install-Package IronPdf

Echa un vistazo a IronPDF en NuGet para una instalación rápida. Con más de 10 millones de descargas, está transformando el desarrollo de PDF con C#. También puede descargar el DLL o el instalador de Windows.

Implement Web Assets into your PDFs

IronPDF's robust support for web assets empowers developers with complete control over the appearance of their PDF documents. From its comprehensive support for HTML, CSS, and JavaScript for a pixel-perfect rendering of HTML content to PDF, to the ability to implement custom fonts and images for visually appealing elements within the document, IronPDF's support for modern web standards and assets enables developers to produce high-quality, visually appealing PDFs effortlessly.

Working with Dynamic Web Content

Let's start by exploring how IronPDF simplifies the process of creating PDF documents from HTML content, complete with CSS styling and JavaScript elements. This straightforward process instills confidence in developers, knowing that they can easily convert their web assets into PDFs.

Debug HTML with Chrome

IronPDF's powerful rendering engine ensures pixel-perfect rendering of any HTML content. This means that the PDFs you render from HTML content will look exactly the same as the HTML does within a Chrome browser, providing a reliable and consistent rendering experience.

:path=/static-assets/pdf/content-code-examples/how-to/pixel-perfect-html-to-pdf-1.cs
// Pixel Perfect HTML Formatting Settings
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer();
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print; // or Screen
' Pixel Perfect HTML Formatting Settings
Dim renderer As New IronPdf.ChromePdfRenderer()
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print ' or Screen
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

CSS (Screen & Print)

CSS controls the design and layout of HTML content. Through its support for CSS styling, IronPDF can produce visually appealing PDF documents while maintaining the original layout and styling of the converted HTML content.

:path=/static-assets/pdf/content-code-examples/how-to/html-to-pdf-responsive-css-table-header.cs
using IronPdf;
using IronPdf.Rendering;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Change the paper size to small
renderer.RenderingOptions.SetCustomPaperSizeinPixelsOrPoints(600, 400);

// Choose screen or print CSS media
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print;

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlFileAsPdf("tableHeader.html");

pdf.SaveAs("tableHeader.pdf");
Imports IronPdf
Imports IronPdf.Rendering

Private renderer As New ChromePdfRenderer()

' Change the paper size to small
renderer.RenderingOptions.SetCustomPaperSizeinPixelsOrPoints(600, 400)

' Choose screen or print CSS media
renderer.RenderingOptions.CssMediaType = PdfCssMediaType.Print

' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlFileAsPdf("tableHeader.html")

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

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Images (jpg, png, svg, gif, etc)

Enhance your PDFs with visual elements using images. When you embed images into your PDF document with IronPDF, the images will be viewable without relying on the internet or working links. This means you can add visually appealing images to attract readers' attention, add images that contain more information for your PDF's topic, and more.

:path=/static-assets/pdf/content-code-examples/how-to/add-images-to-pdfs-embed-image.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

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

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

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

Private renderer As New ChromePdfRenderer()

Private html As String = "<img src='https://ironsoftware.com/img/products/ironpdf-logo-text-dotnet.svg'>"

' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

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

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

JavaScript (Custom Render Delays)

Often, HTML content may contain interactive and dynamic elements that can be lost during the conversion process with some PDF libraries. IronPDF's support for JavaScript ensures that converted content maintains its original interactive elements.

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

string htmlWithJavaScript = @"<h1>This is HTML</h1>
<script>
    document.write('<h1>This is JavaScript</h1>');
    window.ironpdf.notifyRender();
</script>";

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

// Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = true;
// Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500);

// Render HTML contains JavaScript
var pdfJavaScript = renderer.RenderHtmlAsPdf(htmlWithJavaScript);

// Export PDF
pdfJavaScript.SaveAs("javascriptHtml.pdf");
Imports IronPdf

Private htmlWithJavaScript As String = "<h1>This is HTML</h1>
<script>
    document.write('<h1>This is JavaScript</h1>');
    window.ironpdf.notifyRender();
</script>"

' Instantiate Renderer
Private renderer = New ChromePdfRenderer()

' Enable JavaScript
renderer.RenderingOptions.EnableJavaScript = True
' Set waitFor for JavaScript
renderer.RenderingOptions.WaitFor.JavaScript(500)

' Render HTML contains JavaScript
Dim pdfJavaScript = renderer.RenderHtmlAsPdf(htmlWithJavaScript)

' Export PDF
pdfJavaScript.SaveAs("javascriptHtml.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Use WaitFor to Delay PDF Render

When rendering PDF documents, there are times when the necessary assets haven't been fetched yet, resulting in an incomplete rendering. With IronPDF, we can specify a render delay to ensure that all assets are obtained before rendering.

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

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Render as soon as the page is loaded
renderer.RenderingOptions.WaitFor.PageLoad();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Fonts (Web & Icon)

By adding custom fonts to your PDF documents, you can create truly unique PDF files that fit the needs of the type of document you're making. IronPDF simplifies this process, allowing you to capture users' attention with clean, yet visually appealing, font types or utilize web fonts to ensure consistent text across different machines, regardless of the local font availability on that computer.

:path=/static-assets/pdf/content-code-examples/how-to/webfonts-webicons-render-webfont.cs
using IronPdf;

// HTML contains webfont
var html = @"<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>";

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000);

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

// Export the PDF
pdf.SaveAs("font-test.pdf");
Imports IronPdf

' HTML contains webfont
Private html = "<link href=""https://fonts.googleapis.com/css?family=Lobster"" rel=""stylesheet"">
<p style=""font-family: 'Lobster', serif; font-size:30px;"" > Hello Google Fonts</p>"

Private renderer As New ChromePdfRenderer()

' Wait for font to load
renderer.RenderingOptions.WaitFor.AllFontsLoaded(2000)

' Render HTML to PDF
Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)

' Export the PDF
pdf.SaveAs("font-test.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Use SVG Graphics

Aside from rendering images to PDF, IronPDF also offers the ability to render SVG graphics into PDFs.

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

string html = "<img src='https://ironsoftware.com/img/svgs/new-banner-svg.svg' style='width:100px'>";

ChromePdfRenderer renderer = new ChromePdfRenderer();
renderer.RenderingOptions.WaitFor.RenderDelay(1000);

PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
pdf.SaveAs("svgToPdf.pdf");
Imports IronPdf

Private html As String = "<img src='https://ironsoftware.com/img/svgs/new-banner-svg.svg' style='width:100px'>"

Private renderer As New ChromePdfRenderer()
renderer.RenderingOptions.WaitFor.RenderDelay(1000)

Dim pdf As PdfDocument = renderer.RenderHtmlAsPdf(html)
pdf.SaveAs("svgToPdf.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Manage Fonts

Choosing the correct font and being able to customize and embed fonts are crucial aspects when creating PDFs. With IronPDF, you can manage, retrieve, and add fonts all in one package with intuitive methods.

:path=/static-assets/pdf/content-code-examples/how-to/manage-font-retrieve-font.cs
using IronPdf;
using IronPdf.Fonts;
using System.Collections.Generic;

// Import PDF
PdfDocument pdf = PdfDocument.FromFile("sample.pdf");

// Retreive font
PdfFontCollection fonts = pdf.Fonts;
Imports IronPdf
Imports IronPdf.Fonts
Imports System.Collections.Generic

' Import PDF
Private pdf As PdfDocument = PdfDocument.FromFile("sample.pdf")

' Retreive font
Private fonts As PdfFontCollection = pdf.Fonts
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Support UTF-8 and International Languages

Thanks to its adherence to Chrome standards, IronPDF supports the use of UTF-8 Encoding within PDF documents. This ensures that any characters used are correctly rendered, including any foreign languages used in the original content. All of it will be rendered correctly in the final PDF document.

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

const string html_with_utf_8 =
    @"<p>周態告応立待太記行神正用真最。音日独素円政進任見引際初携食。更火識将回興継時億断保媛全職。
    文造画念響竹都務済約記求生街東。天体無適立年保輪動元念足総地作靖権瀬内。
    失文意芸野画美暮実刊切心。感変動技実視高療試意写表重車棟性作家薄井。
    陸瓶右覧撃稿法真勤振局夘決。任堀記文市物第前兜純響限。囲石整成先尾未展退幹販山令手北結。</p>
    <p>
    أم يذكر النفط قبضتهم على, الصين وفنلندا ما حدى. تم لكل أملاً المنتصر,
    ٣٠ حدى مارد القوى. شرسة للسيطرة قامفي. حتى أم يطول المحيط,
    زهاء وحلفاؤها من فعل. لم قامت الجو الساحلية وتم, ويعزى واقتصار قبل كل.
    </p>
    <p>
    ภคันทลาพาธสตาร์เซฟตี้ แชมป์ มาร์เก็ตติ้งล้มเหลวโยเกิร์ต แลนด์บาบูนอึมครึม รุสโซ แบรนด์ไคลแม็กซ์ พิซซ่าโมเดลเสือโคร่ง ม็อบโซนรายชื่อ
    แอดมิชชั่น ด็อกเตอร์ พะเรอ มาร์คเจไดโมจิราสเบอร์รี เอนทรานซ์ออดิชั่นศิลปวัฒนธรรมเปราะบาง โมจิซีเรียสวอลนัตทริปลีเมอร์ ทิป วาไรตี้บิ๊กเมเปิล
    </p>";

var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.InputEncoding = System.Text.Encoding.UTF8;

var pdf = renderer.RenderHtmlAsPdf(html_with_utf_8);
pdf.SaveAs("Unicode.pdf");
Imports IronPdf

Private Const html_with_utf_8 As String = "<p>周態告応立待太記行神正用真最。音日独素円政進任見引際初携食。更火識将回興継時億断保媛全職。
    文造画念響竹都務済約記求生街東。天体無適立年保輪動元念足総地作靖権瀬内。
    失文意芸野画美暮実刊切心。感変動技実視高療試意写表重車棟性作家薄井。
    陸瓶右覧撃稿法真勤振局夘決。任堀記文市物第前兜純響限。囲石整成先尾未展退幹販山令手北結。</p>
    <p>
    أم يذكر النفط قبضتهم على, الصين وفنلندا ما حدى. تم لكل أملاً المنتصر,
    ٣٠ حدى مارد القوى. شرسة للسيطرة قامفي. حتى أم يطول المحيط,
    زهاء وحلفاؤها من فعل. لم قامت الجو الساحلية وتم, ويعزى واقتصار قبل كل.
    </p>
    <p>
    ภคันทลาพาธสตาร์เซฟตี้ แชมป์ มาร์เก็ตติ้งล้มเหลวโยเกิร์ต แลนด์บาบูนอึมครึม รุสโซ แบรนด์ไคลแม็กซ์ พิซซ่าโมเดลเสือโคร่ง ม็อบโซนรายชื่อ
    แอดมิชชั่น ด็อกเตอร์ พะเรอ มาร์คเจไดโมจิราสเบอร์รี เอนทรานซ์ออดิชั่นศิลปวัฒนธรรมเปราะบาง โมจิซีเรียสวอลนัตทริปลีเมอร์ ทิป วาไรตี้บิ๊กเมเปิล
    </p>"

Private renderer = New ChromePdfRenderer()
renderer.RenderingOptions.InputEncoding = System.Text.Encoding.UTF8

Dim pdf = renderer.RenderHtmlAsPdf(html_with_utf_8)
pdf.SaveAs("Unicode.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Base URLs & Asset Encoding

IronPDF allows you to set a Base URL, enabling relative paths in your HTML, such as images, CSS, or JavaScript, to load correctly when rendering to PDF. You can also embed assets with base64 encoding to keep everything self-contained and internet-free.

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

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

string baseUrl = @"C:\site\assets\";
string html = "<img src='icons/iron.png'>";

// Render HTML to PDF
PdfDocument pdf = renderer.RenderHtmlAsPdf(html, baseUrl);

// Export PDF
pdf.SaveAs("html-with-assets.pdf");
Imports IronPdf

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private baseUrl As String = "C:\site\assets\"
Private html As String = "<img src='icons/iron.png'>"

' Render HTML to PDF
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf(html, baseUrl)

' Export PDF
pdf.SaveAs("html-with-assets.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Render WebGL Sites

WebGL is a commonly used tool for creating interactive 3D graphics, but converting them into a static PDF can be a challenging task. With IronPDF, this process is made as seamless as possible, providing developers with a sense of ease and confidence in their ability to convert complex web assets into PDFs.

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

// Configure IronPdf settings
IronPdf.Installation.SingleProcess = true;
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Hardware;

ChromePdfRenderer renderer = new ChromePdfRenderer();

// Set delay before rendering
renderer.RenderingOptions.WaitFor.RenderDelay(5000);

// Render from URL
PdfDocument pdf = renderer.RenderUrlAsPdf("https://docs.mapbox.com/mapbox-gl-js/example/geojson-layer-in-slot/");

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

' Configure IronPdf settings
IronPdf.Installation.SingleProcess = True
IronPdf.Installation.ChromeGpuMode = IronPdf.Engines.Chrome.ChromeGpuModes.Hardware

Dim renderer As New ChromePdfRenderer()

' Set delay before rendering
renderer.RenderingOptions.WaitFor.RenderDelay(5000)

' Render from URL
Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://docs.mapbox.com/mapbox-gl-js/example/geojson-layer-in-slot/")

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

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Chrome PDF Rendering Engine

IronPDF utilizes the powerful Chromium engine, allowing users to create pixel-perfect PDFs with CSS and JavaScript. This creates a what-you-see-is-what-you-get scenario, giving you peace of mind and eliminating any doubts when it comes to converting them to PDFs. The use of this engine ensures high compatibility and performance in PDF rendering.

:path=/static-assets/pdf/content-code-examples/how-to/ironpdf-2021-chrome-rendering-engine-eap-pixel-perfect.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();

renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print;
renderer.RenderingOptions.PrintHtmlBackgrounds = false;
renderer.RenderingOptions.CreatePdfFormsFromHtml = false;

PdfDocument pdf = renderer.RenderUrlAsPdf("https://www.google.com/");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

renderer.RenderingOptions.CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print
renderer.RenderingOptions.PrintHtmlBackgrounds = False
renderer.RenderingOptions.CreatePdfFormsFromHtml = False

Dim pdf As PdfDocument = renderer.RenderUrlAsPdf("https://www.google.com/")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Performance and Compression

When working with large PDF files or generating big batches of PDFs, performance is key to a smooth process. This is where IronPDF stands out, with impressive performance speeds when working with PDFs of all sizes. IronPDF provides consistent, smooth-running performance for all your PDF tasks.

In this section, we'll take a closer look at some of the features and tools that IronPDF offers to ensure smooth performance, regardless of the tasks you need to run.

PDF Compression

Compressing images within a PDF is a convenient way to reduce the file size of a PDF document significantly. Larger PDF files often contain multiple images, which can dramatically inflate the overall size of the PDF file. By compressing these files, you can make them easier to share and store, saving you time and resources.

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

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page");

// Compress images in the PDF
pdf.CompressImages(40);

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

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderUrlAsPdf("https://en.wikipedia.org/wiki/Main_Page")

' Compress images in the PDF
pdf.CompressImages(40)

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

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Async & Multithreading

IronPDF supports asynchronous PDF generation using the RenderHtmlAsPdfAsync method. This powerful feature enables you to convert HTML to PDF without impacting your application's performance, ensuring consistent results. It's beneficial for handling multiple documents or integrating into responsive web APIs, giving you complete control over your application's performance.

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

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

string[] htmlStrings = {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"};

// Create an array to store the tasks for rendering
var renderingTasks = new Task<PdfDocument>[htmlStrings.Length];

for (int i = 0; i < htmlStrings.Length; i++)
{
    int index = i; // Capturing the loop variable
    renderingTasks[i] = Task.Run(async () =>
    {
        // Render HTML to PDF
        return await renderer.RenderHtmlAsPdfAsync(htmlStrings[index]);
    });
}

// Wait for all rendering tasks to complete
// await Task.WhenAll(renderingTasks);
Imports IronPdf
Imports System.Threading.Tasks

' Instantiate ChromePdfRenderer
Private renderer As New ChromePdfRenderer()

Private htmlStrings() As String = {"<h1>Html 1</h1>", "<h1>Html 2</h1>", "<h1>Html 3</h1>"}

' Create an array to store the tasks for rendering
Private renderingTasks = New Task(Of PdfDocument)(htmlStrings.Length - 1){}

For i As Integer = 0 To htmlStrings.Length - 1
	Dim index As Integer = i ' Capturing the loop variable
	renderingTasks(i) = Task.Run(Async Function()
		' Render HTML to PDF
		Return Await renderer.RenderHtmlAsPdfAsync(htmlStrings(index))
	End Function)
Next i

' Wait for all rendering tasks to complete
' await Task.WhenAll(renderingTasks);
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Custom Logging

IronPDF enables custom logging by allowing you to route log messages to your logger. By setting LoggingMode to LoggingModes.Custom and assigning your custom logger to CustomLogger, you can control how and where log messages are handled. This is useful for integrating IronPDF logs into your existing logging infrastructure.

:path=/static-assets/pdf/content-code-examples/how-to/custom-logging-custom-logging.cs
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom;
IronSoftware.Logger.CustomLogger = new CustomLoggerClass("logging");
IronSoftware.Logger.LoggingMode = IronSoftware.Logger.LoggingModes.Custom
IronSoftware.Logger.CustomLogger = New CustomLoggerClass("logging")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Flatten PDFs

The Flatten method in IronPDF is a powerful tool that allows you to make PDFs interactive and fillable widgets non-editable for various purposes. It flattens the PDF, preserving its visual layout while preventing any further editing, ensuring the integrity of your documents.

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

// Select the desired PDF File
PdfDocument pdf = PdfDocument.FromFile("before.pdf");

// Flatten the pdf
pdf.Flatten();

// Save as a new file
pdf.SaveAs("after_flatten.pdf");
Imports IronPdf

' Select the desired PDF File
Private pdf As PdfDocument = PdfDocument.FromFile("before.pdf")

' Flatten the pdf
pdf.Flatten()

' Save as a new file
pdf.SaveAs("after_flatten.pdf")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

PDF Viewing and Printing

Print to Physical Printer

This functionality allows users to generate PDF files instead of sending documents directly to a printer. When the Print is used, the system creates a PDF file that is saved on the local machine. You can also specify a different printer by providing the printer name to the Print method.

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

ChromePdfRenderer renderer = new ChromePdfRenderer();

PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>");

// Send the document to "Microsoft Print to PDF" printer
pdf.Print("Microsoft Print to PDF");
Imports IronPdf

Private renderer As New ChromePdfRenderer()

Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>Test printing</h1>")

' Send the document to "Microsoft Print to PDF" printer
pdf.Print("Microsoft Print to PDF")
$vbLabelText   $csharpLabel

For a more detailed explanation of this code snippet and to explore its additional functionality, please refer to our comprehensive how-to guide.

Conclusion

IronPDF empowers .NET developers with the flexibility to create professional, high-quality PDFs. It seamlessly integrates modern web assets and delivers top-tier performance. Whether you're rendering dynamic HTML content, embedding custom fonts and images, or optimizing large-scale PDF generation through compression and multithreading, IronPDF offers the flexibility and power you need—all without external dependencies.

By combining rich asset support with performance-focused tools like async rendering and custom logging, IronPDF ensures your applications remain fast, scalable, and visually consistent. Whether you're building a simple report or an enterprise-level document automation system, IronPDF makes it easy to deliver beautiful and efficient PDF documents every time.

Now that you've seen what IronPDF can do, it's time to start building smarter, faster PDF workflows in your .NET projects.

Preguntas Frecuentes

¿Cómo puedo optimizar el rendimiento de PDF usando IronPDF?

Para optimizar el rendimiento de PDF usando IronPDF, puedes aprovechar sus funciones de optimización integradas, como comprimir imágenes, reducir el tamaño del archivo, y optimizar las fuentes. Esto asegura que tus PDFs carguen más rápido y se desempeñen mejor.

¿Qué son los activos web en el contexto de la generación de PDF?

Los activos web se refieren a los recursos externos como imágenes, hojas de estilo y scripts que se pueden incluir en tus documentos PDF. Usando IronPDF, puedes incrustar fácilmente estos activos para mejorar los aspectos visuales y funcionales de tus PDFs.

¿Cómo agrego imágenes a un PDF usando IronPDF?

Puedes agregar imágenes a un PDF usando IronPDF ya sea incrustándolas directamente en el código fuente HTML o referenciándolas como URLs externas. IronPDF soporta varios formatos de imagen, permitiendo un contenido visual rico en tus PDFs.

¿Puede IronPDF ayudar a reducir el tamaño de mis archivos PDF?

Sí, IronPDF puede ayudar a reducir el tamaño de tus archivos PDF optimizando imágenes, eliminando metadatos innecesarios, y comprimiendo el contenido cuando sea posible. Esto resulta en documentos PDF más pequeños y manejables.

¿Qué características ofrece IronPDF para optimizar las fuentes en un PDF?

IronPDF proporciona características para subconfigurar y comprimir fuentes, asegurando que solo los datos de fuente necesarios sean incluidos en el PDF. Esto reduce el tamaño del archivo y mejora los tiempos de carga sin comprometer la calidad del texto.

¿Es posible incluir estilos CSS en PDFs generados con IronPDF?

Sí, IronPDF te permite incluir estilos CSS en tus documentos PDF. Puedes incrustar CSS directamente en tu HTML o enlazar a hojas de estilo externas para asegurar que tus PDFs mantengan una apariencia coherente y profesional.

¿Cómo maneja IronPDF los recursos externos en un PDF?

IronPDF puede integrar recursos externos como imágenes y hojas de estilo incrustándolos directamente o referenciando sus URLs. Esto permite la creación de PDFs dinámicos y visualmente atractivos que incorporan una variedad de activos web.

¿Cuáles son los beneficios de optimizar PDFs con IronPDF?

Optimizar PDFs con IronPDF ofrece varios beneficios, incluyendo tiempos de carga más rápidos, tamaños de archivo reducidos, y un mejor rendimiento del documento. Los PDFs optimizados también consumen menos ancho de banda cuando se comparten o descargan.

¿Cómo puedo asegurarme de que mi PDF se vea consistente en diferentes dispositivos usando IronPDF?

Para asegurar consistencia entre dispositivos, utiliza el soporte de IronPDF para consultas de medios y técnicas de diseño responsivo dentro de tu HTML y CSS. Esto permite que el PDF adapte su diseño según el entorno de visualización.

.NET 10 está por llegar: ¿es compatible con IronPDF y qué beneficios aporta?

Sí: IronPDF es totalmente compatible con .NET 10.

Kye Stuart
Escritor Técnico

Kye Stuart fusiona la pasión por la codificación y la habilidad para escribir en Iron Software. Educado en Yoobee College en despliegue de software, ahora transforma conceptos tecnológicos complejos en contenido educativo claro. Kye valora el aprendizaje continuo y acepta nuevos desafíos tecnológicos.

<...
Leer más
¿Listo para empezar?
Nuget Descargas 16,133,208 | Versión: 2025.11 recién lanzado