xaisoft
xaisoft

Reputation: 3451

File.WriteAllBytes generates one pdf fine, but multiple pdfs with errors?

I have a loop that goes through some data and generates pdf files. if I generate one pdf by iteself, it works just fine (the pdf opens), but if I create 2 pdf files, the first one will open fine, but the second one will display and error saying the file is corrupt or something similar. Is there something I am doing wrong in the loop with the stream, etc?

foreach (report r reports)
{
      byte[] pdf;
      ReportName = r.ReportName;

      switch (r.ReportId.ToLower())
      {
           case "pdf":
                pdfBuilder = new pdfHelper(candidate, 
                pdfTemplates[(Guid)case_report.TemplateId], r.XMLFieldData, DCFormats,  
                              r.ProjectReportName, dependants, DepCount, SpoCount);
                                            pdf = pdfBuilder.GenerateCasePDF();

           break;


        }
        //Add Bookmarks for each report in candidate
        ChapterCount++;
        ChapterReport = new Chapter(new Paragraph(case_report.ReportName), ChapterCount);
        tDoc.Add(ChapterReport);

        reader = new PdfReader(pdf);
        n = reader.NumberOfPages;

        for (int page = 1; page <= n; page++)
            copy.AddPage(copy.GetImportedPage(reader, page));

        copy.FreeReader(reader);
        reader.Close();
 }
 //Save pdf to folder
 ReportName = null;
 tDoc.Close();

 PubResult = outputStream.ToArray();

 File.WriteAllBytes(string.Format(@"{0}\{1}.pdf", JobRootPath, CaseFileName), PubResult);



  //Reset for next case
  outputStream = new MemoryStream();
  tDoc = new iTextSharp.text.Document();
  copy = new PdfSmartCopy(tDoc, outputStream);
  copy.ViewerPreferences = PdfWriter.PageModeUseOutlines;
  copy.SetFullCompression();
  tDoc.Open();

}

Upvotes: 0

Views: 904

Answers (1)

bdhess
bdhess

Reputation: 648

I'm guessing ChapterCount should get reset to its initial value like all the other variables you're resetting at the end of your for loop.

That aside, I'd recommend moving the body of your for loop, and all related variables, into a new method. Reusing variables tends to lead to errors like this.

Upvotes: 2

Related Questions