Fop生成pdf(xsl) fopjavaxslxml
程序员文章站
2022-07-06 11:34:48
...
在做项目的时候需要生成PDF,使用了fop技术实现
1、下载对应的jar包,不是maven工程直接下载
1.1 maven项目
2、下载相关字体和模板文件
2.1设置字体路径
2.2设置模板文件数据源
3、编写Java代码
public class FopReport extends BaseService{ private static final String TYPE = ".pdf"; private static final FopFactory fopFactory = FopFactory.newInstance(); private static final String CONRIGURL = "fop.xml"; /** * 转PDF文件 * @param xsl 模板文件 * @param policy 数据对象 * @throws IOException * @throws SAXException */ private ReportData createReport(File xsl,Object policy,boolean flag) throws IOException, SAXException { ReportData reportData = new ReportData(); String userConfig = Configuration.getValue("pdf.font.path")+"/"+CONRIGURL; logger.info("加载字体目录:"+Configuration.getValue("pdf.font.path")+"/"+CONRIGURL); fopFactory.setUserConfig(userConfig); //读取自定义配置 ByteArrayOutputStream output = new ByteArrayOutputStream(); try { Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, output); TransformerFactory factory = TransformerFactory.newInstance(); String templateUrl = Configuration.getValue("pdf.template.path"); File xslFile = new File(new File(templateUrl),xsl.toString()); Transformer transformer = factory.newTransformer(new StreamSource(xslFile)); //模板文件 logger.info("加载模板:"+xslFile.toString()); String str = ""; if (!flag) { Ojbect2Xml ox = new Ojbect2Xml(); str = ox.getFullXML(policy, "get"); } else { str = policy.toString(); } ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream( str.getBytes("UTF-8")); Charset charset = Charset.forName("UTF-8"); Reader r = new InputStreamReader(bytearrayinputstream, charset); Source src = new StreamSource(r); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); reportData.setPdfData(output.toByteArray()); writePdf(reportData); } catch (Exception ex) { ex.printStackTrace(); } finally { output.close(); } return reportData; } }
4、生成一个字节流文件,将文件流写出即可,最终效果
上一篇: Linux用户与用户组概念