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.
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()
You probably should mention that the main change from your original code is that you now close the stamper before writing the result. This is necessary as during closing the stamper finalizes the pdf.
Please check back in a few days and accept your answer. It will not earn you reps but it will help future readers.