Spring MVCを使用して生成されたPDFを返す 質問する

Spring MVCを使用して生成されたPDFを返す 質問する

私はSpring MVCを使用しています。リクエストボディから入力を受け取り、データをPDFに追加し、PDFファイルをブラウザに返すサービスを作成する必要があります。PDFドキュメントはitextpdfを使用して生成されます。Spring MVCを使用してこれを行うにはどうすればよいですか。これを使用してみました

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public Document getPDF(HttpServletRequest request , HttpServletResponse response, 
      @RequestBody String json) throws Exception {
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
    OutputStream out = response.getOutputStream();
    Document doc = PdfUtil.showHelp(emp);
    return doc;
}

PDF を生成する showhelp 関数。とりあえず PDF にランダムなデータをいくつか入れています。

public static Document showHelp(Employee emp) throws Exception {
    Document document = new Document();

    PdfWriter.getInstance(document, new FileOutputStream("C:/tmp/report.pdf"));
    document.open();
    document.add(new Paragraph("table"));
    document.add(new Paragraph(new Date().toString()));
    PdfPTable table=new PdfPTable(2);

    PdfPCell cell = new PdfPCell (new Paragraph ("table"));

    cell.setColspan (2);
    cell.setHorizontalAlignment (Element.ALIGN_CENTER);
    cell.setPadding (10.0f);
    cell.setBackgroundColor (new BaseColor (140, 221, 8));                                  

    table.addCell(cell);                                    
    ArrayList<String[]> row=new ArrayList<String[]>();
    String[] data=new String[2];
    data[0]="1";
    data[1]="2";
    String[] data1=new String[2];
    data1[0]="3";
    data1[1]="4";
    row.add(data);
    row.add(data1);

    for(int i=0;i<row.size();i++) {
      String[] cols=row.get(i);
      for(int j=0;j<cols.length;j++){
        table.addCell(cols[j]);
      }
    }

    document.add(table);
    document.close();

    return document;   
}

これは間違いなく間違いです。クライアントのファイル システムに保存できるように、PDF を生成し、保存/開くダイアログ ボックスをブラウザーで開くようにしたいです。どうか助けてください。

ベストアンサー1

については正しい方向に進んでいますresponse.getOutputStream()が、コードのどこにもその出力を使用していません。基本的に必要なのは、PDF ファイルのバイトを出力ストリームに直接ストリーミングし、応答をフラッシュすることです。Spring では、次のように実行できます。

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

ノート:

  • メソッドには意味のある名前を付けましょう。PDF文書を書き出すメソッドにshowHelpない良いアイデア
  • ファイルを読み込むbyte[]: 例ここ
  • showHelp()2人のユーザーが同時にリクエストを送信した場合にファイルが上書きされないように、一時PDFファイル名にランダムな文字列を追加することをお勧めします。

おすすめ記事