JavaでのPDFファイルをダウンロードしたいと要望があって社内アプリの開発をしていましたが、思った以上にバグがでてかなり長期戦になりました。
やりたいことは
- ボタンを押すとファイルのダウンロードが始まる
- ファイル名は日本語
- PDFファイルには日本語の表示
- 帳票なので表を表示したい
- 使うものはすべてフリーのもの
以上です。
というか現段階でまだできていないんですけどね・・・
一応つまづいたところなどを。
ファイルの日本語名
かなり大変でした。
理屈自体もよくわかってません(汗)
とりあえずコードを書いておきます。iTextというPDFのライブラリを使っています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
protected HttpServletResponse getHttpFileDownloadHeader(String filenName) { String encoding = "Windows-31J"; HttpServletResponse res = getServletResponse(); byte[] name = null; try { name = filenName.getBytes("UTF8"); } catch (UnsupportedEncodingException ex) { Logger.getLogger(MenuBean.class.getName()).log(Level.SEVERE, null, ex); } res.setContentType("text/html; charset=" + encoding); res.setHeader("Content-Disposition", "attachment; filename=\"=?utf-8?B?" + Base64.encodeBase64String(name) + "?=\""); res.setHeader("Content-Type", "application/pdf; charset=utf-8"); res.setCharacterEncoding(encoding); return res; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
HttpServletResponse res = getHttpFileDownloadHeader(getPdfFileName()); try (OutputStream os = res.getOutputStream()) { try { Document doc = new Document(PageSize.A4); PdfWriter write = PdfWriter.getInstance(doc, os); doc.open(); doc.add(new Paragraph("hogehoge")); doc.add(createPdfTable()); doc.close(); } catch (DocumentException ex) { Logger.getLogger(MenuBean.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(MenuBean.class.getName()).log(Level.SEVERE, null, ex); } |
HTTPレスポンスヘッダの[Content-Disposition]について、Safariでの日本語文字化け対策など。
byte変換
これで進めてきたのですが、肝心の帳票に出力する部分で日本語フォントが使えないことが発覚。
ここの対応で行けるようなのですが私は駄目でした・・・(汗)
比較的新しいライブラリということでApachePDFBoxというものを使い始めましたが、日本語表記やテーブル表記も難しく依存関係でもエラーがでました。
一応下記にそれぞれの対処したものとリンクを書いておきます。
apachePDFbox自体の使い方
Java ライブラリ Apache PDFBox で PDF を操作しよう
テーブル文字列
Creating tables with PDFBox
ApachPDFBoxの依存関係
https://pdfbox.apache.org/1.8/dependencies.html
テーブルのサンプルなど
githubより
https://github.com/eduardohl/Paginated-PDFBox-Table-Sample
いろいろ調べましたが検索スキルなどがいまだに未熟ですね・・・・
なんとか公式ページを手探りで読んだり、上司にきいたりしながらエラーは消えましたが、いまだゴールにはたどり着けていません(汗)
うまくいったらまた書きます・・・