Este artículo explica cómo convertir una URL a PDF con C#. Puedes configurar el entorno, obtener una lista de pasos y un código de muestra para transformar la URL a PDF con C# siguiendo las instrucciones aquí. También se comparten configuraciones personalizadas para la página PDF de salida para crear la salida deseada.
Pasos para convertir URL en PDF usando C#
- Configurar el entorno para utilizar Aspose.PDF for .NET para convertir URL a PDF
- Defina la URL para la conversión a PDF y HtmlLoadOptions para configurar la página PDF de salida
- Crea el objeto HttpClient para realizar la solicitud HTTP
- Envíe una solicitud Get a la URL y espere la respuesta
- Asegúrese de que la solicitud sea exitosa y obtenga el contenido de la respuesta como una secuencia
- Crea el documento PDF desde la secuencia y colócalo en el disco.
Estos pasos describen el proceso para convertir una página web a PDF con C#. Defina la configuración de la página PDF de salida, cree una instancia de la clase HttpClient, envíe una solicitud Get a la URL, obtenga el flujo de respuesta y páselo al objeto Document con la configuración de la página. Por último, guarde el PDF de salida generado a partir del contenido de la URL en el disco.
Código para convertir enlace URL a PDF usando C#
// Importing required namespaces | |
using System; | |
using System.IO; | |
using System.Net.Http; | |
using Aspose.Pdf; | |
// Defining a namespace for the project | |
namespace HtmlToPdfConverter | |
{ | |
// Main class of the program | |
class ConverterApp | |
{ | |
// Entry point of the program | |
static void Main(string[] args) | |
{ | |
// Initialize and apply Aspose.PDF license | |
License pdfLicense = new License(); | |
pdfLicense.SetLicense("Aspose_License.lic"); | |
// Convert an online HTML page to PDF | |
GeneratePdfFromWebPage(); | |
} | |
// Method to fetch and convert an HTML webpage to a PDF document | |
private static void GeneratePdfFromWebPage() | |
{ | |
// Define the webpage URL to be converted | |
const string webpageUrl = "https://docs.aspose.com/"; | |
// Configure PDF page settings for conversion | |
var pdfOptions = new HtmlLoadOptions(webpageUrl) | |
{ | |
PageInfo = | |
{ | |
Width = 1200, // Setting custom page width | |
Height = 850, // Setting custom page height | |
IsLandscape = false // Keeping portrait orientation | |
} | |
}; | |
// Fetch the webpage content and create a PDF document | |
using (var pdfDocument = new Document(FetchWebContentAsStream(webpageUrl), pdfOptions)) | |
{ | |
// Save the generated PDF file | |
pdfDocument.Save("Converted_WebPage.pdf"); | |
} | |
} | |
// Method to retrieve the content of a webpage as a stream | |
static Stream FetchWebContentAsStream(string webpageUrl) | |
{ | |
// Initialize HTTP client to make web requests | |
HttpClient httpClient = new HttpClient(); | |
// Send a GET request and retrieve the response | |
HttpResponseMessage webResponse = httpClient.GetAsync(webpageUrl, HttpCompletionOption.ResponseHeadersRead).Result; | |
// Ensure the response was successful | |
webResponse.EnsureSuccessStatusCode(); | |
// Return the webpage content as a stream | |
return webResponse.Content.ReadAsStreamAsync().Result; | |
} | |
} | |
} |
Este código ha demostrado cómo transformar un enlace de una página web en un PDF mediante C#. Puede utilizar la clase HtmlLoadOptions para aplicar más configuraciones, como un indicador para incrustar fuentes, establecer la codificación de entrada, la opción de diseño de página, los márgenes de página, etc. Puede configurar una devolución de llamada para gestionar advertencias mediante WarningHandler.
Este tutorial nos ha guiado a cambiar un enlace a un documento PDF usando C#. Para agregar hipervínculos en un archivo PDF, consulte el artículo sobre Cómo agregar un hipervínculo en un PDF usando C#.