JavaでWEBアプリ(サーブレット)を開発しているとき、PDFを表示したいという事が多々あると思います。
PDFの出力には大きくダウンロードする方法と、ブラウザに表示する方法があります。
なんとなく気にしないで書くとダウンロードになりがちですが、ちゃんと書き方があるので書いてみます。
まずはざっくりとブラウザにPDFを表示する書き方はこんな感じです。PDFはJasperReportsで作成した想定です。
public void outPdf(HttpServletRequest request, HttpServletResponse response, JasperPrint print) {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "inline");
byte[] pdfbyte = null;
pdfbyte = JasperExportManager.exportReportToPdf(print);
OutputStream out = response.getOutputStream();
out.write(pdfbyte, 0, pdfbyte.length);
out.flush();
out.close();
}
このソースの中で、まずはこの部分、これで出力はPDFですよーって指定をしています。
response.setContentType("application/pdf");
そのあとにこの部分、ここでダウンロードなのかブラウザ表示なのかを指定しています。
今この書き方だと「inline」を指定しているのでブラウザ表示になります。
response.setHeader("Content-Disposition", "inline");
ここを「attachment」にするとダウンロードになります。
Content-Disposition: attachment → ダウンロード
Content-Disposition: inline → ブラウザ表示
さらにこの部分にファイル名を指定することもできます。
例)ダウンロードでファイル名を指定
response.setHeader("Content-Disposition", "attachment; filename=sample.pdf");
例)ブラウザ表示でファイル名指定
response.setHeader("Content-Disposition", "inline; filename=sample.pdf");
意外と要望が多いPDFの出力方法なので、使い分けできることを知っておくと、開発が楽になります。
コメント