XSL-FO 转换为PDF(simple.fo)

 

fop包中提供了很多example,以最简单的一个开始学习。

simple.fo

<?xml version="1.0" encoding="utf-8"?>
<!-- XSL-FO 文档属于 XML 文档,因为也需要以 XML 声明来起始: -->

<!-- fo:root 元素是 XSL-FO 文档的根元素。这个根元素也要声明 XSL-FO 的命名空间 -->
<fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
	
   <!-- fo:layout-master-set 元素含有一个或多个页面模板 -->
  <fo:layout-master-set>
    <!-- layout information -->
    <fo:simple-page-master master-name="simple" #每个模板须有一个唯一的名称(master-name)
                  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>
  <!-- end: defines page layout -->


  <!-- 页面,关联到定义好的page-master -->
  <fo:page-sequence master-reference="simple">

    <fo:flow flow-name="xsl-region-body">

      <!-- this defines a title -->
      <fo:block font-size="18pt" #字号
            font-family="sans-serif" #字体
            line-height="24pt" #行高
            space-after.optimum="15pt" #块间距
            background-color="blue" #背景颜色
            color="white" #字体颜色
            text-align="center" #文本对齐
            padding-top="3pt"> #内容区域与边框之间的区域
        Extensible Markup Language (XML) 1.0
      </fo:block>


      <!-- this defines normal text -->
      <fo:block font-size="12pt" #字号
                font-family="sans-serif" #字体
                line-height="15pt"#行高
                space-after.optimum="3pt" #块间距
                text-align="justify"> #内容自动调整,拉伸填满行
        The Extensible Markup Language (XML) is a subset of SGML that is completely described in this document. Its goal is to
        enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML
        has been designed for ease of implementation and for interoperability with both SGML and HTML.
      </fo:block>

      <!-- this defines normal text -->
      <fo:block font-size="12pt" #字号
                font-family="sans-serif" #字体
                line-height="15pt" #行高
                space-after.optimum="3pt" #块间距
                text-align="justify"> #内容自适应,按空间自动调节间隔大小
        The Extensible Markup Language (XML) is a subset of SGML that is completely described in this document. Its goal is to
        enable generic SGML to be served, received, and processed on the Web in the way that is now possible with HTML. XML
        has been designed for ease of implementation and for interoperability with both SGML and HTML.
      </fo:block>

    </fo:flow> <!-- closes the flow element-->
  </fo:page-sequence> <!-- closes the page-sequence -->
</fo:root>

 

 

使用FOP将XSL-FO转换为PDF

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

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.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;


public class FopService {
	/**
	 * 
	 * @param src   fo文件路径
	 * @param dest  将要生成的pdf路径和文件名
	 * @throws Exception
	 * >>Step 1: 创建一个新的FopFactory实例。 FopFactory实例保存配置信息和缓存数据的引用。如果你打算在一个JVM运行期间渲染多个文件,重用该实例对象是非要重要的。
	 * 
	 * >>Step 2: 为将要生成的文件设置一个输出流,使用缓冲区来处理流数据是一个不错的方式
	 * 
	 * >>Step 3:通过FopFactory的工厂方法创建Fop实例,你需要为FopFactory指定需要得到的文件类型,可以通过MIME类型来进行指定,可以使用MimeConstants定义好的常量进行说明。第2个参数是Setp2中所指定的输出流对象
	 * 
	 * >>Step 4: [JAXP:Java API for XML Processing] 获取JAXP的转换对象
	 * 
	 * >>Step 5: 为JAXP准备输入和输出参数
	 * 
	 * >>Step 6: JAXP与FOP合作,将输出流传递给FOP,由FOP来生成PDF,当transform()执行完成后,pdf也生成完毕
	 * 
	 * 最后,关闭流。
	 */
	public static void convertFO2PDF(String src, String dest) throws Exception{
		
		InputStream fo = new FileInputStream(src);
		File pdf = new File(dest);
		
		// Step 1: Construct a FopFactory
		// (reuse if you plan to render multiple documents!)
		FopFactory fopFactory = FopFactory.newInstance();
		
		// Step 2: Set up output stream.
		// Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams).
		OutputStream out = new BufferedOutputStream(new FileOutputStream(pdf));

		try {
			// Step 3: Construct fop with desired output format
			//根据fopFactory工厂创建fop实例。指定需要的类型,以及最后生成的文件存放目录
			Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, out);
			
			// Step 4: Setup JAXP using identity transformer
			TransformerFactory factory = TransformerFactory.newInstance();
			Transformer transformer = factory.newTransformer();
			
			// Step 5: Setup input and output for XSLT transformation
			// Setup input stream
			Source xmlSource = new StreamSource(fo);
			
			// Resulting SAX events (the generated FO) must be piped through to FOP
			Result outputTarget = new SAXResult(fop.getDefaultHandler());
			
			// Step 6: Start XSLT transformation and FOP processing
			transformer.transform(xmlSource, outputTarget);
		} finally {
			//Clean-up
			out.close();
		}
	}
}

 测试

public class Test {
	
	
	@org.junit.Test
	public void test() throws Exception{
		String base = System.getProperty("user.dir")+"/resource/";
		String src = base+"simple.fo";
		String dest = src+".pdf";
		FopService.convertFO2PDF(src, dest);
	}

}

 

生成的PDF:


XSL-FO 转换为PDF(simple.fo)_第1张图片
 

 

你可能感兴趣的:(simple)