选择显示字体大小

转换html内容为pdf格式

为网页提供pdf文件支持

概要

在这篇文章里,nick afshartous描述了一种把html的内容转换为pdf格式的方法。这种方法相当有用,比如说,一个web程序可以在它的页面上提供如“下载为pdf”的功能。这种功能方便了打印和储存,以供日后使用。afshartous的转换方法只使用开源的组件。也有一些商业产品可供使用。因此,在这篇文章里描述的这种方法既在价格上可以承担,又能够获得所用组件的源码。

把网页内容以pdf的格式呈献有利于内容的传播。在一些应用中,提供格式便于打印的文档是一个必需的功能,比如员工利益表等。事实上,法律规定summmary plan descriptions(spds)必须能够打印,即使它们是在线提供的也是如此。然而只打印网页本身是不够的,因为打印格式必包含表格内容和页码。

为了提供这样的功能,开发人员可以把html内容转换为pdf格式。在此即做介绍。这里介绍的这种方法只使用开源组件。一些商业产品也支持动态的文档生成,比如说adobe,它有document server产品线。但是,使用商业产品的开销是相当可观的。使用开源方案可以缓解开销的问题,并增加了组件源码的透明度。

转换过程包含以下三步:
1.把html转换为xhtml;
2.把xhtml转换为xsl-fo(extensible stylesheet language formatting objects扩展样式表语言格式化对象)。这里使用xsl样式表和xslt转换器;
3.把xsl-fo文档传递给格式化程序来生成目标pdf文档。

本文先介绍怎样用命令行界面来做这种转换,然后介绍怎样在java中使用dom接口来做同样的工作。

组件版本:
本文中的代码在以下版本中进行了测试
组件     版本
jdk     1.5_06
jtidy    r7-dev
xalan-j  2.7
fop     0.20.5

版权声明:任何获得matrix授权的网站,转载时请务必保留以下作者信息和链接
作者:nick afshartous;rainy14f(作者的blog:http://blog.matrix.org.cn/page/rainy14f)
原文:http://www.javaworld.com/javaworld/jw-04-2006/jw-0410-html.html
matrix:http://www.matrix.org.cn/resource/article/44/44489_html+pdf.html
关键字:html;pdf


使用命令行界面

在转换过程中的每一步都包含了从一个输入文件生成输出文件的过程。这个过程可以用下图来表示:



使用这三个工具的命令行界面开始我们的工作是个好方法,尽管这种方法并不适合产品级的系统,因为它需要往磁盘中写入临时的中间文件。这种额外的i/o会导致性能的降低。稍后,在我们用java来调用这三个工具时,这个问题就会得到解决。

第一步:转换html为xhtml

第一步就是把html转换为一个新的xhtml文件。当然,如果文件本来已经就是xhtml,那就不需要这一步了。

我用jtidy来完成这个转换。jtidy是tidy html解析器的java版本。在转换的过程中,jtidy会自动添加缺少的标签来创建格式良好(well-formed)的xml文档。我用的是在sourceforge上的最新版本r7-dev。

可以用以下的脚本来运行jtidy:
#/bin/sh
java -classpath lib/tidy.jar org.w3c.tidy.tidy -asxml $1 >$2


此脚本设置了classpath并调用了jtidy。运行时,要输入的文件是以命令行参数的形式传给jtidy。默认情况下,生成的xhtml将被输出到标准输出设备。-modify开关可以用来覆写输入文件。-asxml开关把jtidy的输出重定向到格式良好的xml

调用时像这样:
tidy.sh hello.html hello.xml

hello.html(输入)和hello.xml(输出)的内容如下:




<p>hello world!</p>
是jtidy自动添加的&#91;译注1&#93;。


第二步:转换xhtml为xsl-fo&#91;译注2&#93;

下面,xhtml将被转换为xsl-fo,一种用来为xml文档指定打印格式的语言。我通过用xslt转换器(apache xalan)处理xsl样式表来完成这个转换。我使用的样式表是由antenna house提供的xhtml2fo.xsl。antenna house是一个出售xsl-fo上商用格式程序的公司。

xhtml2fo.xsl样式表指定了如何把每个html标签翻译成相应的xsl-fo格式化命令序列。举例来说,html中的h2标签在翻译中被定义为:

&#91;code&#93;    <xsl:template match=&quot;html:h2&quot;>
      <fo:block xsl:use-attribute-sets=&quot;h2&quot;>
        <xsl:call-template name=&quot;process-common-attributes-and-children&quot;/>
      </fo:block>
    </xsl:template>


在处理的过程中,每次遇到h2标签,以上xslt模板都会被调用。html:前缀表明h2标签是html的命名空间(namespace)。样式表的命名空间在顶层xsl:stylesheet指示符的属性中被指定。在xhtml2fo.xsl的最顶层,我们可以看到它指定了三个命名空间,分别对应于xsl,xsl-fo和html语言。

    <xsl:stylesheet version=&quot;1.0&quot;
                    xmlns:xsl=&quot;http://www.w3.org/1999/xsl/transform&quot;
                    xmlns:fo=&quot;http://www.w3.org/1999/xsl/format&quot;
                    xmlns:html=&quot;http://www.w3.org/1999/xhtml&quot;>...


模板中的第二行

    
<fo:block xsl:use-attribute-sets=&quot;h2&quot;>


致使fo:block标签被输出,并且h2的属性被生成为fo:block标签的属性和值。每个xsl-fo块(block)都是一段文字,它们的格式基于块的属性的值。

h2的属性在样式表中被定义为:

    <xsl:attribute-set name=&quot;h2&quot;>
        <xsl:attribute name=&quot;start-indent&quot;>10mm
        <xsl:attribute name=&quot;end-indent&quot;>10mm
        <xsl:attribute name=&quot;space-before&quot;>1em
        <xsl:attribute name=&quot;space-after&quot;>0.5em
        <xsl:attribute name=&quot;font-size&quot;>x-large
        <xsl:attribute name=&quot;font-weight&quot;>bold
        <xsl:attribute name=&quot;color&quot;>black
   </xsl:attribute-set>


start-indent及其后的属性用来指定h2块的格式化后的外观。当你想改变pdf文档中用同样html标签的文字块的外观时,使用属性集可以使这种改变更加容易。只要改动属性的设置,那么输出的文件中所有使用这些属性的地方都会被改动。

下一个指示符调用一个名为&quot;process-common-attributes-and-children&quot;的模板:

    
<xsl:call-template name=&quot;process-common-attributes-and-children&quot;/>


这个模板在样式表中被指定。它的作用是检查一些普通的html属性(如lang,id,align,valign,style)并生成相应的xsl-fo指示符。要触发对嵌在顶层h2标签中的任意标签的翻译,process-common-attributes-and-children会调用:

    
<xsl:apply-templates/>


因此,如果输入是

    
<h2> hello <em> there </em> </h2>


那么在h2的模板中的<xsl:apply-templates/>就会触发用来翻译<em>标签的模板。

翻译h2标签的输出是:

    <fo:block start-indent=&quot;10mm&quot; ...
        original h2 tag content
      </fo:block>


我们调用xalan来应用xhtml2fo.xsl。在调用xalan之前,用unix脚本xalan.sh来设置它需要用到的classpath变量。

#/bin/sh

export classpath='.;./lib/xalan.jar;./lib/xercesimpl.jar;./lib/xml-apis.jar;lib/serializer.jar'

java -classpath $classpath org.apache.xalan.xslt.process -in $1 -xsl xhtml2fo.xsl -out $2 -tt


因为xalan需要一个xml解析器,所以这里还需要apache xerces和xml-api jars。所有的jar文件都可以在xalan的发布包中找到。

要通过对xhtml应用样式表来新建一个xsl-fo文件,可以调用脚本:

    xalan.sh  hello.xml hello.fo

我喜欢用xalan的跟踪开关(-tt)来显示应用的模板。hello.fo文件如下:

<?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?>

<fo:root xmlns:fo=&quot;http://www.w3.org/1999/xsl/format&quot;
    xmlns:html=&quot;http://www.w3.org/1999/xhtml&quot;
    writing-mode=&quot;lr-tb&quot;
    hyphenate=&quot;false&quot;
    text-align=&quot;start&quot;
    role=&quot;html:html&quot;>

  <fo:layout-master-set>
    <fo:simple-page-master page-width=&quot;auto&quot; page-height=&quot;auto&quot;
                           master-name=&quot;all-pages&quot;>
      <fo:region-body column-gap=&quot;12pt&quot; column-count=&quot;1&quot; margin-left=&quot;1in&quot;
                      margin-bottom=&quot;1in&quot; margin-right=&quot;1in&quot; margin-top=&quot;1in&quot;/>
      <fo:region-before display-align=&quot;before&quot; extent=&quot;1in&quot;
                        region-name=&quot;page-header&quot;/>
      <fo:region-after display-align=&quot;after&quot; extent=&quot;1in&quot;
                      region-name=&quot;page-footer&quot;/>
      <fo:region-start extent=&quot;1in&quot;/>
      <fo:region-end extent=&quot;1in&quot;/>
    </fo:simple-page-master>
  </fo:layout-master-set>

  <fo:page-sequence master-reference=&quot;all-pages&quot;>
    <fo:title>hello world
    <fo:static-content flow-name=&quot;page-header&quot;>
      <fo:block font-size=&quot;small&quot; text-align=&quot;center&quot; space-before=&quot;0.5in&quot;
                space-before.conditionality=;&quot;retain&quot;>
        hello world
      </fo:block>
    </fo:static-content>

    <fo:static-content flow-name=&quot;page-footer&quot;>
      <fo:block font-size=&quot;small&quot; text-align=&quot;center&quot; space-after=&quot;0.5in&quot;
                space-after.conditionality=quot;retain&quot;>
        - <fo:page-number/> -
      </fo:block>
    </fo:static-content>

    <fo:flow flow-name=&quot;xsl-region-body&quot;>
      <fo:block role=&quot;html:body&quot;>
        <fo:block space-before=&quot;1em&quot; space-after=&quot;1em&quot; role=&quot;html:p&quot;>
          hello world!
        </fo:block>
      </fo:block>
    </fo:flow>

  </fo:page-sequence>

</fo:root>



第三步:xsl-fo到pdf

第三步,也就是最后一步,就是把xsl-fo文档传递给格式化程序来生成pdf。我用的是apache fop(formatting objects processor)。fop部分实现了xsl-fo标准,并对pdf的输出格式提供了最好的支持。而对postscript还处于初级阶段,对微软的rtf的支持还在计划中。fop发布版包含shell脚本fop.sh/fop.bat,它们需要传入xsl-fo文件作为输入参数来生成目标pdf文件。

unix下可以这样运行:

    fop.sh hello.fo hello.pdf

唯一所需的前提条件就是把设置为这个脚本使用到的fop目录设置环境变量。

文件hello.pdf即为fop的输出,你在本文的源代码中可以找到。

因为fop目前并未完全实现xsl-fo标准,所以有一定的局限性。具体它实现了标准的哪些子集,可以在fop的网站上的compliance部分找到详细说明。

java 程序

通过使用上述步骤中用过的三个工具的dom api,我接下来会展示一个java程序。它在运行时需要提供两个命令行参数,会自动生成相应的pdf文档,并且不会产生任何临时文件。

第一个程序新建一个html文件的inputstream对象,然后此对象被传给jtidy。

jtidy有个方法叫parsedom(),可以用来生成输出的xhtml文档的document对象。

    public static void main(string&#91;&#93; args) {

    // 打开文件
    if (args.length != 2) {
        system.out.println(&quot;usage: html2pdf htmlfile stylesheet&quot;);
        system.exit(1);
    }

    fileinputstream input = null;
    string htmlfilename = args&#91;0&#93;;
    try {
        input = new fileinputstream(htmlfilename);
    }
    catch (java.io.filenotfoundexception e) {
        system.out.println(&quot;file not found: &quot; + htmlfilename);
    }

        tidy tidy = new tidy();
    document xmldoc = tidy.parsedom(input, null);


jtidy的dom实现并不支持xml命名空间。因此,我们必需修改antenna house的样式表,让它使用默认的命名空间。比如,原来是:

    <xsl:template match=&quot;html:h2&quot;>
      <fo:block xsl:use-attribute-sets=&quot;h2&quot;>
        <xsl:call-template name=&quot;process-common-attributes-and-children&quot;/>
      </fo:block>
    </xsl:template>


被修改后是:

    <xsl:template match=&quot;h2&quot;>
      <fo:block xsl:use-attribute-sets=&quot;h2&quot;>
        <xsl:call-template name=&quot;process-common-attributes-and-children&quot;/>
      </fo:block>
    </xsl:template>


这个改动必需被应用到xhtml2f0.xsl中的所有模板,因为jtidy生成的document对象以标签作为根,如:



修改后的xhtml2fo.xsl包含在这篇文章附带的源代码中。

接着,xml2fo()方法调用xalan,使样式表应用于jtidy生成的dom对象:

    document fodoc = xml2fo(xmldoc, args&#91;1&#93;);  


方法xml2fo()首先调用gettransformer()来获得一个指定的样式表的transformer对象。然后,代表着转换结果的那个document被返回:

    private static document xml2fo(document xml, string stylesheet) {

    domsource xmldomsource = new domsource(xml);
          domresult domresult = new domresult();

    transformer transformer = gettransformer(stylesheet);

    if (transformer == null) {
        system.out.println(&quot;error creating transformer for &quot; + stylesheet);
        system.exit(1);
    }
    try {
        transformer.transform(xmldomsource, domresult);
    }
    catch (javax.xml.transform.transformerexception e) {
        return null;
    }
    return (document) domresult.getnode();

    }


接着,main方法用与html输入文件相同的前缀来打开一个fileoutputstream。然后调用fo2pdf()方法所获得的结果被写入outputstream:

    string pdffilename = htmlfilename.substring(0, htmlfilename.indexof(&quot;.&quot;)) + &quot;.pdf&quot;;
    try {
        outputstream pdf = new fileoutputstream(new file(pdffilename));
        pdf.write(fo2pdf(fodoc));
    }
    catch (java.io.filenotfoundexception e) {
        system.out.println(&quot;error creating pdf: &quot; + pdffilename);
    }
    catch (java.io.ioexception e) {
        system.out.println(&quot;error writing pdf: &quot; + pdffilename);
    }


方法fo2pdf()会使用在转换中产生的xsl-fo document和一个bytearrayoutputstream来生成一个fop driver对象。通过调用driver.run可以生成pdf文件。结果被作为一个byte array返回:

    private static byte&#91;&#93; fo2pdf(document fodocument) {

        documentinputsource fopinputsource = new documentinputsource(
                                                         fodocument);

        try {

            bytearrayoutputstream out = new bytearrayoutputstream();
            logger log = new consolelogger(consolelogger.level_warn);

            driver driver = new driver(fopinputsource, out);
            driver.setlogger(log);
            driver.setrenderer(driver.render_pdf);
            driver.run();

            return out.tobytearray();

        } catch (exception ex) {
            return null;
        }
    }


html2pdf.java的源代码可以在这篇文章的附带代码中找到。

使用dom api来完成这整个过程,速度要比使用命令行界面快得多,因为它不需要往磁盘中写入任何中间文件。这种方法可以集成到服务器里,来处理并发的html-pdf转换请求。

以前我曾以这里展示的这个程序为基础把生成pdf的功能集成到一个web应用。而生成pdf的过程是动态的,因此不需要考虑web页面和相应pdf同步的问题,因为生成的pdf文件并不是存放在服务器上。

结论

综述,在本文里我描述了怎样利用开源组件来实现html到pdf的转换。虽然这种实现方法在价格和源码方面很有吸引力,但同时也有一定的折衷。一些商业组件可以提供更完整的标准实现。

比如说,fop目前的版本是.91,不完全支持xsl-fo标准。尽管如此,相对其它的格式而言,对pdf提供了更多的支持。

在开始一个文档转换的项目之前,你必需考虑对文档格式的需求,并把它们与已有组件所实现的功能做个对比。这将有助于做出正确的决定。

资源

# 下载本文中的源码:http://www.javaworld.com/javaworld/jw-04-2006/html/jw-0410-html.zip
# adobe's document server 产品:http://www.adobe.com/products/server/documentserver/main.html
# antenna house (出售商业的格式化程序):http://www.antennahouse.com
# xhtml2fo.xsl 把 xhtml 转化为 xsl-fo 的样式表:http://www.antennahouse.com/xslsample/xslsample.htm
# apache fop formatter 把 xsl-fo 翻译为 pdf:http://xmlgraphics.apache.org/fop
# fop 对 xsl-fo 标准的兼容性:http://xmlgraphics.apache.org/fop/compliance.html
# jtidy,把 html 转化为 xhtml:http://sourceforge.net/projects/jtidy/
# xalan:http://xalan.apache.org/
# matrix:http://www.matrix.org.cn

附注

[译注1]此处原文是&ldquo;在xml文件中的那个</p>是jtidy自动添加的&rdquo;。我使用jtidy转换的结果是也被添加,而且这符合jtidy的逻辑,因此这里稍作了修改。

[译注2]这一部分我在试着做的时候遇到很多问题。首先,有些地方作者描述的并不清楚,特别是对于模板的解释那一部分。其次,在用xalan做转换时遇到了connection time out的异常。这可能是由于xml文件中的dtd(xhtml1-strict.dtd)无法连接造成的。把该dtd下载到本地后,该异常即可消除。然后是无法找ent文件。所需要的这些ent都可以在xmlbuddy的安装包里找到,拷过来就可以了。我不知道作者是不是没有遇到过这些问题,也可能我这只是特例。


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons