Saltar al pie de página
USANDO IRONPDF

API de PDF en C# (Ejemplo de Código Tutorial)

1. Introduction

Adobe's Portable Document Format (PDF) is essential for various operations in many companies, including generating documents and invoices. Developers also use it to meet client requirements. Libraries have simplified the process of creating PDFs. When choosing a library, consider aspects such as build, read, and conversion capabilities.

2. IronPDF Features

IronPDF is a robust PDF converter and API library that allows developers to generate, read, and manipulate PDF documents. It uses the Chrome engine to convert HTML to PDF and supports a variety of web components and .NET applications. It enables the creation of visually appealing PDFs using HTML5, JavaScript, CSS, and images, and includes a powerful HTML-to-PDF translator and an independent PDF conversion engine.

3. Create PDF Documents from URLs

With the assistance of the IronPDF API library, generating PDF files becomes very easy by creating an HTML file from a URL and converting it to a PDF file using the built-in Chrome browser in IronPDF.

The methods listed below make it simple to create PDF documents with just a few lines of code:

// Instantiate the ChromePdfRenderer object from IronPdf
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer(); 

// Render the contents of a URL as a PDF document
var pdf = renderer.RenderUrlAsPdf("https://www.google.co.in/");

// Save the rendered PDF document to a specified file path
pdf.SaveAs("result.pdf");
// Instantiate the ChromePdfRenderer object from IronPdf
IronPdf.ChromePdfRenderer renderer = new IronPdf.ChromePdfRenderer(); 

// Render the contents of a URL as a PDF document
var pdf = renderer.RenderUrlAsPdf("https://www.google.co.in/");

// Save the rendered PDF document to a specified file path
pdf.SaveAs("result.pdf");
' Instantiate the ChromePdfRenderer object from IronPdf
Dim renderer As New IronPdf.ChromePdfRenderer()

' Render the contents of a URL as a PDF document
Dim pdf = renderer.RenderUrlAsPdf("https://www.google.co.in/")

' Save the rendered PDF document to a specified file path
pdf.SaveAs("result.pdf")
$vbLabelText   $csharpLabel

According to the information above, the RenderUrlAsPdf method can be used to convert the link into a document by providing the link and the save location.

PDF API C# (Code Example Tutorial), Figure 1: The PDF file generated from a URL The PDF file generated from a URL

4. Create a PDF from HTML Strings

The IronPDF API library makes it easy to convert HTML strings into PDF files. Below is an example code for converting HTML strings into documents, and it allows the translation of any HTML tag into PDF files.

// Use the ChromePdfRenderer to convert an HTML string to a PDF
IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Hello world!!").SaveAs("result.pdf");
// Use the ChromePdfRenderer to convert an HTML string to a PDF
IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Hello world!!").SaveAs("result.pdf");
' Use the ChromePdfRenderer to convert an HTML string to a PDF
IronPdf.ChromePdfRenderer().RenderHtmlAsPdf("Hello world!!").SaveAs("result.pdf")
$vbLabelText   $csharpLabel

This example code demonstrates how to convert an unlimited HTML text using RenderHtmlAsPdf, then save the document using the SaveAs method and the whole process is completed in just a matter of seconds.

PDF API C# (Code Example Tutorial), Figure 2: A PDF file generated from an HTML string A PDF file generated from an HTML string

5. Reading PDF Documents

With the help of the IronPDF API library, it is possible to read and extract data from existing PDF documents. The code below shows an example of how to do this:

// Load an existing PDF file into a PdfDocument object
var pdfDocument = IronPdf.PdfDocument.FromFile("result.pdf");

// Extract all text from the PDF document into a string
string AllText = pdfDocument.ExtractAllText();
// Load an existing PDF file into a PdfDocument object
var pdfDocument = IronPdf.PdfDocument.FromFile("result.pdf");

// Extract all text from the PDF document into a string
string AllText = pdfDocument.ExtractAllText();
' Load an existing PDF file into a PdfDocument object
Dim pdfDocument = IronPdf.PdfDocument.FromFile("result.pdf")

' Extract all text from the PDF document into a string
Dim AllText As String = pdfDocument.ExtractAllText()
$vbLabelText   $csharpLabel

In this code, the FromFile function is used to read the PDF from an existing file and convert it into a PdfDocument object. This object can be used to access the text and images present on the PDF pages. The ExtractAllText method can be used to create a string containing every word on the PDF pages.

For more information on how to use the IronPDF API library, refer to the code tutorials and documentation.

6. Conclusion

The IronPDF library provides a free license for development, and different licenses are available for purchase for use in a production environment based on the developer's needs. The Lite package has a starting price of $799 and does not require any ongoing fees. The licenses offer redistribution options for SaaS and OEM and come with a permanent license, a 30-day money-back guarantee, and a year of product support and updates. They are suitable for development, staging, and production and require a one-time purchase. Moreover, IronPDF provides additional complimentary time-limited licenses. IronPDF also offers free licenses for redistribution coverage.

For more information on IronPDF's complete pricing and licensing details, please visit the IronPDF licensing details page.

Preguntas Frecuentes

¿Cómo puedo convertir HTML a PDF en C#?

Puede utilizar el método RenderHtmlAsPdf de IronPDF para convertir cadenas HTML en PDFs. También puede convertir archivos HTML en PDFs utilizando el método RenderHtmlFileAsPdf.

¿Cuáles son las principales características de una biblioteca PDF?

IronPDF permite a los desarrolladores generar, leer y manipular documentos PDF. Admite la conversión de HTML, archivos de imagen, páginas ASPX y vistas Razor/MVC en PDFs. Además, ofrece herramientas para crear PDFs interactivos, editar formularios, extraer texto e imágenes, y más.

¿Cómo creo un PDF desde una URL usando C#?

Puedes crear un PDF desde una URL usando IronPDF instanciando el objeto ChromePdfRenderer y utilizando su método RenderUrlAsPdf. Esto permite que el contenido de una URL se renderice como un documento PDF.

¿Puedo convertir archivos CSS a PDF usando una biblioteca PDF?

Sí, IronPDF admite la conversión de archivos CSS en documentos PDF. Puedes incluir estilos CSS al renderizar HTML para garantizar que el resultado en PDF coincida con el diseño deseado.

¿Cómo puedo extraer texto de un PDF en C#?

Para extraer texto de un PDF en C#, carga el PDF en un objeto PdfDocument usando el método FromFile, y luego usa el método ExtractAllText para recuperar datos de texto del documento.

¿Qué opciones de licencia están disponibles para las bibliotecas PDF?

IronPDF ofrece una licencia gratuita para desarrollo y varias licencias de pago para uso en producción, incluidas opciones para redistribución SaaS y OEM. Estas licencias vienen con una compra única, licencia permanente, una garantía de devolución de dinero de 30 días y un año de soporte y actualizaciones de producto.

¿Puedo manejar PDFs protegidos con contraseña con una biblioteca PDF?

Sí, IronPDF puede acceder a archivos PDF protegidos con contraseña solicitando el nombre de usuario y la contraseña, permitiéndote leer y editar estos documentos.

¿Una biblioteca PDF admite la creación de documentos PDF interactivos?

Sí, IronPDF admite la creación de documentos PDF interactivos, incluida la edición de formularios, adición de marcadores, marcas de agua y encabezados y pies de página personalizados.

¿Qué formatos de entrada son compatibles para la conversión a PDF?

IronPDF admite la conversión de archivos de imagen, documentos HTML5, páginas ASPX, vistas Razor/MVC y archivos CSS en documentos PDF.

¿Cómo puedo crear PDFs a partir de URLs usando una API?

Usando la API de IronPDF, puedes crear fácilmente PDFs a partir de URLs utilizando el navegador Chrome integrado para renderizar el contenido de una URL como un documento PDF con solo unas pocas líneas de código.

¿IronPDF es compatible con .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10. Admite proyectos .NET 10 junto con .NET 9, 8, 7, 6, Core, Standard y Framework, y funciona en distintas plataformas (Windows, Linux, macOS) con el mismo motor de renderizado y conjunto de herramientas de Chrome.

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