在使用iTextSharp尝试解析我想要转换为PDF的html字符串时,我的TextReader遇到了一些麻烦。
Function ViewDeliveryNote(ByVal id As Integer) As FileStreamResult
'Memory buffer
Dim ms As MemoryStream = New MemoryStream()
'the document
Dim document As Document = New Document(PageSize.A4)
'the pdf writer
PdfWriter.GetInstance(document, ms)
Dim wc As WebClient = New WebClient
Dim htmlText As String = wc.DownloadString("http://localhost:59800/Warehouse/DeliveryNote/" & id) 'Change to live URL
Dim worker As html.simpleparser.HTMLWorker = New html.simpleparser.HTMLWorker(document)
Dim reader As TextReader = New StringReader(htmlText)
document.Open()
worker.Open()
worker.StartDocument()
worker.Parse(reader)
worker.EndDocument()
worker.Close()
document.Close()
'ready the file stream
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=DeliveryNote.pdf")
Response.Buffer = True
Response.Clear()
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer.Length)
Response.OutputStream.Flush()
Response.End()
Return New FileStreamResult(Response.OutputStream, "application/pdf")
End Function
即使worker.Parse(reader)
已成功阅读HTML页面,它停在的行Object reference not set to an instance of an object
也会显示错误StringReader(htmlText)
。
我不确定我现在做错了什么,或者我现在缺少什么,所以如果有任何帮助,我将不胜感激。
更新我只是尝试了Dim reader As New StringReader(htmlText)
,但无济于事。虽然htmlText仍然肯定包含一个值,但该对象认为它没有。
答案 0 :(得分:0)
我肯定会为此编写一个自定义操作结果,以避免污染我的控制器。此外,您的代码中所有那些未使用的一次性资源都应该得到照顾:
Public Class PdfResult
Inherits ActionResult
Private ReadOnly _id As Integer
Public Sub New(ByVal id As Integer)
_id = id
End Sub
Public Overrides Sub ExecuteResult(context As ControllerContext)
If context Is Nothing Then
Throw New ArgumentNullException("context")
End If
Dim response = context.HttpContext.Response
response.Buffer = True
response.ContentType = "application/pdf"
response.AddHeader("Content-Disposition", "attachment; filename=DeliveryNote.pdf")
Using client = New WebClient()
Dim htmlText As String = client.DownloadString("http://localhost:59800/Warehouse/DeliveryNote/" & _id) 'Change to live URL
Dim doc = New Document(PageSize.A4)
PdfWriter.GetInstance(doc, response.OutputStream)
Dim worker = New HTMLWorker(doc)
doc.Open()
worker.Open()
Using reader = New StringReader(htmlText)
worker.Parse(reader)
End Using
doc.Close()
End Using
End Sub
End Class
然后简单地说:
Function ViewDeliveryNote(ByVal id As Integer) As ActionResult
Return New PdfResult(id)
End Function
您还应确保服务器可以访问所需的网址。不要忘记他的请求将在网络帐户的上下文中执行,该帐户可能与普通帐户没有相同的权限。