Saltar al contenido

ITextSharp HTML a PDF?

Te sugerimos que revises esta solución en un ambiente controlado antes de enviarlo a producción, un saludo.

Solución:

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. Lo más probable es que el documento necesite algunos ajustes 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;

después de investigar un poco, encontré una buena manera de lograr lo que necesito con ITextSharp.

Aquí hay un código de muestra si ayudará 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 htmlarraylist = HTMLWorker.ParseToList(new StringReader(htmlText), null);
        for (int k = 0; k < htmlarraylist.Count; k++)
        
            document.Add((IElement)htmlarraylist[k]);
        

        document.Close();
    
    catch
    
    

Esto es lo que pude obtener trabajando en la versión 5.4.2 (desde la instalación de nuget) para devolver una respuesta en pdf desde un controlador asp.net mvc. Podría modificarse para usar 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 mirado porque mi uso no lo requiere)

Utiliza XmlWorkerHelper de iTextSharp, por lo que el hmtl entrante debe ser XHTML válido, por lo que es posible que deba realizar algunas correcciones según su 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 = @"
                 
                 
                    
                        Minimal XHTML 1.0 Document with W3C DTD
                    
                  
                    " + 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");
            
        
    

Te invitamos a añadir valor a nuestra información contribuyendo tu veteranía en los comentarios.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *