首页 > java > java处理fop导出pdf的中文乱码问题

java处理fop导出pdf的中文乱码问题

2009年8月3日 发表评论 阅读评论

本文的作用是,生成带中文的加密pdf格式的文件,防止被人修改。
在项目下建立docbook-xsl, fo-res, out, sample四个文件夹
docbook-xsl目录: 放从sourceforge上下载的docbook-xsl.zip解压的文件
fo-res目录: 放一些apache fop需要配置的文件(下面会说到)
out目录: 放导出结果
sample目录: 放xml模板
从apache fop项目下载fop,目前是fop0.95, 只要下载binary版就行了,后面的代码都是以fop0.95进行测试的。
解压后将build目录下的fop.jar以及lib目录下的包都加到你项目里,然后将conf下的fop.xconf配置文件放到fo-res目录下,记住这个文件,等会用它。

以宋体 为例,解决中文乱码问题:
第一步
private static void test1() {
String[] parameters = {
“-ttcname”,
“SimSun”,
“c:\\WINDOWS\\Fonts\\simsun.ttc”, “E:\\project-java\\p-eclipse\\newtest\\fo-res\\simsun.xml”, };
TTFReader.main(parameters);
}
执行test1方法,会在fo-res目录下生成一个simsun.xml
常用的中文字体:
simsun.ttc 宋体
simkai.ttf 宋楷
simhei.ttf 黑体
第二步、修改fo-res目录下的fop.xconf文件,在fonts节点下加入或替换下列内容






metrics-url后面的值可以是绝对路径;
经常我们的项目会部署到linux下,没有simsun.ttc文件怎么办呢,只需要把windows下的这个文件拷贝到linux就可以了。
第三步、把模板中使用的宋体字体 修改为font-family =SimSun。
第四步、执行下面的方法生成pdf;
private static void test2(){
try {
System.out.println(“Preparing…”);
File baseDir = new File(“.”);
File outDir = new File(baseDir, “out”);
outDir.mkdirs();
// Setup input and output files
File xmlfile = new File(baseDir, “/fo-res/p.xml”);
File xsltfile = new File(baseDir, “/fo-res/p.xsl”);
File pdffile = new File(outDir, “/sample.pdf”);
File conffile = new File(baseDir, “/fo-res/fop.xconf”);
System.out.println(“Input: XML (” + xmlfile + “)”);
System.out.println(“Stylesheet: ” + xsltfile);
System.out.println(“Output: PDF (” + pdffile + “)”);
System.out.println();
System.out.println(“Transforming…”);
FopFactory fopFactory = FopFactory.newInstance();
FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
/* 1. userPassword: String, may be null
2. ownerPassword: String, may be null
3. allowPrint: true if printing is allowed
4. allowCopyContent: true if copying content is allowed
5. allowEditContent: true if editing content is allowed
6. allowEditAnnotations: true if editing annotations is allowed
*/
foUserAgent.getRendererOptions().put(“encryption-params”, new PDFEncryptionParams(
null, “password”, true, false, false, false));
// Setup output
OutputStream out = new java.io.FileOutputStream(pdffile);
out = new java.io.BufferedOutputStream(out);
try {
//加载配有中文配置的文件
fopFactory.setUserConfig(conffile);
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out);
// Setup XSLT
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
// Setup input for XSLT transformation
Source src = new StreamSource(xmlfile);
Result res = new SAXResult(fop.getDefaultHandler());
// Start XSLT transformation and FOP processing
transformer.transform(src, res);
} finally {
out.close();
}
System.out.println(“Success!”);
} catch (Exception e) {
e.printStackTrace();
}
}

分类: java 标签: 6,422 次阅读
原文链接:http://www.wenhq.com/article/view_352.html
欢迎转载,请注明出处:亲亲宝宝
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.