I a method that generates a PDF and the method returns a byte value, but after response.end statement, the shows an error that the "File does not begin with '%PDF-' here is the code:

private static Byte[] GenerateReports(string templateFilePath, DataTable table, string fileName)
            Byte[] Output = null;
            string FilePath;
                FilePath = Setting.WorkingFolder + "\\GeneratePDF\\" + fileName;
                PdfReader reader = null;
                FileStream output = new FileStream(fileName, FileMode.Create);
                reader = new PdfReader(templateFilePath);

                PdfStamper stamper = null;

                stamper = new PdfStamper(reader, output);

                AcroFields form = stamper.AcroFields;

                if (table.Rows.Count != 0)
                    foreach (DataRow row in table.Rows)

                        form.SetField("mIncome", row["Income"].ToString());
                        form.SetField("mEnter", row["Enterntainment"].ToString());
                        form.SetField("mSav", row["Savings"].ToString());
                        form.SetField("mHealth", row["Health"].ToString());
                        form.SetField("mTrans", row["Transportation"].ToString());
                        form.SetField("mSupplies", row["Daily_Supplies"].ToString());
                        form.SetField("mCharity", row["Charity"].ToString());
                        form.SetField("mObli", row["Obligations"].ToString());
                        form.SetField("mHome", row["Home_expenses"].ToString());
                        form.SetField("mIBal", row["InitialBalance"].ToString());
                        form.SetField("mcBal", row["CurrentExpenses"].ToString());
                        form.SetField("mFbal", row["FinalBalance"].ToString());

                Output = new byte[output.Length];
                output.Write(Output, 0, Convert.ToInt32(output.Length));
                stamper.FormFlattening = true;
            return Output;
public static Byte[] PrintReport(DataTable data)
            return GeneratePDF.GenerateReports(Setting.TemplatePath + "ReportTemplate.pdf", data, "Report.pdf");
Response.ContentType = "application/pdf";
                Response.AddHeader("Content-Desposition", "attachment; filename = Report.pdf");


The problem is the filestream.write reference. Easy mistake to make, the semantics are messed up.


When you say:

output.write(byte[], offset, length)

You are actually asking it to take bytes out of the array and put them into the stream.

What you want is output.read(byte[], offset, length).

While they may end up producing a roughly similar byte array, the results of output.write will be not be correct.

In short

Output = new byte[output.Length];
output.Read(Output, 0, Convert.ToInt32(output.Length));
stamper.FormFlattening = true;