File.WriteAllBytes生成一个pdf罚款,但多个pdf有错误?

时间:2014-05-24 05:25:04

标签: c# asp.net .net pdf-generation itextsharp

我有一个循环,遍历一些数据并生成pdf文件。如果我通过iteself生成一个pdf,它工作正常(pdf打开),但如果我创建2个pdf文件,第一个将打开正常,但第二个将显示和错误说该文件已损坏或类似的东西。我在循环中遇到了一些错误的事情吗?

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

}

1 个答案:

答案 0 :(得分:2)

我猜 ChapterCount 应该像你在for循环结束时重置的所有其他变量一样重置为初始值。

除此之外,我建议将 for 循环的主体以及所有相关变量移动到新方法中。重用变量往往会导致这样的错误。