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

ITextSharp exported PDF is not supported or damaged visual basic

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

I'm new to using ITextSharp and I'm trying to export a PDF as an attachment. The code below works fine

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()

However, when I try to convert this to export an attachment, Adobe Acrobat Reader can't open the file because it's not a supported type or it's been damaged. My Code is below.

    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()

I've been struggling to find any good examples or documentation on this. Any assistance on where I'm going wrong would be appreciated.

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

For anyone having a similar issue I figured it out.

    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()