Question

I use this code to convert my aspx page to pdf using itextsharp 5.0.6:

 Using ms = New MemoryStream()

        Dim Html As String = vbCr & vbLf & "<h1>h1</h1>" & vbCr & vbLf & "<p class=""bo"">A paragraph</p>    " & vbCr & vbLf & "<ul> " & vbCr & vbLf & "<li>one</li>   " & vbCr & vbLf & "<li>two</li>   " & vbCr & vbLf & "<li>three</li>   " & vbCr & vbLf & "</ul>"
        Dim Html1 As String = RenderControlToString(Page)

        Dim styles As New StyleSheet()
        styles.LoadStyle("bo", "size", "10")
        styles.LoadTagStyle(HtmlTags.H1, HtmlTags.FONT, "59")
        styles.LoadTagStyle(HtmlTags.H1, HtmlTags.COLOR, "#ff0000")
        styles.LoadTagStyle(HtmlTags.UL, HtmlTags.INDENT, "10")
        styles.LoadTagStyle(HtmlTags.LI, HtmlTags.LEADING, "16")

        Using document As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate())

            PdfWriter.GetInstance(document, ms)
            document.Open()

            document.Add(New Paragraph("this is atest"))
            document.Add(New Paragraph("this is a test"))
            Dim strB As New StringBuilder(Html1)
            Using sReader As TextReader = New StringReader(Html1.ToString())
                Dim list As List(Of IElement) = HTMLWorker.ParseToList(sReader, styles)
                For Each elm As IElement In list
                    document.Add(elm)
                Next
            End Using


        End Using

    End Using

However I kept getting error on this line saying object reference not set to an instance of an object:

 Dim list As List(Of IElement) = HTMLWorker.ParseToList(sReader, styles)

If I changed from variable Html1 to Html in this line of code, it is working fine.

  Using sReader As TextReader = New StringReader(Html1.ToString())

Any idea how I can fix this error? Here is the function:

  Private Function RenderControlToString(control As Control) As String
    Dim sb As New StringBuilder()
    Dim sw As New StringWriter(sb)
    Dim writer As New HtmlTextWriter(sw)

    control.RenderControl(writer)
    Return sb.ToString()
End Function

Thanks for your help.

Was it helpful?

Solution

(comment moved to answer)

iTextSharp's HTMLWorker has known problems with <hr> tags. The short term solution is to just remove those tags but the long term solution is to switch to XMLWorker which supports those tags and is actively being developed and maintained.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top