欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用Apache FOP+XML-FO生成PDF文档

程序员文章站 2022-06-07 21:23:45
...
package tst.word;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.FormattingResults;
import org.apache.fop.apps.MimeConstants;
import org.apache.fop.apps.PageSequenceResults;
import org.xml.sax.InputSource;
public class PDFWithFOP {
 public static void main(String[] args) throws Exception{
  new PDFWithFOP().run();
  System.out.println("success");
 }
 public void run() throws Exception{
  File fo=new File("D:\\newtst\\helloworld.fo");
  File pdf=new File("D:\\newtst\\helloworld.pdf");
  convertFO2PDF(fo,pdf);
 }
 public void convertFO2PDF(File fo, File pdf) throws Exception {
        //Construct driver
  FopFactory factory=FopFactory.newInstance();
  FOUserAgent userAgent=factory.newFOUserAgent();
  OutputStream out=null;
  out=new FileOutputStream(pdf);
  out=new BufferedOutputStream(out);
  Fop fop=factory.newFop(MimeConstants.MIME_PDF,userAgent,out);
  TransformerFactory transformerFactory=TransformerFactory.newInstance();
  Transformer transformer=transformerFactory.newTransformer();
  Source source=new StreamSource(fo);
  Result res=new SAXResult(fop.getDefaultHandler());
  transformer.transform(source,res);
  out.close();
   }
}


关键在于XML-FO对XML的描述。可通过XSTL转换的方式生成FO,也可通过自己的程序去生成FO。
通过FOP可最终产生PDF、RTF等等各种文档类型。

新博客地址
相关标签: Apache XML Java