GAE/JアプリでPDF出力(1)の続き。
PageクラスがNoOperation.noOp()を返すのがアレなので、
PDF用Navigationクラスを実装する。
・StreamNavigationを継承する or Navigationインターフェイスだけ実装する
・PDF専用Navigationにする or 汎用StreamNavigationにする
といったこと等で悩んで色々試行錯誤したが、結局StreamNavigation継承の汎用型にした。
Navigationクラス
package test.navigation;import java.io.File;
import java.io.InputStream;
import javax.servlet.http.HttpServletResponse;import org.t2framework.t2.contexts.WebContext;
import org.t2framework.t2.navigation.StreamNavigation;public class Stream extends StreamNavigation{
protected String contentType;public Stream(byte[] bytes) {
super(bytes);
}
public Stream(InputStream is) {
super(is);
}public Stream(File file) {
super(file);
}
protected Stream setContentType(String contentType){
this.contentType = contentType;
return this;
}public static Stream send(byte[] bytes, String contentType){
return new Stream(bytes).setContentType(contentType);
}public static Stream send(InputStream is, String contentType){
return new Stream(is).setContentType(contentType);
}public static Stream send(File file, String contentType){
return new Stream(file).setContentType(contentType);
}@Override
public void execute(WebContext context) throws Exception {
HttpServletResponse response = context.getResponse().getNativeResource();
response.setContentType(contentType);
super.writeTo(response, response.getOutputStream());
}
}
Pageクラス
package test.page;import java.io.ByteArrayOutputStream;
import javax.servlet.http.HttpServletResponse;import org.t2framework.commons.annotation.composite.RequestScope;
import org.t2framework.commons.util.Logger;
import org.t2framework.t2.annotation.core.Default;
import org.t2framework.t2.annotation.core.Page;
import org.t2framework.t2.spi.Navigation;import test.navigation.Stream;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;@Page("/pdf")
@RequestScope
public class PDFPage {
@SuppressWarnings("unused")
private static Logger logger = Logger.getLogger(PDFPage.class);@Default
public Navigation pdf(HttpServletResponse response) throws Exception{// 用紙サイズと余白を指定してドキュメント生成
Document doc = new Document(PageSize.A4, 30, 30, 30, 30);
ByteArrayOutputStream byteout = new ByteArrayOutputStream();
PdfWriter.getInstance(doc, byteout);
doc.open();
// ベースフォント指定
BaseFont basefont = BaseFont.createFont("HeiseiKakuGo-W5", "UniJIS-UCS2-H", false);
// フォントを指定して文章追加
doc.add(new Paragraph("日本語も出力できますよっと", new Font(basefont, 12)));
doc.close();
return Stream.send(byteout.toByteArray(), "application/pdf");
}
}