将网页导出为PDF

时间:2014-05-07 09:08:52

标签: asp.net pdf

我正在尝试从具有主站点的asp.net网页导出PDF。请注意,我没有使用网格视图,我只想导出页面本身。

以下是我目前的情况:

Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New iTextSharp.text.Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()

我得到的错误信息是:

UNC路径的格式应为\ server \ share。

描述:执行当前Web请求期间发生了未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.ArgumentException:UNC路径的格式应为\ server \ share。

Source Error: 


Line 46:             PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
Line 47:             pdfDoc.Open()
Line 48:             htmlparser.Parse(sr)
Line 49:             pdfDoc.Close()
Line 50:             Response.Write(pdfDoc)

任何帮助都会很棒,谢谢。

1 个答案:

答案 0 :(得分:0)

你必须使用一些免费的“itextsharp.dll”第三方dll。您可以将其用于以下代码。

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
    ' Verifies that the control is rendered 

End Sub

Protected Sub btnExport_Click(sender As Object, e As EventArgs)
    If gridview.Rows.Count > 0 Then
        Dim sw As New StringWriter()
        Dim htw As New HtmlTextWriter(sw)

        gridview.RenderControl(htw)

        Dim mem = New MemoryStream()

        Dim document As New Document(PageSize.LETTER, 50, 50, 50, 50)
        PdfWriter.GetInstance(document, mem)

        document.Open()

        Dim hw As New iTextSharp.text.html.simpleparser.HTMLWorker(document)
        hw.Parse(New StringReader(sw.ToString()))
        document.Close()

        Response.ClearContent()
        Response.ClearHeaders()
        Response.ContentType = "application/pdf"
        Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now)

        Response.BinaryWrite(mem.ToArray())
        Response.[End]()
        Response.Flush()
        Response.Clear()
    End If
End Sub