FOP有3種使用方式,分別為命令行,程序嵌入,XT
嵌入,這裏將主要介紹如何在程序中嵌入FOP功能。將XML文件轉換為PDF實際上分為2步,第1步是利用XSLT將XML轉換為XSL-FO,第2步是
將XSL-FO轉換為PDF。這裏不想講述XSLT和XSL-FO有關的知識(這方面的文檔相當多),而只將講述如何進行第2步的轉換編程。
在程序中嵌入FOP
1. 範例simple.fo文件
<?xml version="1.0" encoding="utf-8"?>
<fo:root xmlns:fo="ame "SimSun" C:\WINNT\Fonts\simsun.ttc simsun.xml
-ttcname後面指定需要從ttc文件中提取的字體名稱
第二步,登記上述字體
在FOP主目錄下的conf子目錄下有壹個userconfig.xml文件,為了方便,我們將它和
上壹步產生的simsun.xml,simkai.xml都拷貝到與我們的演示程序同壹目錄下。在userconfig.xml的最後幾行有壹
個<fonts></fonts>標記區,我們在其中加入以下項:
<font metrics-file="simsun.xml" kerning="yes" embed-file="c:\WINNT\fonts\simsun.ttc">
<font-triplet name="mysimsun" style="normal" weight="normal"/>
</font>
<font metrics-file="simkai.xml" kerning="yes" embed-file="c:\WINNT\fonts\simkai.ttf">
<font-triplet name="mysimkai" style="normal" weight="normal"/>
</font>
其中metrics-file裏可以設相對路徑或絕對路徑(因為我們這裏在同壹目錄下,所以只需寫文件名即可),font-triplet裏的name可以自己自由設定,並不要求與字體名壹樣。設定這個名字後,在fo裏就只能通過這個名字引用這個字體。
為了演示中文顯示,範例simplecn.fo文件為
<?xml version="1.0" encoding="gb2312"?>
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
<fo:layout-master-set>
<fo:simple-page-master master-name="simple"
page-height="29.7cm"
page-width="21cm"
margin-top="1cm"
margin-bottom="2cm"
margin-left="2.5cm"
margin-right="2.5cm">
<fo:region-body margin-top="3cm"/>
<fo:region-before extent="3cm"/>
<fo:region-after extent="1.5cm"/>
</fo:simple-page-master>
</fo:layout-master-set>
<fo:page-sequence master-name="simple">
<fo:flow flow-name="xsl-region-body">
<fo:block font-size="18pt"
font-family="mysimsun"
line-height="24pt"
text-align="center"
padding-top="3pt">
這是宋體
</fo:block>
<fo:block font-size="18pt"
font-family="mysimkai"
line-height="24pt"
text-align="center"
padding-top="3pt">
這是楷體
</fo:block>
</fo:flow>
</fo:page-sequence>
</fo:root>
上述fo文件使用兩種字體分別顯示壹行文字,註意在<fo:block>的屬性中的font-family被我們設成userconfig.xml中相應的名字。
由於需要讀入userconfig.xml來得到字體信息,程序主體修改如下:
Driver driver = new Driver();
driver.setInputSource(new InputSource (args[0]));
driver.setOutputStream(new FileOutputStream(args[1]));
driver.setRenderer(Driver.RENDER_PDF);
//讀入配置(在Options的構造函數中完成)
Options options = new Options(new File("userconfig.xml"));
driver.run();