2012-03-18 53 views
3

我尝试使用下面的代码生成从我的GridView PDF:iTextSharp的文档没有页

HtmlForm form = new HtmlForm(); 

form.Controls.Add(PGGridViewDetail); 
StringWriter sw = new StringWriter(); 
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw); 
form.Controls[0].RenderControl(hTextWriter); 
string htmlContent = sw.ToString(); 

htmlContent = Regex.Replace(htmlContent, "</?(a|A).*?>", ""); 
htmlContent = Regex.Replace(htmlContent, "px", ""); 

Document document = new Document(); 

// step 2: 
// we create a writer that listens to the document 
// and directs a PDF-stream to a file 
string Path = Server.MapPath("~/Jaram PDF/PDFS/") + "Sample.pdf"; 
PdfWriter.GetInstance(document, 
         new FileStream(Path, FileMode.Create)); 

// step 3: we open the document 
document.Open(); 

// step 4: we add a paragraph to the document 
document.Add(new Paragraph(htmlContent.ToString())); 
System.Xml.XmlTextReader _xmlr = new 
     System.Xml.XmlTextReader(new StringReader(htmlContent)); 
_xmlr.WhitespaceHandling = WhitespaceHandling.None; 
ITextHandler xmlHandler = new ITextHandler(document); 
xmlHandler.Parse(_xmlr); 
//HtmlParser.Parse(document, _xmlr); 

// step 5: we close the document   
document.Close(); 

但它显示网格而不是在新生成的PDF网格的HTML标记。

如果我评论第4步

// step 4: we add a paragraph to the document 
document.Add(new Paragraph(htmlContent.ToString())); 

然后我得到一个没有页的文档。

任何想法我做错了什么?

回答

1

其实,你正在给你写html字符串为PDF。 相反,根据您希望在PDF中显示的网格,将for/foreach循环中的单元添加到PDF中。

例子:

PdfPTable DataTable0 = new PdfPTable(dtCommodities.Rows.Count); 

      Chunk DataHeaderCH01 = new Chunk("Commodity", new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.WHITE)); 
      Phrase dhph01 = new Phrase(); 
      dhph01.Add(DataHeaderCH01); 
      PdfPCell dhcell01 = new PdfPCell(); 
      dhcell01.BackgroundColor = new BaseColor(System.Drawing.Color.FromArgb(80, 124, 209)); 
      dhcell01.AddElement(dhph01); 
      DataTable0.AddCell(dhcell01); 

      for (int i = 0; i < dtCommodities.Rows.Count; i++) 
      { 
       DataTable0.AddCell(new Phrase(dtCommodities.Rows[i]["Code"].ToString(), new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL, BaseColor.BLACK))); 
      } 
DataTable0.HorizontalAlignment = Element.ALIGN_LEFT; 
      DataTable0.WidthPercentage = 100f; 
      myDocument.Add(DataTable0); 

希望它能帮助。 如果它解决了您的问题,请不要忘记加注。 谢谢.. :)