使用html字符串中的iTextsharp生成PDF

时间:2014-12-02 11:44:45

标签: asp.net vb.net itextsharp

我有一个html格式字符串,其中包含从数据库加载的数据以及代码隐藏文件中的图像,我将其绑定到后面的代码中的aspx页面div,如下所示

Dim pdfstring as string= "< html>< body>< table width='93%' border='0' cellspacing='0' cellpadding='0' style='margin:0px auto;'><tr><td>&nbsp;</td></tr><tr><td width=100%' align='left' style='padding:10px 20px; background: #005984; text-align:left;' > <img src='D:\Develop_Duke\ra\PortalDev\Portal\Assets\image\pdfimages\logo.png' border='0'/><br/></tr></table>< /body>< /html>"

您能否告诉我如何使用asp.net中的 ITextSharp 从生成的html字符串生成pdf格式(我不想再将该字符串写入外部任何.html文件)它应该显示带有hss和css的路径的图像。

1 个答案:

答案 0 :(得分:1)

你应该看看在线documentation,顺便说一下你的任务是如下:

Using stream As New MemoryStream
          Using doc As New iTextSharp.text.Document(PageSize.A4, 0, 0, 0, 0)
Using writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, stream)

  writer.CloseStream = False
  Dim xmlWorker = XMLWorkerHelper.GetInstance()

  doc.Open()


  Dim _helperWiter As New StringWriter

  // the page to convert to PDF
  HttpContext.Current.Server.Execute(String.Format("../Reports/Templates/Page.aspx", _helperWiter)
  Using reader As New StringReader(_helperWiter.ToString())
    xmlWorker.ParseXHtml(writer, doc, reader)

  End Using
  doc.Close()
  writer.Close()
  stream.Close()

  Response.ContentType = "pdf/application"
  Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.pdf", filemane))

  Response.BufferOutput = False
  Response.BinaryWrite(stream.ToArray())

  Response.Flush()
  Response.Close()
  Response.End()

    End Using
  End Using
End Using