我使用此代码使用itextsharp 5.0.6将我的aspx页面转换为pdf:
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
但是我在这一行上一直收到错误,说对象引用没有设置为对象的实例:
Dim list As List(Of IElement) = HTMLWorker.ParseToList(sReader, styles)
如果我在这行代码中从变量Html1更改为Html,它工作正常。
Using sReader As TextReader = New StringReader(Html1.ToString())
知道如何修复此错误吗?这是功能:
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
感谢您的帮助。
答案 0 :(得分:2)
(评论移动回答)
iTextSharp的HTMLWorker
已知<hr>
标记存在问题。短期解决方案是删除这些标签,但长期解决方案是切换到支持这些标签的XMLWorker
,并且正在积极开发和维护。