Results 1 to 8 of 8

Thread: [FOUND ISSUE] iTextSharp Html to PDF - issue parsing html

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2000
    Location
    Minnesota
    Posts
    830

    [FOUND ISSUE] iTextSharp Html to PDF - issue parsing html

    Below I have code that takes a url and pulls the html source. However, using iTextSharp if I print to pdf it works but it shows all the html tags in the document. I want it to be as if viewing in the browser so I believe what I am missing is dealing with the line 'HtmlParser.Parse(document, se)'. Does anyone know how I change this to accept my html code and parse it?

    What I am trying to do it make a print to pdf linkbutton on my page that basically will requery the page and send the source to the iTextSharp to convert to pdf. If you think there is a better way let me know.

    Code:
    Imports System
    Imports System.Data
    Imports System.IO
    Imports System.Xml
    Imports iTextSharp.text
    Imports iTextSharp.text.pdf
    Imports iTextSharp.text.html
    Imports iTextSharp.text.html.simpleparser
    Imports System.Net
    
    Partial Class testemail
        Inherits System.Web.UI.Page
    
        Protected Sub btnSendEmail_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnTest.Click
            lblOutput.Text = "ABCDEFG".ToLower
        End Sub
    
        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim req As WebRequest = WebRequest.Create("http://www.google.com")
            Dim resp As WebResponse = req.GetResponse()
    
            Dim s As Stream = resp.GetResponseStream()
            Dim sr As StreamReader = New StreamReader(s, Encoding.ASCII)
            Dim doc As String = sr.ReadToEnd()
    
            CreatePDFDocument(doc)
            
        End Sub
    
        Public Shared Sub CreatePDFDocument(ByVal strHtml As String)
            Dim MStream As New MemoryStream()
            Dim document As New Document(PageSize.A4, 80, 50, 30, 65)
            Try
                Dim writer As PdfWriter = PdfWriter.GetInstance(document, MStream)
                'document.Open()
                'document.Add(New iTextSharp.text.Paragraph("This is a test and must work"))
                'document.Close()
    
                Dim se As New StringReader(strHtml)
                document.Open()
                HtmlParser.Parse(document, se)  '<---- DOESN'T LIKE THIS LINE
                document.Close()
    
            Catch e As Exception
                Throw e
            End Try
            HttpContext.Current.Response.Buffer = True
            HttpContext.Current.Response.ClearContent()
            HttpContext.Current.Response.ClearHeaders()
            HttpContext.Current.Response.ContentType = "application/pdf"
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=myPDFNew.pdf")
            HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer())
            HttpContext.Current.Response.End()
        End Sub
    End Class
    HTML Code:
    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="testemail.aspx.vb" Inherits="testemail" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnTest" runat="server" Text="Test" />
            &nbsp;&nbsp;&nbsp;<asp:Button ID="Button1" runat="server" Text="Button" /><br />
            &nbsp;<br /><asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>
            <br />
            <asp:TextBox ID="txtSource" runat="server" TextMode="MultiLine"></asp:TextBox></div>
        </form>
    </body>
    </html>
    Last edited by lleemon; Apr 29th, 2009 at 06:32 AM. Reason: Unresolved but found issue

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: iTextSharp Html to PDF - issue parsing html

    Usually it's specific parts of a page that you want to send over the PDF file. Controls generally have a .RenderControl() method which writes out the HTML of that specific control which you can use to send over to the PDF so that you only render the parts that you want selectively.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2000
    Location
    Minnesota
    Posts
    830

    Re: iTextSharp Html to PDF - issue parsing html

    mendhak - thanks for the info. It would be so much easier if you could say, take the page html and pass and then it creates a pdf. Sounds like I have to either manually recreate with iTextSharp or find a different way.

  4. #4
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: iTextSharp Html to PDF - issue parsing html

    Oh, I see what you mean - you want all the HTML from the entire page?

    OK, override the Render method.

    Code:
     using(System.IO.MemoryStream ms = new System.IO.MemoryStream()) 
        { 
            using(System.IO.StreamWriter sw = new System.IO.StreamWriter(ms)) 
            { 
                HtmlTextWriter htmlWriter = new HtmlTextWriter(sw); 
                base.Render(htmlWriter); 
                htmlWriter.Flush(); 
                ms.Position = 0; 
                using(System.IO.StreamReader sr = new System.IO.StreamReader(ms)) 
                { 
                    string allTheLovelyHTML = sr.ReadToEnd(); 
                    sr.Close(); 
                } 
            } 
        }
    Or something like that. allTheLovelyHTML should then contain all the lovely HTML from your page. You can use it to generate a PDF.

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2000
    Location
    Minnesota
    Posts
    830

    Re: iTextSharp Html to PDF - issue parsing html

    The webrequest does the same thing and is working. I could try render, but I will still have the issue of writing it to pdf which is my current state.

    Any suggestions to take the html and convert to pdf?

  6. #6

    Thread Starter
    Fanatic Member
    Join Date
    Nov 2000
    Location
    Minnesota
    Posts
    830

    Re: iTextSharp Html to PDF - issue parsing html

    Based on the findings of Imran the following will work if the html is valid.

    Code:
    Public Shared Sub CreatePDFDocument(ByVal strHtml As String)
            Dim MStream As New MemoryStream()
            Dim document As New Document(PageSize.A4, 80, 50, 30, 65)
            Try
                Dim writer As PdfWriter = PdfWriter.GetInstance(document, MStream)
         
                Dim _xmlr As System.Xml.XmlTextReader = New System.Xml.XmlTextReader(New StringReader(strHtml))
    
                HtmlParser.Parse(document, _xmlr)
    
            Catch e As Exception
                Throw e
            End Try
            HttpContext.Current.Response.Buffer = True
            HttpContext.Current.Response.ClearContent()
            HttpContext.Current.Response.ClearHeaders()
            HttpContext.Current.Response.ContentType = "application/pdf"
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=myPDFNew.pdf")
            HttpContext.Current.Response.BinaryWrite(MStream.GetBuffer())
            HttpContext.Current.Response.End()
        End Sub
    But it seems like any page I try even google it gives some kind of error. The basic "<html><body>THis is a test</body></html>" works though so guess I will either recreate or find a different solution.

  7. #7
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: [FOUND ISSUE] iTextSharp Html to PDF - issue parsing html

    What's the error?

  8. #8
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: [FOUND ISSUE] iTextSharp Html to PDF - issue parsing html

    The issue of writing to PDF isn't a big one, though. iTextSharp does, after all, take an HTML string, which is what the code in #4 is showing you, for the page.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width