如何保存PDF

时间:2014-03-20 15:42:07

标签: asp.net vb.net pdf

嗨我有一个pdf生成,当我点击按钮时,它会很好地下载到计算机上。但是,我需要将该文件保存到系统中的文件夹中。

我尝试了很多不同的方法,但我无法正常工作是否有任何可以将其保存到我的网站上的Visual Studio中创建的PDF文件夹

更新代码

    Partial Class Pages_Payment
Inherits System.Web.UI.Page 



Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
        btnPayment.Visible = False

    Response.ContentType = "application/pdf"

    Response.AddHeader("content-disposition", "attachment;filename=Receipt_" & Session("InvoNo") & ".pdf")

    Response.Cache.SetCacheability(HttpCacheability.NoCache)

    Dim sw As New StringWriter()

    Dim hw As New HtmlTextWriter(sw)

    pnlPerson.RenderControl(hw)

    Dim sr As New StringReader(sw.ToString())

    Dim pdfDoc As New 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()


    Pages_Payment.SavePDF("~/PDF/Mypdf.pdf", pdfDoc)


End Sub

Public Shared Sub SavePDF(virtualPath As String, document As Document)
    Dim msOutput As New MemoryStream()
    Dim writer As New PdfWriter(document, msOutput)
    Dim filebytes As Byte() = msOutput.ToArray()
    Dim path As String = Server.MapPath(virtualPath)
    File.WriteAllBytes(path, filebytes)
End Sub

结束班

1 个答案:

答案 0 :(得分:0)

基本上PdfWriter连接到MemoryStream。将MemoryStream转换为字节数组,然后将字节保存到文件中。

    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
    'btnPayment.Visible = False
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=Receipt_" & Session("InvoNo") & ".pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As New StringWriter()
    Dim hw As New HtmlTextWriter(sw)
    pnlPerson.RenderControl(hw)
    Dim sr As New StringReader(sw.ToString())
    Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
    Dim htmlparser As New HTMLWorker(pdfDoc)
    Dim msOutput As New MemoryStream()
    Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, msOutput)    
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Dim filebytes As Byte() = msOutput.ToArray()
    Dim path As String = Server.MapPath("~/PDF/mypdf.pdf")
    File.WriteAllBytes(path, filebytes)
    Response.BinaryWrite(filebytes)
    Response.End()
End Sub