Cómo convertir HTML a PDF con CSS responsive usando C#

How to use CSS with HTML

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

The CSS 'screen' media type is primarily intended for display on computer screens and similar devices. When styles are defined for the 'screen' media type, they affect how web content is presented on screens, emphasizing visual design and interactivity.

In contrast, the CSS 'print' media type is designed for printing. It determines how the web page will appear when printed, with a focus on optimizing content for the printed page. This optimization may include adjusting font sizes, margins, and removing or hiding elements that are not relevant or necessary when printed.

Quickstart: Generate PDFs with Responsive HTML and CSS

Convert your HTML with responsive CSS to a polished PDF using IronPDF effortlessly. With just a few lines of code, developers can ensure their PDFs render perfectly across devices, maintaining the integrity of both screen and print styles. This quick guide demonstrates how to use IronPDF to achieve professional PDF output from your existing HTML content, streamlining the process for swift and accurate results.

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 { RenderingOptions = { CssMediaType = IronPdf.Rendering.PdfCssMediaType.Print } }
        .RenderUrlAsPdf("https://example.com")
        .SaveAs("responsive.pdf");
  3. Deploy to test on your live environment

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


Screen & Print CSS Types (CSS3)

IronPDF generates PDFs from HTML in C# and can effortlessly render a screen stylesheet to a PDF by default. This is convenient because print stylesheets are often less well-documented, used, or developed compared to their screen counterparts.

CSS3 allows certain CSS styles to be rendered exclusively in printed documents, while others are intended for web browsers. IronPDF can be programmed to work with either.

Create and apply a print stylesheet to your HTML: Learn how to create and apply a perfect print stylesheet..

It is very hard to say which CSS media type is better since each type targets different use cases. It is worth trying each one through trial and error to see which is suitable for your requirement.

Example of Print 1 Example of Screen 1


Repeat Table Headers

When dealing with HTML tables that span multiple pages, set the CssMediaType property to PdfCssMediaType.Print. This ensures that the table header is repeated at the top of each extended page. In contrast, PdfCssMediaType.Screen instructs Chrome to print the headers only once.

To make sure Chrome detects the table header, it should be enclosed in a <thead> tag. Let's render the 'tableHeader.html example of repeating table headers' HTML file to PDF to see the effect.

: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

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF con diseño adaptable?

Puedes convertir HTML a PDF con diseño adaptable usando IronPDF descargando primero la biblioteca C# de IronPDF. Luego, prepara tu archivo HTML, especifica el tipo de medio CSS apropiado y configura las dimensiones del viewport para asegurar que el PDF sea adaptable en distintos dispositivos.

¿Cuál es la diferencia entre los tipos de medios CSS 'screen' y 'print'?

El tipo de medio CSS 'screen' se usa para mostrar contenido en pantallas digitales, centrándose en el diseño visual y la interactividad. En contraste, el tipo de medio 'print' optimiza el contenido para materiales impresos ajustando elementos como tamaños de fuente y márgenes, haciéndolo adecuado para impresiones físicas.

¿Cómo aseguras que los encabezados de tabla se repitan en cada página de un PDF?

Para asegurar que los encabezados de tabla se repitan en cada página de un PDF, configura la propiedad CssMediaType a PdfCssMediaType.Print y encierra el encabezado de la tabla en una etiqueta <thead>. Esto asegura una representación consistente del encabezado en múltiples páginas.

¿Puede IronPDF manejar tanto hojas de estilo para pantalla como para impresión?

Sí, IronPDF puede manejar tanto hojas de estilo para pantalla como para impresión. Permite renderizar PDFs a partir de HTML con cualquiera de los tipos de medio, asegurando flexibilidad dependiendo de si la salida está destinada para pantallas digitales o impresión.

¿Cuáles son los beneficios de usar una hoja de estilo para impresión al convertir HTML a PDF?

Una hoja de estilo para impresión es beneficiosa al convertir HTML a PDF ya que asegura que el contenido esté optimizado para la impresión. Esto incluye ajustes en los tamaños de fuente y márgenes, asegurando que el PDF esté correctamente formateado para impresiones físicas.

¿Cómo implementas CSS adaptable en un PDF usando una biblioteca C#?

Para implementar CSS adaptable en un PDF usando IronPDF, descarga la biblioteca C# de IronPDF, prepara tu contenido HTML, especifica el tipo de medio CSS deseado y ajusta las dimensiones del viewport para asegurar que el PDF se adapte a varios dispositivos.

¿Por qué es importante usar el tipo de medio CSS correcto para PDFs?

Usar el tipo de medio CSS correcto es importante para PDFs porque determina cómo se renderiza el contenido. El tipo de medio 'screen' es adecuado para pantallas digitales, mientras que el tipo de medio 'print' asegura que el contenido esté optimizado para papel, afectando elementos como el diseño y la legibilidad.

¿IronPDF es compatible con .NET 10? ¿Hay ventajas en utilizar la última versión?

Sí, IronPDF es compatible con .NET 10. Dado que .NET 10 es una versión con soporte a largo plazo (LTS) con importantes mejoras de rendimiento, tiempo de ejecución y SDK (incluyendo mejor integración JIT, aceleración de hardware y API HTTP y de serialización mejoradas), usar .NET 10 con IronPDF permite una generación de PDF más rápida y eficiente, además de estabilidad a largo plazo. ([devblogs.microsoft.com](https://devblogs.microsoft.com/dotnet/announcing-dotnet-10/?utm_source=openai))

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado