利用itext生成pdf文件

2021-07-06 11:16:17 字數 1993 閱讀 9977

最近在用itext這一開源庫生成pdf檔案,小有所悟,故寫下。

第一步,建立乙個

itextsharp.text.document

物件的例項:

document document = new document();

第二步,為該

document

建立乙個

writer

例項:

pdfwriter.getinstance(document, new filestream("chap0101.pdf", filemode.create));

第三步,開啟當前

document

document.open();

第四步,為當前

document

新增內容:

document.add(new paragraph("hello world"));

第五步,關閉

document

document.close();

方法一:使用windows系統字型(truetype)

方法二:使用itextasian.jar中的字型

方法三:使用資源字型(classpath)

//方法一:使用windows系統字型(truetype)    

basefont basefont = basefont.createfont("c:/windows/fonts/simyou.ttf",basefont.identity_h,basefont.not_embedded);

//方法二:使用itextasian.jar中的字型

//basefont basefont = basefont.createfont("stsong-light",basefont.identity_h,basefont.not_embedded);

//方法三:使用資源字型(classpath)

basefont basefont = basefont.createfont("/simyou.ttf",basefont.identity_h,basefont.not_embedded);

通常,方法一不會別選用,因為需要系統資源,不確定性太大。

方法二,這種方法雖然能夠正常地顯示中文資訊,但是有乙個缺點,就是只有一種字型。因為itext官方**提供的itextasian.jar包中只包 含幾種簡單的亞洲字型,對於簡體中文來說,只有宋體。因此,採用這種方法生成的pdf中,中文字型只能為宋體,無法顯示其他字型。

所以,還是選擇方法三。選擇方法三,需要注意兩點。

1、對於宋體,需要表示為 "simsun.ttc,1"。2、在生成pdf的時候,程式會從類路徑中查詢這個字型檔案,可以選擇把字型檔案放到類路徑中。

writer.setstrictimagesequence(true);
2、解析度

將生成到pdf裡面結果的dpi 與生成之後pdf 解析度不一樣導致列印出來的不行。

dpi:「dot per inch」的縮寫,就是指在每英吋長度內的點數。在photoshop中文版中可以看到中文解釋是「解析度」的一種表示方式
原本dpi就是96,pdf生成的總是72。
img.scalepercent(75f);
3、縮放

public void scaleabsolute(int newwidth, int newheight)直接設定顯示尺寸

public void scalepercent(int percent)設定顯示比例

public void scalepercent(int percentx, int percenty)根據高寬設定顯示比例

1、鎖定表頭:table.setheaderrows(1);

2、緩解記憶體壓力:table.setcomplete(false);

3、**跨頁顯示:table.setsplitrows(false);

itext生成pdf文件

包 交易金額 datamap.put jine order.getorderprojiectmoney datamap.put jinedaxie stringutil.trans2rmb order.getorderprojiectmoney datamap.put daozhangshijian...

使用iText生成pdf文件

一 建立乙個新pdf文件 1.首先建立乙個文件document document doc new document 也可以設定文件背景,大小等 文件的背景色 rectangle psize new rectangle 144,90 psize.setbackgroundcolor color.blu...

利用PDFLib生成PDF文件

本文 生成的pdf文件效果圖 一 pdf介紹 pdf是portable document format的縮寫,pdf檔案格式是國際通用的電子文件交換事實標準,被許多國家採用作為電子文件交換。pdf檔案可以在各種平台下閱讀 編輯 發布。該檔案格式支援字型 影象 甚至任何附件的嵌入。您可以通過免費的ad...