Cómo exportar una página web con ASP.NET a PDF

En mi trabajo muchas ocasiones he tenido la necesidad de exportar una página web a PDF. Por eso en este artículo voy a explicar cómo exportar una página web a PDF con una imagen en ASP.Net, VB. En seguida te muestro el ejemplo y en la parte final de este artículo podrás descargar el ejemplo completo:


Puedes revisar este otro artículo donde con solo 4 líneas de código puedes exportar una página web a PDF con solo pasar la URL.

  1. Crea la página default.aspx y agregas el siguiente código:

 

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" EnableEventValidation="false" Inherits="ConvertirPDF_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:Image ID="Image1" runat="server" ImageUrl="http://www.developerji.com/App_Themes/Principal/Images/logo.png" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <br />
        <asp:Button ID="btnExportasPDF" runat="server" Text="Exportar Página a PDF"
            OnClick="btnExportasPDF_Click" />
        <br />
        <br />
        Más ejemplos en: <a href="http://www.developerji.com/">http://www.developerji.com/</a>
        <br />
    </div>
    </form>
</body>
</html>
  1. Agrega el siguiente código a la página default.aspx.vb
Imports System
Imports System.Configuration
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.HtmlControls
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Xml.Linq

' include iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.Text
Imports System.IO

Partial Class ConvertirPDF_Default
    Inherits System.Web.UI.Page
    Private dt As New DataTable()


    Protected Sub btnExportasPDF_Click(sender As Object, e As EventArgs) Handles btnExportasPDF.Click
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        Me.Page.RenderControl(hw)
        Dim sr As New StringReader(sw.ToString())
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
        Dim htmlparser As New HTMLWorker(pdfDoc)
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()
        htmlparser.Parse(sr)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.[End]()
    End Sub

    Protected Sub Page_Load1(sender As Object, e As EventArgs) Handles Me.Load
        dt.Columns.Add("ID", GetType(Integer))
        dt.Columns.Add("Nombre", GetType(String))
        dt.Columns.Add("Dirección", GetType(String))
        dt.Columns.Add("Fecha", GetType(DateTime))

        '
        ' Here we add five DataRows.
        '
        dt.Rows.Add(25, "José", "México", DateTime.Now)
        dt.Rows.Add(50, "DeveloperJI", "Distrito Federal", DateTime.Now)
        dt.Rows.Add(10, "Juan", "Morelos", DateTime.Now)
        dt.Rows.Add(21, "Fernanda", "Aguascalientes", DateTime.Now)
        dt.Rows.Add(100, "Alejandra", "Hidalgo", DateTime.Now)

        GridView1.DataSource = dt
        GridView1.DataBind()
    End Sub
End Class

El resultado es el siguiente:

ASP.NET and PDF

Puedes descargar el ejemplo en esta liga.

¡!!! Anímate y déjanos tus comentarios a ver que te pareció este ejemplo.

Artículos relacionados
70 Comentarios
  • Juan Manuel Comentar
    Tuesday, July 16, 2013

    Muy buen ejemplo, de donde puedo descargar el ejemplo?

    • José I. EstradaComentar
      Tuesday, July 16, 2013

      Lo puedes descargar en la siguiente liga https://github.com/jiestrada/ExportASP.NET_PDF saludos

  • Jorge Antonio Comentar
    Tuesday, July 16, 2013

    Ya lo estoy probando, buen aporte

  • Jose Comentar
    Tuesday, November 19, 2013

    Excelente amigo pero tengo un problema con las rutas relativas al insertar una imagen No se puede encontrar una parte de la ruta de acceso 'C:\Program Files\IIS Express\Images\logo_bimbo.jpg'.

    • José I. Estrada HdzComentar
      Wednesday, November 20, 2013

      Hola José, Puedes mandarme el código para ver cual es el problema, esa imagen "logo_bimbo.jpg" lo tienes en tu proyecto? y la carpeta tiene permisos de lectura y escritura? Saludos

  • Rodrigo Comentar
    Monday, November 25, 2013

    No me funciona me entrega error en la siguiente linea Me.Page.RenderControl(hw) error: can only be called during Render(); si alguien me ayudara

  • Edgar Zambrano Comentar
    Friday, July 25, 2014

    Gracias por tu ejemplo, lo realice en C# y me funciono perfecto, claro me habia generado error al inicio pero era que me faltaba EnableEventValidation="false".

  • Edgar Zambrano Comentar
    Friday, July 25, 2014

    Tengo una pregunta, si quisiera cambiar la orientación de la página en el pdf, por ejemplo que me genere el archivo con la orientación de la hoja horizontal y no vertical como seria?

  • mily Comentar
    Wednesday, August 13, 2014

    Hola!! me da el siguiente error: "The document has no pages" en la linea "pdfDoc.Close()" A qué se refiere?

  • Yexon Comentar
    Wednesday, September 24, 2014

    Amigo me da el siguiente error al tratar de replicar tu ejemplo me podrias ayudar por favor. Sólo se puede llamar a RegisterForEventValidation durante Render();

  • Alvaro Comentar
    Friday, March 20, 2015

    me sale lo siguiente:"Error en el servidor remoto: (407) Se requiere autenticación del proxy."

  • joe pinedo Comentar
    Monday, July 6, 2015

    me da error en htmlparser.parse(sr)

  • Juan Carlos Comentar
    Monday, July 27, 2015

    hice el ejercicio con c#, y me marca un error en un par de imagenes que tengo, las quite y funciono pero no me respeta los estilos, incluso en el PDF de resultado me imprime las deficiciones de los estilos y las funciones javascript que tengo en el archivo aspx.

  • Jose Hernandez Comentar
    Thursday, October 29, 2015

    Que tal. ya hice el ejemplo del codigo, y me sale un error de que no tiene acceso a mis imagenes, las cuales estan en mi proyecto, espero me puedan ayudar

  • Wilson Lemus Comentar
    Wednesday, December 23, 2015

    Quiero saber si no tiene el mismo ejemplo pero con C#. Gracias

  • larva Comentar
    Tuesday, May 10, 2016

    NO SE PUEDE EXPORTAR LA IMAGEN MALDITA SEA........

  • Hocking Comentar
    Tuesday, March 7, 2017

    Heya i'm for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and help others like you aided me.

  • Petty Comentar
    Friday, March 10, 2017

    I know this if off topic but I'm looking into starting my own blog and was wondering what all is needed to get setup? I'm assuming having a blog like yours would cost a pretty penny? I'm not very internet savvy so I'm not 100% positive. Any recommendations or advice would be greatly appreciated. Cheers

  • Coons Comentar
    Monday, March 13, 2017

    I like what you guys tend to be up too. This sort of clever work and coverage! Keep up the very good works guys I've included you guys to my blogroll.

  • Franco Comentar
    Saturday, April 15, 2017

    Its like you learn my thoughts! You appear to understand so much about this, such as you wrote the guide in it or something. I think that you just can do with some p.c. to force the message home a little bit, however instead of that, that is great blog. A great read. I will certainly be back.

  • Dahms Comentar
    Monday, April 24, 2017

    ? am now not sure the place you are getting ?our ?nfo, but great topic. I needs to spend some time learning mu?h more or working out mo?e. Thank you for great info I w?s l?oking for this information for my mission.

  • Franki Comentar
    Wednesday, May 17, 2017

    Paragraph writing is also a excitement, if you be acquainted with then you can write if not it is complex to write.

  • 0 Comentar
    Monday, May 22, 2017

    Hi! Someone in my Myspace group shared this site with us so I came to check it out. I'm definitely loving the information. I'm bookmarking and will be tweeting this to my followers! Excellent blog and great style and design.

  • Feakes Comentar
    Sunday, May 28, 2017

    If some one wishes to be updated with latest technologies therefrore he must be pay a visit this web page and be up to date all the time.

  • Kohlmeier Comentar
    Monday, May 29, 2017

    Have you ever thought about including a little bitt more than just your articles? Imean, what you say is fundamental and all. However think about iff you added some great photos or video clips to give your posts more, "pop"! Your content is excellent but with pics and videos, thius site could certainly be one of the greatest in its niche. Terrific blog!

  • Anderton Comentar
    Tuesday, June 6, 2017

    Terrific work! That is the kind of information that are meant to be shared across the net. Disgrace on the seek engines for not positioning this post higher! Come on over and consult with my website . Thank you =)

  • Bachus Comentar
    Saturday, June 10, 2017

    Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Anyway I'll be subscribing to your feeds and even I achievement you access consistently quickly.

  • Gerald Comentar
    Saturday, June 17, 2017

    Olá lá , gosto de ler através de o post . Eu queria para escrever um pequeno comentário para apoiar vocês.

  • Corlette Comentar
    Saturday, June 17, 2017

    Inspire e empurre a barriga com as maos.

  • Farris Comentar
    Monday, June 19, 2017

    Leia artigo novamente e faca algo.

  • Hanna Comentar
    Wednesday, June 21, 2017

    Cartao ficou m?ito bonito, e diferente!

  • Ransome Comentar
    Tuesday, July 11, 2017

    I must thank you for the efforts you've put in writing this site. I'm hoping to check out the same high-grade blog posts by you in the future as well. In fact, your creative writing abilities has motivated me to get my very own site now ;)

  • Shute Comentar
    Sunday, August 6, 2017

    GR

  • Algeranoff Comentar
    Saturday, September 2, 2017

    Fb hacking and other safety associated points.

  • Wildman Comentar
    Monday, September 4, 2017

    Whether you have chose to become an Approved or Premier Reseller, you will get pleasure from the benefits of growing your enterprise with Intuit options.

  • Blevins Comentar
    Friday, September 8, 2017

    Hey There. I found your blog using msn. This is a very well written article. I will be sure to bookmark it and return to read more of your useful info. Thanks for the post. I will definitely return.

  • Hollway Comentar
    Tuesday, September 12, 2017

    I'm gone to convey my little brother, that he should also pay a visit this website on regular basis to obtain updated from hottest gossip.

  • Sauls Comentar
    Monday, October 2, 2017

    Hey! I know this is somewhat off-topic however I had to ask. Does running a well-established website like yours take a large amount of work? I am completely new to operating a blog but I do write in my journal everyday. I'd like to start a blog so I can easily share my own experience and views online. Please let me know if you have any kind of ideas or tips for new aspiring blog owners. Appreciate it!

  • Bivens Comentar
    Thursday, October 12, 2017

    No matter if some one searches for his necessary thing, therefore he/she wants to be available that in detail, thus that thing is maintained over here.

  • Morris Comentar
    Thursday, October 19, 2017

    Yeoh did not support Leung publicly.

  • Caulfield Comentar
    Friday, October 27, 2017

    Page rank is how much more or less important a search engine believes your website to be relative to other websites with similar content for the search terms used and will use it as part of the decision in determining website positioning in a list of search results.

  • Trenwith Comentar
    Monday, October 30, 2017

    Hi, all is going fine here and ofcourse every one is sharing facts, that's actually fine, keep up writing.

  • Kater Comentar
    Monday, November 13, 2017

    31 yr old Paediatrician Zerbe from Madoc, enjoys to spend time languages, Dewa Poker and operating on cars. Finds the planet an enjoyable place following 6 weeks at Generalife and Albayzín.

  • Sconce Comentar
    Friday, November 17, 2017

    I absolutely love your blog.. Excellent colors & theme. Did you build this website yourself? Please reply back as I'm hoping to create my own personal website and would love to find out where you got this from or just what the theme is named. Many thanks!

  • Meek Comentar
    Saturday, November 18, 2017

    Sweet blog! I found it while browsing on Yahoo News. Do you have any tips on how to get listed in Yahoo News? I've been trying for a while but I never seem to get there! Thank you

  • Klass Comentar
    Monday, November 20, 2017

    This design is steller! You most certainly know how to keep a reader entertained. Between your wit and your videos, I was almost moved to start my own blog (well, almost...HaHa!) Fantastic job. I really loved what you had to say, and more than that, how you presented it. Too cool!

  • Fink Comentar
    Thursday, November 23, 2017

    You ought to be a part of a contest for one of the best sites on the internet. I'm going to recommend this website!

  • Mcqueen Comentar
    Thursday, November 30, 2017

    We are a group of Merchandisers.

  • Reuter Comentar
    Tuesday, December 5, 2017

    It's going to be ending of mine day, except before finish I am reading this wonderful article to improve my experience.

  • Reuter Comentar
    Tuesday, December 5, 2017

    It's going to be ending of mine day, except before finish I am reading this wonderful article to improve my experience.

  • Gilroy Comentar
    Thursday, December 14, 2017

    Amazing! This blog looks just like my old one! It's on a completely different topic but it has pretty much the same page layout and design. Great choice of colors! beasiswa s2 australia 2016

  • Mahan Comentar
    Saturday, December 23, 2017

    Magnificent website. Lots of helpful information here. I am sending it to several pals ans additionally sharing in delicious. And obviously, thank you on your sweat!

  • Colangelo Comentar
    Friday, December 29, 2017

    Woah! I'm really loving the template/theme of this site. It's simple, yet effective. A lot of times it's very difficult to get that "perfect balance" between usability and visual appeal. I must say that you've done a excellent job with this. Also, the blog loads very quick for me on Internet explorer. Outstanding Blog!

  • Holley Comentar
    Friday, December 29, 2017

    It's going to be end of mine day, however before finish I am reading this wonderful piece of writing to increase my experience.

  • Weatherburn Comentar
    Tuesday, January 9, 2018

    Good day! Would you mind if I share your blog with my myspace group? There's a lot of folks that I think would really appreciate your content. Please let me know. Thank you

  • Cropper Comentar
    Friday, January 19, 2018

    Superb, what a weblog it is! This weblog provides useful data to us, keep it up.

  • Farncomb Comentar
    Sunday, January 28, 2018

    Your style is unique in comparison to other folks I've read stuff from. Many thanks for posting when you have the opportunity, Guess I'll just book mark this blog.

  • Engle Comentar
    Tuesday, February 27, 2018

    Leather jackets put a shot of cool in your wardrobe.

  • alezz Comentar
    Tuesday, March 13, 2018

    Realmente bueno hombre!!. 100Pts.... se le debe agregar en la etiqueta Page del html un EnableEventValidation="false" y funciona de maravilla. se nota que se le puede sacar mucho provecho.

  • Seymore Comentar
    Saturday, March 17, 2018

    I am really thankful to the owner of this website who has shared this great post at here.

  • Thrasher Comentar
    Saturday, March 24, 2018

    When some one searches for his required thing, therefore he/she wants to be available that in detail, so that thing is maintained over here.

  • Hardman Comentar
    Tuesday, March 27, 2018

    Howdy! Some?ne in my Facebook ?roup shared th?s site with u? so ? came to give it a lo?k. I'm definitely loving thee info?mation. I'm book-marking ?nd w?ll bee tweeting this to my followers! Outstanding blog ?nd g?eat deskgn and style.

  • Tuck Comentar
    Wednesday, March 28, 2018

    That is a very good tip particularly to those fresh to the blogosphere. Simple but very accurate info… Many thanks for sharing this one. A must read article!

  • Blair Comentar
    Wednesday, March 28, 2018

    ? love what ?ou guys ?re usual?? u? too. This ?ind ?f clever ?ork and exposure! K?ep up the awesome w?rks guys I've you guys t? my ownn blogroll.

  • Christopher Comentar
    Wednesday, March 28, 2018

    Hey there! I know this i? some?hat off topic b?t I w?s wondering if ?ou knew where I ?ould locate a captcha plugin for my comment form? ?'m using the same blog platform as you?s ?nd I'm ha?ing ?roblems finding ?ne? Thanks a ?ot!

  • Demaria Comentar
    Saturday, March 31, 2018

    H?llo, aft?r reading thi? amazing article i am also glad t? share my experience hhere w?th mates.

  • Koerstz Comentar
    Wednesday, April 4, 2018

    You could certainly see your enthusiasm within the work you write. The arena hopes for even more passionate writers like you who aren't afraid to say how they believe. Always go after your heart.

  • Fysh Comentar
    Wednesday, April 25, 2018

    I am sure this article has touched all the internet visitors, its really really pleasant piece of writing on building up new website.

  • Horner Comentar
    Friday, April 27, 2018

    Valuable info. Fortunate me I discovered your site by chance, and I'm surprised why this coincidence did not happened earlier! I bookmarked it.

  • Kossak Comentar
    Friday, April 27, 2018

    After checking out a few of the articles on your site, I seriously appreciate your way of writing a blog. I saved it to my bookmark webpage list and will be checking back in the near future. Take a look at my web site as well and let me know how you feel.

  • Horder Comentar
    Saturday, May 26, 2018

    Aw, this was a very nice post. Finding the time and actual effort to make a great article… but what can I say… I put things off a lot and don't manage to get anything done.

  • Nickson Comentar
    Monday, May 28, 2018

    Since the admin of this site is working, no hesitaation very rapidly it will be well-known, due to iits feature contents.

Enviame un comentario