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"/>
    <form id="form1" runat="server">
    <asp:Image ID="Image1" runat="server" ImageUrl="http://www.developerji.com/App_Themes/Principal/Images/logo.png" />
        <asp:GridView ID="GridView1" runat="server">
        <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 />
  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")
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        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)
    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
    End Sub
End Class

El resultado es el siguiente:


Puedes descargar el ejemplo en esta liga.

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

Artículos relacionados
Cómo exportar una página web con PHP a PDF
Cómo exportar una página web con PHP a PDF

En el artículo anterior explique cómo exportar

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

En mi trabajo muchas ocasiones he tenido la ne

¿Cómo exportar una página web html a pdf con una API gratuita?
¿Cómo exportar una página web html a pdf con una API gratuita?

En este post veremos c&oacute;mo convertir nue

70 Comentarios
  • Juan Manuel Comentar
    martes, 16 de julio de 2013

    Muy buen ejemplo, de donde puedo descargar el ejemplo?

    • José I. EstradaComentar
      martes, 16 de julio de 2013

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

  • Jorge Antonio Comentar
    martes, 16 de julio de 2013

    Ya lo estoy probando, buen aporte

  • Jose Comentar
    martes, 19 de noviembre de 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
      miércoles, 20 de noviembre de 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
    lunes, 25 de noviembre de 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
    viernes, 25 de julio de 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
    viernes, 25 de julio de 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
    miércoles, 13 de agosto de 2014

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

  • Yexon Comentar
    miércoles, 24 de septiembre de 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
    viernes, 20 de marzo de 2015

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

  • joe pinedo Comentar
    lunes, 6 de julio de 2015

    me da error en htmlparser.parse(sr)

  • Juan Carlos Comentar
    lunes, 27 de julio de 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
    jueves, 29 de octubre de 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
    miércoles, 23 de diciembre de 2015

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

  • larva Comentar
    martes, 10 de mayo de 2016


  • Hocking Comentar
    martes, 7 de marzo de 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
    viernes, 10 de marzo de 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
    lunes, 13 de marzo de 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
    sábado, 15 de abril de 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
    lunes, 24 de abril de 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
    miércoles, 17 de mayo de 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
    lunes, 22 de mayo de 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
    domingo, 28 de mayo de 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
    lunes, 29 de mayo de 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
    martes, 6 de junio de 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
    sábado, 10 de junio de 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
    sábado, 17 de junio de 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
    sábado, 17 de junio de 2017

    Inspire e empurre a barriga com as maos.

  • Farris Comentar
    lunes, 19 de junio de 2017

    Leia artigo novamente e faca algo.

  • Hanna Comentar
    miércoles, 21 de junio de 2017

    Cartao ficou m?ito bonito, e diferente!

  • Ransome Comentar
    martes, 11 de julio de 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
    domingo, 6 de agosto de 2017


  • Algeranoff Comentar
    sábado, 2 de septiembre de 2017

    Fb hacking and other safety associated points.

  • Wildman Comentar
    lunes, 4 de septiembre de 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
    viernes, 8 de septiembre de 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
    martes, 12 de septiembre de 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
    lunes, 2 de octubre de 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
    jueves, 12 de octubre de 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
    jueves, 19 de octubre de 2017

    Yeoh did not support Leung publicly.

  • Caulfield Comentar
    viernes, 27 de octubre de 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
    lunes, 30 de octubre de 2017

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

  • Kater Comentar
    lunes, 13 de noviembre de 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
    viernes, 17 de noviembre de 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
    sábado, 18 de noviembre de 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
    lunes, 20 de noviembre de 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
    jueves, 23 de noviembre de 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
    jueves, 30 de noviembre de 2017

    We are a group of Merchandisers.

  • Reuter Comentar
    martes, 5 de diciembre de 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
    martes, 5 de diciembre de 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
    jueves, 14 de diciembre de 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
    sábado, 23 de diciembre de 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
    viernes, 29 de diciembre de 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
    viernes, 29 de diciembre de 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
    martes, 9 de enero de 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
    viernes, 19 de enero de 2018

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

  • Farncomb Comentar
    domingo, 28 de enero de 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
    martes, 27 de febrero de 2018

    Leather jackets put a shot of cool in your wardrobe.

  • alezz Comentar
    martes, 13 de marzo de 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
    sábado, 17 de marzo de 2018

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

  • Thrasher Comentar
    sábado, 24 de marzo de 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
    martes, 27 de marzo de 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
    miércoles, 28 de marzo de 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
    miércoles, 28 de marzo de 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
    miércoles, 28 de marzo de 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
    sábado, 31 de marzo de 2018

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

  • Koerstz Comentar
    miércoles, 4 de abril de 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
    miércoles, 25 de abril de 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
    viernes, 27 de abril de 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
    viernes, 27 de abril de 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
    sábado, 26 de mayo de 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
    lunes, 28 de mayo de 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