【发布时间】:2017-12-15 10:10:15
【问题描述】:
我必须下载一个使用 spring 调用 rest api 的 pdf 文件。我的代码如下:
@RequestMapping(value = "downloadPDF", method = RequestMethod.GET, produces = MediaType.APPLICATION_PDF_VALUE)
public @ResponseBody ResponseEntity<InputStreamResource> getPDF() throws IOException {
ByteArrayInputStream bis = GeneratePdfReport.createReport();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "inline; filename=migration.pdf");
return ResponseEntity
.ok()
.headers(headers)
.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(bis));
}
这是将简单表格打印到文档中的 createReport 方法
public static ByteArrayInputStream createReport() {
Document document = new Document();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(60);
table.setWidths(new int[]{1, 3, 3});
Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
PdfPCell hcell;
hcell = new PdfPCell(new Phrase("Id", headFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
hcell = new PdfPCell(new Phrase("Name", headFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
hcell = new PdfPCell(new Phrase("Population", headFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
} catch (DocumentException ex) {
System.out.println("error");
}
return new ByteArrayInputStream(out.toByteArray());
}
当我调用 rest api 并从服务器收到此错误时出现问题
HTTP Status 406 – Not Acceptable
The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation
【问题讨论】:
标签: rest spring-boot itext