天天看點

使用abcpdf将html轉換成pdf檔案

ABCpdf.NET使用介紹

最新做一個項目需要生成pdf文檔以供列印,研究決定使用abcpdf這款元件,先針對其使用方法做一個簡單的總結介紹以給有需要的朋友做參考。

一、 ABCpdf.NET簡單介紹

  ABCpdf.NET是一個能夠很友善生成pdf的.net元件,能夠運作在以下作業系統中:Windows 2000, Windows XP, Windows Server 2003, Windows Vista, and Windows Server 2008.官方建議運作環境安裝IE6或者以上版本。對應不同的系統,它有32位和64位的版本,使用時注意版本的選用。 ABCpdf的功能比較多,比如可以讀word、excel等檔案,可以儲存pdf、xps、swf等格式檔案。本文主要介紹其生成pdf的方法。使用時,需要ABCpdf.DLL和ABCpdfCE7.DLL支援。其中ABCpdf.DLL(.net調用接口)需要引用到項目中,ABCpdfCE7.DLL(核心驅動)放在ABCpdf.DLL的同一目錄下即可。 ABCpdf的坐标系采用Adobe PDF标準坐标系,原點在螢幕的左下角,采用72DPI(我們用的通常是96DPI,在計算大小時注意轉換,網頁面上的96px相當于ABCpdf裡面72px)

二、 入門,生成第一個pdf檔案

  這一節将通過執行個體來展示如何用ABCpdf.NET生成pdf檔案。在使用前需要引入ABCpdf.DLL,在代碼中引用名空間:using WebSupergoo.ABCpdf7;通常情況下隻需要引入這個名空間就可以了。

Code:    

使用abcpdf将html轉換成pdf檔案
private void GeneratePdfTest1()
        {
            using (Doc theDoc = new Doc())
            {
                theDoc.Rect.Inset(24, 48); //Rect預設是文檔整個頁面大小, 這裡的Inset表示将Rect左右留出24的空白,上下留出48的空白                                
                theDoc.Color.String = "32,48,117";
                theDoc.FrameRect();//為目前rect添加邊框                 
                theDoc.MediaBox.String = "0 0 590 840";//設定添加新頁面時,頁面的大小                
                theDoc.Rect.String = "14 14 576 770";//目前輸出區間                 
                theDoc.Color.String = "192,48,117";
                theDoc.FrameRect();
                theDoc.FontSize = 12;
                theDoc.AddText("Hello World");
                theDoc.Font = theDoc.AddFont("宋體", "ChineseS");
                theDoc.FontSize = 16;
                theDoc.Flatten();//合并pdf各個layer,減少pdf大小                 
                theDoc.Save(Server.MapPath("simple.pdf"));
                theDoc.Clear();
            }
        }       
使用abcpdf将html轉換成pdf檔案

上面的代碼可以簡單的生成一個pdf檔案。

三、 進階,控制生成的pdf

  上面的代碼隻是簡單的生成了一個pdf,很多細節問題都沒有說明,現在将介紹如何控制生成的pdf和介紹一些有用的方法。比如頁面的大小、字型、添加的内容位置等。 WebSupergoo.ABCpdf7.Doc類有很多屬性和方法可以利用,這裡我們就要用到:

1. SetInfo方法 virtual void SetInfo(int id, string type, string value) 用來擷取或者改變pdf頁面各對象的外觀情況,id通過getinfo方法可以擷取。 e.g.預設的pdf頁面大小是a4頁面大小,可以用這個方法來改變目前頁面的大小。 theDoc.SetInfo(theDoc.Page, "/MediaBox:Rect", "0 0 200 300");

2. Rect屬性 這是一個很重要的屬性,abcpdf裡面生成pdf的基本思路就是先确定一個rect再向該rect裡裡面添加内容,所有的pdf對象都依賴rect,用rect來定位的。 e.g.在指定位置添加文字。 theDoc.Rect.String = "14 14 576 770"; theDoc.AddText("Hello World"); 當然,可以在添加文字前設定字型和顔色等資訊: theDoc.Font = theDoc.AddFont("宋體", "ChineseS"); theDoc.FontSize = 12; theDoc.Color.String = "192,48,117";

3. MediaBox屬性 設定MediaBox屬性隻會影響後面添加的頁面大小,後面添加的頁面大小将會是MediaBox設定的大小。它不會影響已存在的頁面大小。改變已存在頁面大小用setinfo方法。

4. Layer屬性 擷取或設定目前層,和html的層是一樣的,前面的層會覆寫後面的層。預設的Layer為1,在最前面。

AddHtml添加html代碼(将會被解析,但此方法不支援css)支援以下html标記:

<Head> <Body>

<BR> <P> <H1> to <H6> <List>

<UL> <OL> <LI> <A> <B>

<I> <U> <Strike> <Sup> <Sub>

<Font> <StyleRun> <BlockQuote>

<Pre> e.g.Code: Doc theDoc = new Doc(); theDoc.FontSize = 72; theDoc.AddHtml("<b>Gallia</b> est omnis divisa in partes tres, quarum unam incolunt <b>Belgae</b>, aliam <b>Aquitani</b>, tertiam qui ipsorum lingua <b>Celtae</b>, nostra <b>Galli</b> appellantur."); theDoc.Save(Server.MapPath("docaddhtml.pdf")); theDoc.Clear();

5. AddImageHtml方法 virtual int AddImageHtml(string html) virtual int AddImageHtml(string html, bool paged, int width, bool disableCache) html 需要添加的html paged 是否分頁,true啟用分頁 width 頁面的寬度(浏覽器解析html時浏覽器的寬度) disableCache 是否忽略緩存,true不啟用緩存,false啟用緩存,緩存時間5分鐘 return 傳回添加的html對象id 說明:這個方法和AddImageUrl基本上是一樣的,隻不過這個直接用的html,AddImageUrl用的是url位址。這個方法将用傳入的html生成一個臨時檔案,然後解析該臨時檔案來為pdf添加相關内容。這個是一個很簡單的方法,它不提供任何性能上的提升。如果是在asp.net中使用,需要IIS擁有對臨時檔案夾的完全通路權限,否則将會出現錯誤。如果html内含有外部的樣式和圖檔,則需要用絕對位址,因為傳入的html沒有具體的位址,将會無法解析其包含的相對位址。如果必須用相對位址,請用AddImageUrl方法。 e.g.Code: Doc theDoc = new Doc(); using (StreamReader sReader = new StreamReader(Server.MapPath("s.html"))) { theDoc.AddImageHtml(sReader.ReadToEnd(),true,760,true); }

6. AddImageUrl方法 virtual int AddImageUrl(string url) virtual int AddImageUrl(string url, bool paged, int width, bool disableCache) 參數說明同上,隻不過是将html換成了url。 說明:通過這個方法可以很友善的将一個web page添加到pdf檔案,其解析web page用的是ie的核心(版本估計和機器上安裝的版本相關,有興趣可以利用css測試一下)。值得注意的一個問題是pdf的dpi是72,通常html的dpi是96,是以如果要pdf上顯示的和浏覽器上看到的一樣大,那麼在設定rect大小(會填滿所設定的rect)的時候需要用width參數乘以72/96。

 e.g.Code:

 Doc theDoc = new Doc();

theDoc.AddImageUrl("http://www.google.com/");

theDoc.Save(Server.MapPath("htmlimport.pdf"));

 theDoc.Clear();

四、 進階,如何分頁

在利用html轉pdf的時候,通常都會遇到的問題。abcpdf會進行智能的分頁,而分頁的實作也隻需要幾行代碼。

int theID = theDoc.AddImageUrl("http://localhost:1141/WebSitePDF/000001.OF.html", true, 760, true); //以下實作多頁效果

while (true) {     

theDoc.FrameRect();//畫Rect的邊框     

if (!theDoc.Chainable(theID))        

break;     

theDoc.Page = theDoc.AddPage();     

theID = theDoc.AddImageToChain(theID);

 } 如果需要在分頁時不對子產品進行截斷,請為相應子產品添加列印樣式“page-break-inside: avoid”如果需要在指定位置進行強制分頁,請添加:“<div style="page-break-before:always">&nbsp;</div>”其中“&nbsp;”是必須要的。經過我的實驗此強制分頁标記并不是任何時候都分頁的,用之前注意針對指定的html代碼進行測試。推薦用自動分頁+保證子產品完整性樣式。 對于需要設定頁眉和頁腳的,也很簡便,隻要将頁面分成三個rect(頁眉,頁腳,中間内容),分頁的時候将内容添加到中間的rect,分頁完畢後再分别補充頁面,頁腳。

 e.g.Code:

theDoc.Rect.String = "14 35 576 803";

int theID = theDoc.AddImageUrl(url, true, 760, true); //以下實作多頁效果

while (true)

{

if (!theDoc.Chainable(theID))

   break;

theDoc.Page = theDoc.AddPage();

theID = theDoc.AddImageToChain(theID);

}

for (int i = 1; i <= theDoc.PageCount; i++)

{

theDoc.PageNumber = i; 表頭

theDoc.Rect.String = "14 803 576 835";

theDoc.AddImageUrl(urlTop, false, 760, true); 表尾

theDoc.Rect.String = "14 35 576 5";

theDoc.AddImageUrl(urlBottom, false, 760, true);

}

五、 運作js,js支援 abcpdf支援html頁面腳本JavaScript,這讓我們利用html生成pdf時多了一個利器,可以通過js改變html,再生成pdf。如何執行頁面上的js呢?下面将介紹幾個相關的屬性。注意這個受運作機器浏覽器安全設定限制,如果浏覽器安全級别很高或者限制了js的運作,在調用js的時候将會報錯:Unable to apply JScript Windows error 5. Access is denied.

1. theDoc.HtmlOptions.UseScript 是否啟用腳本,預設為false不啟用

2. theDoc.HtmlOptions.OnLoadScript 當啟用腳本時,頁面載入後執行的腳本,可以是一段js代碼,也可以是html頁面包含函數方法

3. theDoc.HtmlOptions.HostWebBrowser 是否啟用WebBrowser,預設為false不啟用。隻有在啟用了WebBrowser後,left, top, width, height, offsetLeft, offsetTop, offsetWidth, offsetHeight, clientLeft, clientTop, clientWidth, clientHeight, pixelLeft, pixelTop, pixelWidth, pixelHeight, posLeft, posTop, posWidth, and posHeight這些dom方法才可用,否則都是0。在啟用WebBrowser後,還可以用用xml,xslt。

e.g.Code:

theDoc.HtmlOptions.UseScript = true;

theDoc.HtmlOptions.HostWebBrowser = true;

theDoc.HtmlOptions.OnLoadScript ="var divs=document.getElementById('content').childNodes;if(divs[0].scrollHeight<divs[1].scrollHeight)divs[0].style.height=divs[1].scrollHeight;";

六、 關于程式釋出注冊 對于釋出程式,需要在建立doc對象前注冊一些該元件的key,如下: XSettings.InstallRedistributionLicense(" 注冊碼"); Doc doc = new Doc(); Response.Write("License: " + doc.License + "<br>"); 或者 Doc theDoc = new Doc(); // here we use a trial license key as copied from the PDFSettings application theDoc.SetInfo(0, "License", "cd9b5c07db69df2bf57c0a04d9bca58b10c44889c9fb197984e592f49addfce5ec5fe85d7b9205bc"); Response.Write(theDoc.GetInfo(0, "License")); 在程式引入的dll版本要和打包的版本一緻,否則會出現找不到xx版本dll的錯誤,編譯時将dll的版本号也包含進去了,大概是因為該dll是強命名的原因。

繼續閱讀