我已经编写了在服务器计算机中生成pdf文件的代码,但是我的要求是,在这种情况下,当用户单击站点上的某些按钮/ URL时,他应该能够在浏览器的新标签页中看到该pdf文件,或者直接下载到他的机器上
这是我写的代码
@RequestMapping(value = "/downloadPDF", method = RequestMethod.POST)
public void downloadPDF()
throws FileNotFoundException, DocumentException {
final String DEST = "column_width_example.pdf";
StringBuilder sb = new StringBuilder();
//Below method returns the data which will be convert in table format for pdf file
String dataForPDFFile = rowForUserCompetency(sb, "name");
Document document = new Document(PageSize.A4.rotate());
PdfWriter.getInstance(document, new FileOutputStream(DEST));
document.open();
float[] columnWidths = { 2.5f, 2, 2, 1, 2, 2, 3 };
String[] lines = dataForPDFFile.toString().split("\\n");
Font fontRow = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
PdfPTable table = new PdfPTable(columnWidths);
table.setWidthPercentage(100);
table.getDefaultCell().setUseAscender(true);
table.getDefaultCell().setUseDescender(true);
for (String string : lines) {
String[] cellData = string.toString().split(",");
for (String header : cellData) {
PdfPCell cell = new PdfPCell();
cell.setPhrase(new Phrase(header.toUpperCase(), fontRow));
table.addCell(cell);
}
table.completeRow();
}
document.add(table);
document.close();
}
而且此代码正在该服务器上生成pdf文件,因此普通用户将无法在其计算机上看到该文件,因此有人可以指导我上面代码中的更改是什么。
最佳答案
您需要管理HTTP响应。
public void downloadPDF(HttpServletResponse response) {
// Set the headers for downloading or opening your document
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment; filename=\"user_file_name.pdf\"");
...
// Write directly the output stream.
PdfWriter.getInstance(document, response.getOutputStream());
...
// Build your document as ever.
}