2011-06-29 44 views
0

PDF这是我的控制器类: -错误生成使用iTextSharp的

public class PlantHeadController : Controller 
    { 
     private WOMSEntities2 db = new WOMSEntities2(); 
     // 
     // GET: /PlantHead/ 
     Document doc = new Document(); 
     static String[] tt=new String[20]; 



     public ActionResult Index() 
     { 
      ViewBag.productCode = new SelectList(db.Product, "ID","code"); 


      return View(); 
     } 

     public void Convert() 
     { 



      PdfWriter.GetInstance(doc, new 
      FileStream((Request.PhysicalApplicationPath + "\\Receipt3.pdf"), 
      FileMode.Create)); 
      doc.Open(); 
      PdfPTable table = new PdfPTable(2); 
      doc.AddCreationDate(); 
      PdfPCell cell = new PdfPCell(new Phrase("Receipt")); 
      cell.Colspan = 3; 
      cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right 
      table.AddCell(cell); 

      table.AddCell("ahym"); 
      table.AddCell("ram"; 
      table.AddCell("good"); 
      table.AddCell("morning"); 

      String rawGroup = ""; 
      foreach (String lll in raw) 
       rawGroup = rawGroup + lll+" "; 


      table.AddCell("" + rawGroup); 




      doc.Add(table); 


      doc.Close(); 
      Response.Redirect("~/Receipt3.pdf"); 


      } 


} 

每当我按下提交按钮,使PDF文件,则该错误窗口打开: - enter image description here

意味着PDF是不是成功生成。在某些情况下,会显示旧的pdf。请给我建议我该怎么办?

回答

3

上面大部分内容都看起来不错(除了table.AddCell("ram";上的缺失括号,我认为这只是一个错字,你也可以使用一些using语句)。我不知道为什么你会得到一个错误,但你得到相同的PDF的原因几乎肯定是因为浏览器缓存。你可以附加一个随机查询字符串到文件,但我建议完全跳过该文件,并直接写入二进制流。通过这种方式,您可以控制缓存,而无需使用浏览器重定向。下面的代码应该适用于您(它的定位5.1.1.0取决于您的版本,您可能会或可能不会使用某些using声明)。

编辑

我donwgraded我的代码不使用新版本中发现的IDisposable接口,这应该对你现在的工作。 (我没有访问C#编译器,所以我没有测试它,所以希望这可以工作。)

using (MemoryStream ms = new MemoryStream()) 
    { 

     Document doc = new Document()); 

     PdfWriter writer = PdfWriter.GetInstance(doc, ms)); 

     doc.Open(); 

     doc.AddCreationDate(); 

     PdfPTable table = new PdfPTable(2); 
     PdfPCell cell = new PdfPCell(new Phrase("Receipt")); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right 
     table.AddCell(cell); 

     table.AddCell("ahym"); 
     table.AddCell("ram"); 
     table.AddCell("good"); 
     table.AddCell("morning"); 

     String rawGroup = ""; 
     foreach (String lll in raw) 
     { 
      rawGroup = rawGroup + lll + " "; 
     } 

     table.AddCell("" + rawGroup); 

     doc.Add(table); 
     doc.Close(); 



     Response.Clear(); 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("content-disposition", "attachment;filename=Receipt3.pdf"); 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.BinaryWrite(ms.ToArray()); 
     System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    } 
+0

+1在浏览器问题上。在尝试浏览到PDF文件时,我在许多网站上得到了完全相同的错误....但是,然后右键单击+另存为,它工作正常。 – maciek

+0

使用语句的Sie正在创建错误,请告诉我该怎么做。 –

+0

@Pushpendra Kuntal,我降级了上面的代码,你现在应该可以使用 –