descargar .net itextsharp html-to-pdf

.net - descargar - ITextSharp HTML a PDF?



itextsharp documentation (8)

Me gustaría saber si ITextSharp tiene la capacidad de convertir HTML a PDF. Todo lo que convertiré será texto sin formato, pero lamentablemente hay muy poca o ninguna documentación sobre ITextSharp, por lo que no puedo determinar si esa será una solución viable para mí.

Si no puede hacerlo, ¿alguien puede indicarme algunas buenas librerías .net que pueden tomar un documento HTML sencillo y convertirlo a un pdf?

tia.


Después de hacer algunas excavaciones encontré una buena manera de lograr lo que necesito con ITextSharp.

Aquí hay un código de muestra si ayuda a alguien más en el futuro:

protected void Page_Load(object sender, EventArgs e) { Document document = new Document(); try { PdfWriter.GetInstance(document, new FileStream("c://my.pdf", FileMode.Create)); document.Open(); WebClient wc = new WebClient(); string htmlText = wc.DownloadString("http://localhost:59500/my.html"); Response.Write(htmlText); List<IElement> htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null); for (int k = 0; k < htmlarraylist.Count; k++) { document.Add((IElement)htmlarraylist[k]); } document.Close(); } catch { } }


El código anterior ciertamente ayudará a convertir HTML a PDF, pero fallará si el código HTML tiene etiquetas IMG con rutas relativas. La biblioteca iTextSharp no convierte automáticamente las rutas relativas a las absolutas.

Probé el código anterior y agregué el código para encargarme de las etiquetas IMG.

Puede encontrar el código aquí para su referencia: http://www.am22tech.com/html-to-pdf/


Esto es lo que pude hacer trabajando en la versión 5.4.2 (de la instalación nuget) para devolver una respuesta en pdf desde un controlador asp.net mvc. Se podría modificar el uso de FileStream en lugar de MemoryStream para la salida, si eso es lo que se necesita.

Lo publico aquí porque es un ejemplo completo del uso actual de iTextSharp para la conversión html -> pdf (sin tener en cuenta las imágenes, no lo he visto porque mi uso no lo requiere)

Utiliza el XmlWorkerHelper de iTextSharp, por lo que el hmtl entrante debe ser XHTML válido, por lo que es posible que tengas que hacer algunas correcciones dependiendo de tu entrada.

using iTextSharp.text.pdf; using iTextSharp.tool.xml; using System.IO; using System.Web.Mvc; namespace Sample.Web.Controllers { public class PdfConverterController : Controller { [ValidateInput(false)] [HttpPost] public ActionResult HtmlToPdf(string html) { html = @"<?xml version=""1.0"" encoding=""UTF-8""?> <!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Strict//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd""> <html xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en""> <head> <title>Minimal XHTML 1.0 Document with W3C DTD</title> </head> <body> " + html + "</body></html>"; var bytes = System.Text.Encoding.UTF8.GetBytes(html); using (var input = new MemoryStream(bytes)) { var output = new MemoryStream(); // this MemoryStream is closed by FileStreamResult var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER, 50, 50, 50, 50); var writer = PdfWriter.GetInstance(document, output); writer.CloseStream = false; document.Open(); var xmlWorker = XMLWorkerHelper.GetInstance(); xmlWorker.ParseXHtml(writer, document, input, null); document.Close(); output.Position = 0; return new FileStreamResult(output, "application/pdf"); } } } }


Me encontré con la misma pregunta hace unas semanas y este es el resultado de lo que encontré. Este método realiza un volcado rápido de HTML a un PDF. Es muy probable que el documento necesite algún ajuste de formato.

private MemoryStream createPDF(string html) { MemoryStream msOutput = new MemoryStream(); TextReader reader = new StringReader(html); // step 1: creation of a document-object Document document = new Document(PageSize.A4, 30, 30, 30, 30); // step 2: // we create a writer that listens to the document // and directs a XML-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, msOutput); // step 3: we create a worker parse the document HTMLWorker worker = new HTMLWorker(document); // step 4: we open document and start the worker on the document document.Open(); worker.StartDocument(); // step 5: parse the html into the document worker.Parse(reader); // step 6: close the document and the worker worker.EndDocument(); worker.Close(); document.Close(); return msOutput; }


Prefiero usar otra biblioteca llamada Pechkin porque es capaz de convertir HTML no trivial (que también tiene clases de CSS). Esto es posible porque esta biblioteca usa el motor de diseño WebKit que también es usado por navegadores como Chrome y Safari.

Detallé en mi blog mi experiencia con Pechkin: http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/


Quisiera saber la respuesta de mightymada si tuviera la reputación. Acabo de implementar una solución asp.net HTML to PDF usando Pechkin. los resultados son maravillosos

Hay un paquete nuget para Pechkin, pero como menciona el póster anterior en su blog ( http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - Espero que no le importe me reposicionó), hay una pérdida de memoria que se ha solucionado en esta rama:

https://github.com/tuespetre/Pechkin

El blog anterior tiene instrucciones específicas sobre cómo incluir este paquete (es un dll de 32 bits y requiere .net4). aquí está mi código El HTML entrante se ensambla a través del paquete HTML Agility (estoy automatizando generaciones de facturas):

public static byte[] PechkinPdf(string html) { //Transform the HTML into PDF var pechkin = Factory.Create(new GlobalConfig()); var pdf = pechkin.Convert(new ObjectConfig() .SetLoadImages(true).SetZoomFactor(1.5) .SetPrintBackground(true) .SetScreenMediaType(true) .SetCreateExternalLinks(true), html); //Return the PDF file return pdf; }

nuevamente, gracias mightymada, tu respuesta es fantástica.


Si está convirtiendo html a pdf en el lado del servidor html, puede usar Rotativa:

Install-Package Rotativa

Esto está basado en wkhtmltopdf pero tiene mejor soporte css que iTextSharp y es muy simple de integrar con MVC (que se usa principalmente) ya que simplemente puede devolver la vista como pdf:

public ActionResult GetPdf() { //... return new ViewAsPdf(model);// and you are done! }


Tiene la capacidad de convertir archivos HTML a PDF.

El espacio de nombre requerido para las conversiones es:

using iTextSharp.text; using iTextSharp.text.pdf;

y para el archivo de conversión y descarga:

// Create a byte array that will eventually hold our final PDF Byte[] bytes; // Boilerplate iTextSharp setup here // Create a stream that we can write to, in this case a MemoryStream using (var ms = new MemoryStream()) { // Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF using (var doc = new Document()) { // Create a writer that''s bound to our PDF abstraction and our stream using (var writer = PdfWriter.GetInstance(doc, ms)) { // Open the document for writing doc.Open(); string finalHtml = string.Empty; // Read your html by database or file here and store it into finalHtml e.g. a string // XMLWorker also reads from a TextReader and not directly from a string using (var srHtml = new StringReader(finalHtml)) { // Parse the HTML iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml); } doc.Close(); } } // After all of the PDF "stuff" above is done and closed but **before** we // close the MemoryStream, grab all of the active bytes from the stream bytes = ms.ToArray(); } // Clear the response Response.Clear(); MemoryStream mstream = new MemoryStream(bytes); // Define response content type Response.ContentType = "application/pdf"; // Give the name of file of pdf and add in to header Response.AddHeader("content-disposition", "attachment;filename=invoice.pdf"); Response.Buffer = true; mstream.WriteTo(Response.OutputStream); Response.End();