2016-03-09 77 views
0

我怎樣才能在文檔中平行設置兩個表 enter image description here如何在itextsharp文檔中並行設置兩個表格?

用於生成PDF是我的示例代碼,

  Document doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10); 
     doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate()); 

     PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream); 

     doc.Open(); 

     PdfPTable table = new PdfPTable(3); 
     table.TotalWidth = 144f; 
     table.LockedWidth = true; 
     PdfPCell cell = new PdfPCell(new Phrase("This is table 1")); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; 
     table.AddCell(cell); 
     table.AddCell("Col 1 Row 1"); 
     table.AddCell("Col 2 Row 1"); 
     table.AddCell("Col 3 Row 1"); 
     table.AddCell("Col 1 Row 2"); 
     table.AddCell("Col 2 Row 2"); 
     table.AddCell("Col 3 Row 2"); 
     table.WriteSelectedRows(0, -1, doc.Left, doc.Top, writer.DirectContent); 


     table = new PdfPTable(3); 
     table.TotalWidth = 144f; 
     table.LockedWidth = true; 
     cell = new PdfPCell(new Phrase("This is table 2")); 
     cell.Colspan = 3; 
     cell.HorizontalAlignment = 1; 
     table.AddCell(cell); 
     table.AddCell("Col 1 Row 1"); 
     table.AddCell("Col 2 Row 1"); 
     table.AddCell("Col 3 Row 1"); 
     table.AddCell("Col 1 Row 2"); 
     table.AddCell("Col 2 Row 2"); 
     table.AddCell("Col 3 Row 2"); 
     table.WriteSelectedRows(0, -1, doc.Left + 200, doc.Top, writer.DirectContent); 
     doc.Close(); 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("content-disposition", "attachment;" + "filename=Sample .pdf"); 
     Response.Cache.SetCacheability(HttpCacheability.NoCache); 
     Response.Write(doc); 
     Response.End(); 

當運行這段代碼,PDF格式下載,但表示無法載入PDF文件的錯誤消息」 「。請幫我解決錯誤並獲得預期的輸出

回答

2

代碼中有許多問題。立即可見的那些:

  • 你不關閉文檔doc,但只在收盤時創建的PDF的某些重要組成部分,特別是交叉引用表。因此,您必須在完成其內容後儘快關閉文檔。

  • 您嘗試將doc寫入響應

    Response.Write(doc); 
    

    這是不對的,你要指揮你PdfWriter的輸出響應。你真正做到這一點,也有種嘗試重複發送PDF:

    PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream); 
    

    但是:

  • 您更改響應特性後開始寫的響應,即首先要創建一個PDF將其流式傳輸到Response.OutputStream,之後才更改內容類型,內容處置和緩存標頭。

    這很有可能會使Response忽略您的設置,或者忘記到目前爲止流入的設置。

直到你有固定的這些問題,我建議你創建一個簡單的的HelloWorld PDF,而不是你的平行表,不必在使用Web服務類的像Response與交融在PDF生成的問題和存在的問題彼此。

相關問題