Generar un documento en PDF desde asp.net

Wiki: Los usuarios registrados de DesarrolloWeb.com pueden modificar los contenidos y realizar aportaciones en esta sección.
  • Dar una respuesta
Da una respuesta
Votos útiles (1) inútiles (0)
Discusión creada por ddoganieri el 16/12/2011

Categoría wiki: ASP

Cómo generar un documento en PDF desde asp.net

Últimas respuestas enviadas
Hola a todos! Soy nueva en esto de postear temas en la web sobre mis trabajos, así que espero que les sea de ayuda.

Para este tema, generaremos un documento en PDF desde una aplicación WEB desarrollada en asp.net (sharp) con Visual Studios 2010. Consistirá en un campo de texto y un botón para generar el documento. El PDF generado consistirá en un título, un párrafo en rojo alineado a la derecha y en cursiva y otro párrafo en el que concatenaremos el textbox.

Lo primero que tenemos que hacer es descargar la librería iTextSharp y agregar la referencia a su proyecto. una vez que agreguemos la referencia, empezaremos a programar.

Una vez que tengamos un campo de texto de id="txt" y un botón de id="boton", le agregamos un OnClick="boton_Click" que hará lo siguiente:


protected void boton_Click(object sender, EventArgs e)
        {          
            StringWriter sw = new StringWriter();
            string html = sw.ToString();
            
            Document Doc = new Document();
            
            PdfWriter.GetInstance
            (Doc, new FileStream(Environment.GetFolderPath
            (Environment.SpecialFolder.Desktop)
            + "\\Prueba.pdf", FileMode.Create));
            Doc.Open();

            Chunk c = new Chunk
            ("Prueba de un Documento en PDF \n", FontFactory.GetFont("Verdana", 15));
            
            Paragraph p = new Paragraph();
            p.Alignment = Element.ALIGN_CENTER;
            p.Add(c);

            BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
            Font times = new Font(bfTimes, 12, Font.ITALIC, Color.RED);
            Font times2 = new Font(bfTimes, 12, Font.NORMAL, Color.BLACK);

            Chunk chunk1 = new Chunk
            ("\nEste es un parrafo (p1) alineado a la derecha, con letra cursiva y de color rojo. \n\n", times);
            Paragraph p1 = new Paragraph();
            
            p1.Alignment = Element.ALIGN_RIGHT;
            p1.Add(chunk1);

            Chunk chunk2 = new Chunk
            ("Este es un parrafo (p2) con letra normal, color negro, en el que estamos concatenando este texto un texto extraido de un textbox, que dice '" + txt.Text.ToString() + "'", times2);
            Paragraph p2 = new Paragraph();
            
            p2.Alignment = Element.ALIGN_JUSTIFIED;
            p2.Add(chunk2);

            Doc.Add(p);
            Doc.Add(p1);
            Doc.Add(p2);

            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(new StringReader(html));
            HtmlParser.Parse(Doc, xmlReader);

            Doc.Close();

            string Path = Environment.GetFolderPath
            (Environment.SpecialFolder.Desktop)
            + "\\Prueba.pdf";


            ShowPdf(Path);
        }



Como verán, se llama a un método "ShowPdf" que recibe el atributo "(Path)". Este método contendrá lo siguiente:


private void ShowPdf(string strS)
        {
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AddHeader
            ("Content-Disposition", "attachment; filename=" + strS);
            Response.TransmitFile(strS);
            Response.End();
            //Response.WriteFile(strS);
            Response.Flush();
            Response.Clear();

        }



Y por último, las librerías a utilizar son las siguientes:


using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualBasic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Text;
using System.Collections;
using System.Data;
using System.Configuration;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Net;
using System.Data.SqlClient;


De repente alguna de estas librerias no les sean útiles a ustedes, pero en mi caso sí porque tengo más código en el mismo documento que no es relevante para este tema y que necesita de todas esas librerias.

Espero que esto les haya servido de ayuda. See ya!
Categoría relacionada
+ ASP
Donaciones
Si piensas que te hemos ayudado y merecemos tu apoyo económico...