34
私はSpring MVCを使用しています。要求本体から入力を受け取り、データをpdfに追加し、pdfファイルをブラウザに戻すサービスを作成する必要があります。 pdfドキュメントはitextpdfを使用して生成されます。 Spring MVCを使ってどうすればいいですか?私はこれを使用しようとしましたSpring MVCを使用して生成されたpdfを返す
@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が生成され、クライアントのファイルシステムに保存することができるようにブラウザを介して開く/保存ダイアログボックスを保存したい。私を助けてください。
それは私を助けました。どうもありがとう!!!私はもう一つ持っている。私はここで私のファイルシステムに生成されたPDFを保存して、それを読んでバイトに変換しています。外出先で生成されたpdfを変換する必要がある場合はどうすればよいですか。事前に感謝します –
あなたの 'PdfWriter.getInstance()'で 'FileOutputStream'を使うのではなく、' ByteArrayOutputStream'を使うことができます。 – kryger
@kryger、ブラウザウィンドウでPDFファイルを開く方法を知っていますか?私はあなたの方法を使用し、すぐにファイルを保存するようにユーザーに求めています:) –