2011-06-13 145 views
3

我正在使用以下代碼使用iTextSharp.text將html寫入pdf。Html寫入pdf的格式不正確

但我的PDF格式的文件格式不是他們在HTML中顯示。設計不適當。

我該怎麼做才能在pdf中顯示正確的設計?

Document document = new Document(PageSize.A4_LANDSCAPE, 0, 0, 30, 65); 
PdfWriter.GetInstance(document, new FileStream(Server.MapPath("/") + "Temp/" + "parsetest1.pdf", FileMode.Create)); 
document.Open(); 
String htmlText = "<div style='margin: 20px auto; width: 300px; font-family: Arial, Helvetica, sans-serif;'><div style='background: rgb(216, 216, 216); padding: 7px;'><div style='background: rgb(255, 255, 255); padding: 10px; width: 57px; float: left;'><img alt='barcode' src='images/abc.png'></div><div style='width: 7px; height: 7px; float: left;'></div>   <div style='width: 166px; float: right;'><div style='background: rgb(255, 255, 255); padding: 10px;' align='center'><img alt='img' src='images/photpath.png'><div style='clear: both;'></div></div><div style='background: rgb(255, 255, 255); padding: 10px; margin-top: 7px;' align='center'><div style='color: rgb(157, 157, 157); font-size: 12px; float: left;'>Name</div><div style='width: 146px; text-align: center; color: rgb(0, 0, 0); clear: both; font-size: 14px; margin-top: 10px; float: left;' align='center'><strong>dalvirsaini</strong></div><div style='clear: both;'></div></div><div style='background: rgb(255, 255, 255); padding: 10px; margin-top: 7px;' align='center'><div style='color: rgb(157, 157, 157); font-size: 12px; float: left;'>Description</div><div style='width: 146px; text-align: center; color: rgb(0, 0, 0); clear: both; font-size: 14px; margin-top: 10px; float: left;' align='center'><strong>Payment Status</strong></div><div style='clear: both;'></div></div><div style='background: rgb(255, 255, 255); padding: 10px; height: 89px; margin-top: 7px;' align='center'><img alt='ScanCode' src='images/abc2.png'><div style='clear: both;'></div></div><div style='clear: both;'></div></div><div style='clear: both;'></div></div><div style='clear: both;'></div></div>"; 
StringReader abc = new StringReader(htmlText); 
List<iTextSharp.text.IElement> elements = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(abc, null); 
foreach (object item in elements) 
{ 
    document.Add((IElement)item); 
} 
document.Close(); 
+1

你的HTML是無效的完全形成HTML - 有效的HTML有從HTML標籤開始。嘗試使用簡單有效的HTML作爲初學者。 – 2011-06-13 10:18:46

+0

你找到了解決辦法嗎? – Armance 2011-07-08 08:57:55

回答

2

HTMLWorker已棄用。並有很好的理由。它不支持全套HTML和CSS結構,並且沒有積極努力更新其功能。

我建議你試試PDFHTML,最新的iText解決方案將HTML轉換爲PDF,它支持HTML5和CSS3。

一個小的代碼示例:

// IO 
String html = "your_html_snippet"; 
File pdfDest = new File(System.getProperty("user.home"), "output.pdf"); 

// pdfHTML specific code 
ConverterProperties converterProperties = new ConverterProperties(); 
HtmlConverter.convertToPdf(html, new FileOutputStream(pdfDest), converterProperties); 

檢查出iText的網站,瞭解詳情: