Warm tip: This article is reproduced from serverfault.com, please click

vb.net-不支持ITextSharp导出的PDF或Visual Basic损坏

(vb.net - ITextSharp exported PDF is not supported or damaged visual basic)

发布于 2020-12-11 14:18:32

我是使用ITextSharp的新手,正在尝试将PDF导出为附件。下面的代码工作正常

Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
Dim newFile As String = "C:\Users\mrogers\Documents\ERCP_CA_Template3.pdf"
Dim pdfReader As New PdfReader(pdfTemplate)
Dim pdfStamper As New PdfStamper(pdfReader, New System.IO.FileStream(newFile, System.IO.FileMode.Create))
Dim pdfFormFields As AcroFields = pdfStamper.AcroFields

pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
pdfStamper.FormFlattening = True

pdfStamper.Close()

但是,当我尝试将其转换为导出附件时,Adobe Acrobat Reader无法打开该文件,因为该文件不受支持,或者该文件已损坏。我的代码如下。

    Dim ms As MemoryStream = New MemoryStream()
    Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
    Dim pdfReader As New PdfReader(pdfTemplate)
    Dim pdfStamper As New PdfStamper(pdfReader, ms)
    Dim pdfFormFields As AcroFields = pdfStamper.AcroFields

    pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
    pdfStamper.FormFlattening = True

    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache)
    HttpContext.Current.Response.ContentType = "application/pdf"
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=testingPdf2.pdf")
    HttpContext.Current.Response.Write(ms.ToArray())
    HttpContext.Current.Response.BufferOutput = True
    HttpContext.Current.Response.Flush()
    HttpContext.Current.Response.Close()

    pdfStamper.Close()

我一直在努力寻找与此相关的任何良好示例或文档。对于我要去哪里的任何帮助,将不胜感激。

Questioner
GingerMattRogers
Viewed
0
GingerMattRogers 2020-12-11 23:17:23

对于任何有类似问题的人,我都可以弄清楚。

    Dim output As New MemoryStream()
    Dim pdfTemplate As String = "C:\Users\mrogers\Documents\ERCP_CA_Template2.pdf"
    Dim pdfReader As New PdfReader(pdfTemplate)
    Dim pdfStamper As New PdfStamper(pdfReader, output)
    Dim pdfFormFields As AcroFields = pdfStamper.AcroFields

    pdfFormFields.SetField("BUSINESS_SITE_ADDRESS_A5", "Demo")
    pdfStamper.FormFlattening = True

    pdfStamper.Close()

    Dim mergedBytes() As Byte = output.GetBuffer()
    HttpContext.Current.Response.Clear()
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=demo4.pdf")
    HttpContext.Current.Response.AddHeader("Content-Length", mergedBytes.Length.ToString())
    HttpContext.Current.Response.ContentType = "application/octet-stream"
    HttpContext.Current.Response.BinaryWrite(mergedBytes.ToArray)
    HttpContext.Current.Response.Flush()
    HttpContext.Current.Response.End()