Here is my situation, I have a List of data model that will populate a given PDF template into a single big pdf and display on the web page for client to print the file. (no local copy) . I use kuujinbo's example https://stackoverflow.com/a/8525007/5533303 but for some reason i can't let the memory stream to bind when i am going to display the pdf on page. (the error is can't read closed memory stream. ) My system Environment is MVC 5 with the latest itextsharp.
20151107 Updated:Find the reason. Overall code is correct but at the end of loop i should put byteInfo = Masterstream.ToArray(); outside the smartcopy using but inside the document using. and create a new memory string later to crab the byteinfo and return to the view.
List<Datamodel> PrintList = ( List<Datamodel> )Session["GetDAta"];
BaseFont baseChineseFont = BaseFont.CreateFont(@"~~~~~~~~~",
BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
MemoryStream Masterstream = new MemoryStream();
byte[] byteInfo;
using (Document document = new Document())
{
using (PdfSmartCopy copy = new PdfSmartCopy(document, Masterstream))
{
document.Open();
foreach (Datamodel childnode in PrintList)
{
PdfReader pdfReader = new PdfReader(Request.MapPath("~/Content/try 1.pdf"));
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(pdfReader, ms))
{
// do stuff //
AcroFields pdfForm = stamper.AcroFields;
#region[input data]
pdfForm.AddSubstitutionFont(baseChineseFont);//加font
pdfForm.SetField("XXXXXXXX", childnode.XXXXXX);
#endregion
stamper.FormFlattening = true;
}
pdfReader = new PdfReader(ms.ToArray());
copy.AddPage(copy.GetImportedPage(pdfReader, 1));
}
}
byteInfo = Masterstream.ToArray();
}
}
Masterstream.Write(byteInfo, 0, byteInfo.Length);
Masterstream.Position = 0;
return new FileStreamResult(Masterstream, "application/pdf");
correct result
}///smartcopy end using
byteInfo = Masterstream.ToArray();
} //document end using
MemoryStream finalyresult= new MemoryStream(byteInfo);
finalyresult.Write(byteInfo, 0, byteInfo.Length);
finalyresult.Position = 0;
return new FileStreamResult(finalyresult, "application/pdf");