public void print() {
Document document = new Document(PageSize.A4);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", String.format(ATTACHMENT, "-normal"));
PdfWriter pdfWriter = PdfWriter.getInstance(document, byteArrayOutputStream);
document.open();
BaseFont baseFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, ISO_8859_9, true);
BaseFont baseBoldFont = BaseFont.createFont(BaseFont.TIMES_BOLD, ISO_8859_9, true);
Font font11 = new Font(baseFont, 11);
document.add(new Paragraph(seciliListeElemani.getOgrno() + " " +
seciliListeElemani.getAd() + " " + seciliListeElemani.getSoyad() + " Mezun Olabilir!!!!", font11));
document.close();
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream servletOutputStream = response.getOutputStream();
byteArrayOutputStream.writeTo(servletOutputStream);
byteArrayOutputStream.flush();
FacesContext.getCurrentInstance().responseComplete();
} catch (DocumentException e) {
throw new OrgunException(e.getMessage());
} catch (IOException e) {
throw new OrgunException(e.getMessage());
}
}
私はこのコードを使ってPDFファイルを印刷しました。 Webアプリケーションで自分のボタンをクリックしても何も起こりません。エラーメッセージはありません。私はデバッグ時にメソッドが正常に完了したようです。しかし、ただ待っていて、pdfがダウンロードされないように待っている。助言がありますか?Java Pdf生成とダウンロード
ヒント:デバッガの使用方法を学ぶ。 * trace *文を追加したりできます。あなたのコードが何をしているのか観察できないときは、それを観測可能に変更してください! – GhostCat
答えは正しいです:これは本当に貧弱な方法の1つです。このメソッドが何をしているのかについて**何も言わない**という名前から始まります。その後、すべての種類のクリーンコード規則の違反が続きます。それは問題です:バグはひどく書かれたコードに隠れます。 – GhostCat
コードをデバッグします。ローカルで実行し、ファイルに書き込みます。それは動作しますか?もしそうなら、pdf生成に関係しない何かが間違っている。 wiresharkを使用して、実際にネットワーク経由で送信されているコンテンツを確認します。 –