2011-09-30 204 views
0

我試圖通過生成基於HTML的PDF來創建「報告」。HTML to PDF解決方案(處理內容,頁眉和頁腳)

起初,我只是試圖將原始編碼的HTML寫入文檔,然後使用Javascript打印該文檔。然而,這讓我很少無法控制頁眉和頁腳。

我試圖使用theadtfoot元素,這在大多數瀏覽器中都能很好地工作,但是我無法獲得我正在尋找的格式。

當前 - 我正在嘗試在MVC3中使用iTextSharp的服務器端解決方案,但是我對如何繼續工作有點遺憾,沒有與iTextSharp一起工作過。

輸入和輸出的描述:

會有在創建報告使用的4個項目:

  • 報告內容(這是目前編碼的HTML,因爲我不能確定,如果解碼將改變任何格式)
  • 報告標題(將簡單地t他生成的PDF)的名稱
  • 報告標題(將顯示在左上角每一頁)
  • 報表頁腳(將在左下每個頁面的顯示)

控制器動作:

//This will be accessed by a jQuery Post 
[HttpPost] 
public FileStreamResult GeneratePDF(string id) 
{ 
     //Grab Report Item 
     ReportClass report = reportingAgent.GetReportById(id); 

     Document doc = new Document(); 

     //Do I need to decode the HTML or is it possible to use the encoded HTML? 

     //Adding Headers/Footers 

     //Best method of returning the PDF? 
} 

回答

2

iTextSharp無法將HTML轉換爲PDF。這不是它設計的目的。它旨在從頭開始創建PDF文件,而不是將各種格式轉換爲PDF。如果您想將HTML轉換爲PDF,您可以使用基於iTextflying-saucer庫。我有blogged關於如何在.NET中使用IKVM.NET Bytecode Compiler (ikvmc.exe)來完成此操作。

所以你的控制器動作看起來可能沿着線:

[HttpPost] 
public FileStreamResult GeneratePDF(string id) 
{ 
    ReportClass report = reportingAgent.GetReportById(id); 
    return PdfResult(report.Html); 
} 

其中PdfResult可能是一個自定義操作結果以原始HTML和PDF輸出爲響應流:

public class PdfResult : ActionResult 
{ 
    private readonly string _html; 
    public PdfResult(string html) 
    { 
     _html = html; 
    } 

    public override void ExecuteResult(ControllerContext context) 
    { 
     var response = context.HttpContext.Response; 
     response.ContentType = "application/pdf"; 
     var builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
     using (var bais = new ByteArrayInputStream(Encoding.UTF8.GetBytes(_html))) 
     using (var bao = new ByteArrayOutputStream()) 
     { 
      var doc = builder.parse(bais); 
      var renderer = new ITextRenderer(); 
      renderer.setDocument(doc, null); 
      renderer.layout(); 
      renderer.createPDF(bao); 
      var buffer = bao.toByteArray(); 
      response.OutputStream.Write(buffer, 0, buffer.Length); 
     } 
    } 
} 
+0

謝謝達林 - 我會研究飛碟。爲工作找到合適的工具總是更好。 –

+0

@Rionmonster,它只是我在生產應用程序中成功使用的一種工具。可能還有其他的替代品,包括商業組件。 –

+0

你有什麼工具可以推薦你將飛碟庫移植到.NET上(如你的博客中提到的) –