---
title: "fop生成PDF支持中文(xml & xsl)"
author: "samwong"
date: "2014-04-16T22:39:00Z"
tags: []
categories: ["行业应用"]
slug: "fop-pdf-xml-xsl"
draft: false
lastmod: "2014-04-16T22:39:00Z"
id: 2047597
url: "https://samwong.iteye.com/blog/2047597"
---

[http://oudoud.iteye.com/blog/1755054](http://oudoud.iteye.com/blog/1755054)

本例可将xml格式数据按xsl模板转化为PDF   
1.首先，程序结构如下：   
![](http://dl.iteye.com/upload/attachment/0078/4825/7dcf4457-0376-3614-914e-f66ee944c76a.png)   
2.FopReport.java 

Java代码  [![收藏代码](http://oudoud.iteye.com/images/icon_star.png)]()

01. // Step 1: Construct a FopFactory
02. private static final FopFactory fopFactory = FopFactory.newInstance();
03. /\**
04. * 根据xsl模板及xml数据文件生成pdf
05. * @param xsltFile xsl模板
06. * @param xmlFile xml数据文件
07. * @return ReportData
08. * @throws Exception
09. * @author bin.yin 2012/12/25
10. \*/
11. public static ReportData createReport(String xsltFile, String xmlFile) throws Exception {
12. ReportData reportData = new ReportData();
13. reportData.setContentType("application/pdf");
14. fopFactory.setUserConfig("conf/fop.xml");
15. // Step 2: Set up output stream.
16. ByteArrayOutputStream out = new ByteArrayOutputStream();
17. try {
18. // Step 3: Construct fop with desired output format
19. Fop fop = fopFactory.newFop(MimeConstants.MIME\_PDF, out);
20. // Step 4: Setup XSLT using identity transformer
21. TransformerFactory factory = TransformerFactory.newInstance();
22. Transformer transformer = factory.newTransformer(new StreamSource(new File(xsltFile)));
23. // Step 5: Setup input and output for XSLT transformation
24. Source src = new StreamSource(new File(xmlFile));
25. // Source src = new StreamSource(new StringReader(myString));
26. // Step 6: Resulting SAX events (the generated FO) must be piped through to FOP
27. Result res = new SAXResult(fop.getDefaultHandler());
28. // Step 7: Start XSLT transformation and FOP processing
29. transformer.transform(src, res);
30. reportData.setData(out.toByteArray());
31. } catch(Exception e) {
32. throw e;
33. } finally {
34. out.close();
35. }
36. return reportData;
37. }
38. /\**
39. * 根据xsl模板及xml字节数组生成pdf
40. * @param xsltFile xsl模板
41. * @param bXmlData xml字节数组 eg. StringBuffer buf = new StringBuffer(); buf.getBytes("UTF-8");
42. * @return ReportData
43. * @throws Exception
44. * @author bin.yin 2012/12/25
45. \*/
46. public static ReportData createReport(String xsltFile, byte\[] bXmlData) throws Exception {
47. ReportData reportData = new ReportData();
48. try {
49. // convert xml bytes to a temp file
50. File xmlFile = File.createTempFile("FOP", ".tmp");
51. FileOutputStream fos = new FileOutputStream(xmlFile);
52. fos.write(bXmlData);
53. fos.close();
54. reportData = createReport(xsltFile, xmlFile.getAbsolutePath());
55. // delete temp file
56. xmlFile.delete();
57. } catch (Exception e) {
58. throw e;
59. }
60. return reportData;
61. }

3.拼接xml文件 

Java代码  [![收藏代码](http://oudoud.iteye.com/images/icon_star.png)]()

01. StringBuffer buf = new StringBuffer();
02. buf.append("&lt;?xml version=\\"1.0\\" encoding=\\"UTF-8\\"?&gt;");
03. buf.append("&lt;ItemListReport&gt;");
04. buf.append("    &lt;ReportHeader&gt;");
05. buf.append("        &lt;Title&gt;附加条款&lt;/Title&gt;");
06. buf.append("        &lt;PartyA&gt;上海信息技术有限公司B&lt;/PartyA&gt;");
07. buf.append("        &lt;PartyB&gt;上海信息技术有限公司B&lt;/PartyB&gt;");
08. buf.append("    &lt;/ReportHeader&gt;");
09. buf.append("    &lt;ReportBody&gt;");
10. buf.append("        &lt;Table&gt;");
11. buf.append("            &lt;TableRow&gt;");
12. buf.append("                &lt;ItemName&gt;附加条款1&lt;/ItemName&gt;");
13. buf.append("                &lt;ItemTime&gt;2012-12-23 09:03&lt;/ItemTime&gt;");
14. buf.append("            &lt;/TableRow&gt;");
15. buf.append("            &lt;TableRow&gt;");
16. buf.append("                &lt;ItemName&gt;上海信息技术有限公司附加条款1&lt;/ItemName&gt;");
17. buf.append("                &lt;ItemTime&gt;2012-12-23 09:03&lt;/ItemTime&gt;");
18. buf.append("            &lt;/TableRow&gt;");
19. buf.append("        &lt;/Table&gt;");
20. buf.append("    &lt;/ReportBody&gt;");
21. buf.append("    &lt;ReportFooter&gt;");
22. buf.append("        &lt;PrintDate&gt;2012-12-12&lt;/PrintDate&gt;");
23. buf.append("        &lt;ReportNo&gt;010123456789&lt;/ReportNo&gt;");
24. buf.append("    &lt;/ReportFooter&gt;");
25. buf.append("&lt;/ItemListReport&gt;");

4.生成PDF文档 

Java代码  [![收藏代码](http://oudoud.iteye.com/images/icon_star.png)]()

1. ReportData data = FopReport.createReport("report\\\\sample\\\\Sample.xsl", buf.toString().getBytes("UTF-8"));
2. FileOutputStream fos = new FileOutputStream("D:/sample.pdf");

5.附字体配置fop.xml 

Java代码  [![收藏代码](http://oudoud.iteye.com/images/icon_star.png)]()

1. &lt;font metrics-url="conf/fonts/SimSun.xml" kerning="yes" embed-url="conf/fonts/SimSun.ttc"&gt;
2. &lt;font-triplet name="SimSun" style="normal" weight="normal" /&gt;
3. &lt;font-triplet name="SimSun" style="normal" weight="bold" /&gt;
4. &lt;font-triplet name="SimSun" style="italic" weight="normal" /&gt;
5. &lt;font-triplet name="SimSun" style="italic" weight="bold" /&gt;
6. &lt;/font&gt;

6.效果图如下：   
![](http://dl.iteye.com/upload/attachment/0078/4829/738822cd-0075-30a3-8de0-d55336488bd5.png "点击查看原始大小图片")