Apache FOPをつかってPDF作成。
もともとLaTexとかいうのが入ってたけど、使い方わかんないし、ちょっとやってみたけど小難しかったので、あきらめた。
データはXML形式で保持されてるから、XMLからPDF作れないかなー?で探したら、
Apache FOPでできるらしい。
http://xmlgraphics.apache.org/fop/
Apache FOP 1.0版を使用。
そのままでは日本語が出力できない。
1.0版では、OSにはいってるフォントを探して適宜やってくれるらしい。
そのためには定義ファイルを作成して、それを読み込ませてあげる必要があるらしい。
参考http://blog.recyclebin.jp/archives/760
Javaでの実装の仕方は、ここ参照
http://xmlgraphics.apache.org/fop/1.0/embedding.html
今回はXMLファイルとXSLファイルをあわせてつくるため、とくにこのサンプルにおせわになった。
http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleXML2PDF.java?view=markup
設定した日本語の定義ファイルをよみこませ方はここ参照
http://xmlgraphics.apache.org/fop/1.0/embedding.html#config-external
こんな風に実装したら、pdfのファイル名(パス+ファイル名)のところにPDFができてた。
/**
* PDFファイル出力処理
* @param xslFile XSLファイルパス
* @param xmlFile XMLファイルパス
* @param pdfFileName PDFファイルパス+名前
* @throws Exception
*/
public static void createPdfFile(String xslFile,
String xmlFile,
String pdfFileName
) throws Exception {
// 各ファイル
File xmlfile = new File(xmlFile);
File xsltfile = new File(xslFile);
File pdffile = new File(pdfFileName);
// FopFactoryオブジェクトの取得
FopFactory fopFactory = FopFactory.newInstance();
// 日本語フォント読込
fopFactory.setUserConfig("/conf/fop_fonts.xconf");
// 出力先の指定
OutputStream output = new BufferedOutputStream(new FileOutputStream(pdffile));
try {
// 出力フォーマット(PDFD)を指定してFopオブジェクトを生成
Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, output);
// XSLT準備
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(new StreamSource(xsltfile));
// XSLT変換のため設定
Source src = new StreamSource(xmlfile);
// Resulting SAX events (the generated FO) must be piped through to FOP
Result res = new SAXResult(fop.getDefaultHandler());
// XSLTファイルをFOPファイルにトランスファー
transformer.transform(src, res);
} finally {
output.close();
}
}
}