Java 需要在客户端/用户上下载pdf文件';s机器,而不是Spring Boots或MVC中的服务器机器
我已经编写了在服务器机器中生成pdf文件的代码,但我的要求是,当用户单击站点上的某个按钮/url时,在这种情况下,他应该能够在浏览器的新选项卡中看到该pdf文件,或者应该直接下载到他的机器中 这是我写的代码Java 需要在客户端/用户上下载pdf文件';s机器,而不是Spring Boots或MVC中的服务器机器,java,file,spring-mvc,pdf,itext,Java,File,Spring Mvc,Pdf,Itext,我已经编写了在服务器机器中生成pdf文件的代码,但我的要求是,当用户单击站点上的某个按钮/url时,在这种情况下,他应该能够在浏览器的新选项卡中看到该pdf文件,或者应该直接下载到他的机器中 这是我写的代码 @RequestMapping(value = "/downloadPDF", method = RequestMethod.POST) public void downloadPDF() throws FileNotFoundException, Docu
@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.
}
您需要管理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.
}
那么问题/错误是什么呢?这段代码正在服务器上生成pdf文件,所以用户无法看到文件。那么问题/错误是什么呢?这段代码正在服务器上生成pdf文件,所以用户无法看到文件。它对我来说非常有效,有没有什么方法可以让我在新标签中打开相同的pdf文件而不是下载?看看这里:至于在另一个窗口中打开它,这取决于你使用的链接/提交的目标(客户端是纯HTML),你不能从服务器上强制它。这对我来说非常有效,有什么方法可以在新标签页打开相同的pdf文件而不是下载它吗?看看这里:至于在另一个窗口打开它,这取决于你使用的链接/提交的目标(客户端是纯HTML),你不能从服务器强制它。