2010-05-07 33 views
0

背景:PHP和IIS7 C#通信(生成動態PDF)

我找不到在C#中的任何像樣的免費的HTML到PDF轉換工具。 PHP中有100多種文檔,支持和CSS支持。所以我使用html2ps and html2pdf(PHP)。

我在IIS7上安裝了PHP 5.2,它的工作很精美,可以創建PDF。

我在getPDF.aspx

<!-- Output the header --> 
<DM:header runat="server" ID="header" /> 

<asp:Placeholder id="content" runat="server" /> 

<!-- Output the footer --> 
<DM:footer runat="server" ID="footer" /> 

以下和getPDF.aspx.cs

protected void Page_Load(object sender, EventArgs e){ 
    // AddContentControl simples adds a controls to the content Placeholder. 

    AddContentControl("controls/page1.ascx"); 
    AddContentControl("controls/page2.ascx"); 
    AddContentControl("controls/page3.ascx"); 
} 

generatePDF.php

<?php 
    /* ... includes and stuff here ... */ 

    $data = "THE HTML GOES HERE!"; 
    // creates the PDF from the $data and Outputs the created file. 
    convert_to_pdf($data); 
?> 

- getPDF.aspx作品完美...除了輸出是HTML。

那麼,怎樣才能我得到getPDF.aspx才能輸出HTML通過generatePDF.php作爲生成的PDF?

回答

1

我建議你看看iTextSharp iText的一個免費的.NET端口(基於Java的PDF庫)然後,你可以切斷等式。

對於使用iTextSharp請參見轉換HTML This Post(使用谷歌實測值)

更新

在ASP.NET形式渲染局部模板(即渲染單個控制,或與對照頁)您創建一個System.Web.Page來驅動事件結構。

下面是一個代碼示例中,我適合我的一個項目:

public static string Render<T>(string controlPath, Action<T> initControlCallback) where T : Control 
    { 
     Page renderPage = new Page(); 

     // Load the control & add to page 
     T control = (T) renderPage.LoadControl(controlPath); 
     renderPage.Controls.Add(control); 

     // Initialize the control 
     initControlCallback.Invoke(control); 
     renderPage.DataBind(); 

     StringWriter result = new StringWriter(); 
     HttpContext.Current.Server.Execute(renderPage, result, false); // Render Process 
     return result.ToString(); 
    } 

它被稱爲是這樣的:

MyHelper.Render<MyControlBase>("~/SomePath/SomeControl.ascx", p => { p.SomeProperty = "Initializer" }); 

此代碼可能不是你所需要的,但你可以看到你可以使用Server/Page對象來渲染結果,這可能是你應該採用的路線。

+0

我以前實際上使用過iTextSharp,但是我不知道它適用於HTML。字符串「HTML」不在其主頁上。 – 2010-05-07 19:25:02

+0

我已更新了我的答案,並附有示例鏈接。 – Aren 2010-05-07 19:41:34

+0

我正在處理它。現在我的問題是,我試圖呈現控件,然後將其內容寫入PDF。這些控件依賴於自己的Page_Load事件,這些事件在使用control.RenderControl(HtmlTextWriter)時不會被觸發。 – 2010-05-07 19:53:30