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 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.


Comentarios (68)

  • Juan Manuel Responder

    Muy buen ejemplo, de donde puedo descargar el ejemplo?

    Tuesday, July 16, 2013 10:46 AM
    • José I. Estrada Responder

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

      7/16/2013 12:13:24 PM
  • Jorge Antonio Responder

    Ya lo estoy probando, buen aporte

    Tuesday, July 16, 2013 12:11 PM
  • Jose Responder

    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'.

    Tuesday, November 19, 2013 9:47 AM
    • José I. Estrada Hdz Responder

      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

      11/20/2013 8:14:01 AM
  • Rodrigo Responder

    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

    Monday, November 25, 2013 7:09 AM
  • Edgar Zambrano Responder

    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".

    Friday, July 25, 2014 12:55 PM
  • Edgar Zambrano Responder

    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?

    Friday, July 25, 2014 1:00 PM
  • mily Responder

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

    Wednesday, August 13, 2014 7:01 AM
  • Yexon Responder

    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();

    Wednesday, September 24, 2014 5:48 PM
  • Alvaro Responder

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

    Friday, March 20, 2015 1:58 PM
  • joe pinedo Responder

    me da error en htmlparser.parse(sr)

    Monday, July 6, 2015 1:38 PM
  • Juan Carlos Responder

    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.

    Monday, July 27, 2015 12:28 PM
  • Jose Hernandez Responder

    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

    Thursday, October 29, 2015 9:58 AM
  • Wilson Lemus Responder

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

    Wednesday, December 23, 2015 9:37 AM
  • larva Responder


    Tuesday, May 10, 2016 5:35 PM
  • Hocking Responder

    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.

    Tuesday, March 7, 2017 1:28 AM
  • Petty Responder

    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

    Friday, March 10, 2017 8:40 PM
  • Coons Responder

    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.

    Monday, March 13, 2017 5:53 PM
  • Franco Responder

    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.

    Saturday, April 15, 2017 6:18 PM
  • Dahms Responder

    ? 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.

    Monday, April 24, 2017 9:21 PM
  • Franki Responder

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

    Wednesday, May 17, 2017 1:08 AM
  • 0 Responder

    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.

    Monday, May 22, 2017 9:20 PM
  • Feakes Responder

    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.

    Sunday, May 28, 2017 2:11 AM
  • Kohlmeier Responder

    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!

    Monday, May 29, 2017 3:12 AM
  • Anderton Responder

    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 =)

    Tuesday, June 6, 2017 7:30 AM
  • Bachus Responder

    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.

    Saturday, June 10, 2017 6:43 AM
  • Gerald Responder

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

    Saturday, June 17, 2017 3:33 AM
  • Corlette Responder

    Inspire e empurre a barriga com as maos.

    Saturday, June 17, 2017 6:53 AM
  • Farris Responder

    Leia artigo novamente e faca algo.

    Monday, June 19, 2017 9:58 AM
  • Hanna Responder

    Cartao ficou m?ito bonito, e diferente!

    Wednesday, June 21, 2017 12:42 AM
  • Ransome Responder

    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 ;)

    Tuesday, July 11, 2017 9:41 AM
  • Shute Responder


    Sunday, August 6, 2017 12:48 AM
  • Algeranoff Responder

    Fb hacking and other safety associated points.

    Saturday, September 2, 2017 6:30 AM
  • Wildman Responder

    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.

    Monday, September 4, 2017 6:02 PM
  • Blevins Responder

    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.

    Friday, September 8, 2017 3:05 PM
  • Hollway Responder

    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.

    Tuesday, September 12, 2017 2:46 AM
  • Sauls Responder

    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!

    Monday, October 2, 2017 11:05 AM
  • Bivens Responder

    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.

    Thursday, October 12, 2017 11:05 PM
  • Morris Responder

    Yeoh did not support Leung publicly.

    Thursday, October 19, 2017 10:14 AM
  • Caulfield Responder

    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.

    Friday, October 27, 2017 10:53 PM
  • Trenwith Responder

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

    Monday, October 30, 2017 1:27 AM
  • Kater Responder

    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.

    Monday, November 13, 2017 10:21 PM
  • Sconce Responder

    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!

    Friday, November 17, 2017 12:33 PM
  • Meek Responder

    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

    Saturday, November 18, 2017 11:16 AM
  • Klass Responder

    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!

    Monday, November 20, 2017 11:30 PM
  • Fink Responder

    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!

    Thursday, November 23, 2017 4:20 PM
  • Mcqueen Responder

    We are a group of Merchandisers.

    Thursday, November 30, 2017 2:06 AM
  • Reuter Responder

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

    Tuesday, December 5, 2017 8:27 AM
  • Reuter Responder

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

    Tuesday, December 5, 2017 8:28 AM
  • Gilroy Responder

    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

    Thursday, December 14, 2017 10:34 AM
  • Mahan Responder

    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!

    Saturday, December 23, 2017 5:21 PM
  • Colangelo Responder

    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!

    Friday, December 29, 2017 1:55 AM
  • Holley Responder

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

    Friday, December 29, 2017 4:40 PM
  • Weatherburn Responder

    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

    Tuesday, January 9, 2018 7:58 PM
  • Cropper Responder

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

    Friday, January 19, 2018 9:56 PM
  • Farncomb Responder

    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.

    Sunday, January 28, 2018 6:58 AM
  • Engle Responder

    Leather jackets put a shot of cool in your wardrobe.

    Tuesday, February 27, 2018 12:13 PM
  • alezz Responder

    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.

    Tuesday, March 13, 2018 4:26 PM
  • Seymore Responder

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

    Saturday, March 17, 2018 3:25 PM
  • Thrasher Responder

    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.

    Saturday, March 24, 2018 8:13 PM
  • Hardman Responder

    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.

    Tuesday, March 27, 2018 4:25 AM
  • Tuck Responder

    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!

    Wednesday, March 28, 2018 1:19 PM
  • Blair Responder

    ? 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.

    Wednesday, March 28, 2018 6:29 PM
  • Christopher Responder

    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!

    Wednesday, March 28, 2018 6:34 PM
  • Demaria Responder

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

    Saturday, March 31, 2018 7:26 PM
  • Koerstz Responder

    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.

    Wednesday, April 4, 2018 6:28 PM
  • Fysh Responder

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

    Wednesday, April 25, 2018 1:22 AM

Animate deja un comentario!!!

Eres un humano?

Últimos Tweets


  • Dirección: Plutarco Elias Calles 243, Granjas México, Iztacalco, DF.

  • Teléfono:55-2712-3820 o 55-4164-9484

  • Email: info@developerji.com