Java 如何在SpringMVC中下载PDF文件?
这是我的文件路径Java 如何在SpringMVC中下载PDF文件?,java,spring,pdf,model-view-controller,Java,Spring,Pdf,Model View Controller,这是我的文件路径 public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/"; 下面的代码是我为从上述资源文件夹下载pdf而编写的 Pdf="column name in database i used for storing in database" @RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET) public void getPdf(@
public final static String BOOKINGPDFFILE= "D:/Hotels/pdf/";
下面的代码是我为从上述资源文件夹下载pdf而编写的
Pdf="column name in database i used for storing in database"
@RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(@PathVariable("pdf") String fileName, HttpServletResponse response,HttpServletRequest request) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
Files.copy(file.toPath(),response.getOutputStream());
} catch (IOException ex) {
System.out.println("Contract Not Found");
System.out.println(ex.getMessage());
}
}
您需要创建AbstractPdfView的实现来实现这一点。。您可以参考此链接,您可以尝试以下内容:
@RequestMapping(method = { RequestMethod.GET }, value = { "/downloadPdf" })
public ResponseEntity<InputStreamResource> downloadPdf()
{
try
{
File file = new File(BOOKINGPDFFILE);
HttpHeaders respHeaders = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/pdf");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
respHeaders.setContentDispositionFormData("attachment", file.getName());
InputStreamResource isr = new InputStreamResource(new FileInputStream(file));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Errore nel download del file "+idForm+".csv; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@RequestMapping(方法={RequestMethod.GET},值={”/downloadPdf})
公众回应下载PDF()
{
尝试
{
文件文件=新文件(BookingPdfile);
HttpHeaders respHeaders=新的HttpHeaders();
MediaType MediaType=MediaType.parseMediaType(“application/pdf”);
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
setContentDispositionFormData(“附件”,file.getName());
InputStreamResource isr=新的InputStreamResource(新文件InputStream(文件));
返回新的ResponseEntity(isr、RespHeader、HttpStatus.OK);
}
捕获(例外e)
{
String message=“Errore nel download del file”+idForm+.csv;“+e.getMessage();
记录器。错误(消息,e);
返回新的响应属性(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
在您的网页中,您可以这样写链接:
<a href="/yourWebAppCtx/yourControllerRoot/downloadPdf" target="_blank"> download PDF </a>
这是方法,希望对你有所帮助
@RequestMapping(value = "/getpdf/{pdf}", method = RequestMethod.GET)
public void getPdf(@PathVariable("pdf") String fileName, HttpServletResponse response) throws IOException {
try {
File file = new File(FileConstant.BOOKINGPDFFILE + fileName+ ".pdf");
if (file.exists()) {
// here I use Commons IO API to copy this file to the response output stream, I don't know which API you use.
FileUtils.copyFile(file, response.getOutputStream());
// here we define the content of this file to tell the browser how to handle it
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".pdf");
response.flushBuffer();
} else {
System.out.println("Contract Not Found");
}
} catch (IOException exception) {
System.out.println("Contract Not Found");
System.out.println(exception.getMessage());
}
}
这是你问题的详细答案。 让我从服务器端代码开始: 下面的类用于创建包含一些随机内容的pdf,并返回等效的字节数组outputstream
public class pdfgen extends AbstractPdfView{
private static ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
public ByteArrayOutputStream showHelp() throws Exception {
Document document = new Document();
// System.IO.MemoryStream ms = new System.IO.MemoryStream();
PdfWriter.getInstance(document,byteArrayOutputStream);
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 byteArrayOutputStream;
}
好的,我正在浏览它,如果我想在浏览器中打开文件,在下一个选项卡中打开它自己,我也在使用Commons IO,但在这一部分我得到了错误FileUtils.copyFile(file,response.getOutputStream());如果你能留下更多关于错误和Spring MVC配置的详细信息,我可以帮助你。错误基本上是404找不到。当我单击下载按钮时,它会重定向到新选项卡并显示“404找不到”。我需要添加这部分吗我使用的是4.0.1 Spring framework..itext for pdf generationLook,您误解了资源标记的用法,因为它被配置为向WEB声明公共资源,如图像、静态html等。您可能正在使用itext生成PDF,并在OS temp目录中执行此操作。如果不是这样,那么我建议您使用此文件夹进行此类工作。然后,一旦准备好下载文件,只需使用以下代码指示文件的位置:
file file file=new file(FileUtils.gettempredirectorypath()+“/”+fileName+”.pdf)代码>。魔法是通过response.flushBuffer()完成的代码>指令。您对我提供的指令所做的是:1。将我的文件复制到将写入客户端(本例中为浏览器)的缓冲区。2.告诉客户端要处理的文件的内容和名称。3.将此文件提交到客户端。ResponseEntity
从何处导入?
@RequestMapping(path="/home")
public ResponseEntity<byte[]> render(HttpServletRequest request , HttpServletResponse response) throws IOException
{
pdfgen pg=new pdfgen();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment:filename=report.pdf");
try {
OutputStream out = response.getOutputStream();
}
catch (IOException e){
e.printStackTrace();
}
byte[] contents = null;
try {
contents = pg.showHelp().toByteArray();
}
catch (Exception e) {
e.printStackTrace();
}
//These 3 lines are used to write the byte array to pdf file
/*FileOutputStream fos = new FileOutputStream("/Users/naveen-pt2724/desktop/nama.pdf");
fos.write(contents);
fos.close();*/
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("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[]> respons = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK);
return respons;
}
$.ajax({
url:'/PDFgen/home',
method:'POST',
cache:false,
xhrFields: {
responseType: 'blob'
},
success: function(data) {
//alert(data);
let blob = new Blob([data], {type: 'application/pdf'}); //mime type is important here
let link = document.createElement('a'); //create hidden a tag element
let objectURL = window.URL.createObjectURL(blob); //obtain the url for the pdf file
link.href = objectURL; // setting the href property for a tag
link.target = '_blank'; //opens the pdf file in new tab
link.download = "fileName.pdf"; //makes the pdf file download
(document.body || document.documentElement).appendChild(link); //to work in firefox
link.click(); //imitating the click event for opening in new tab
},
error:function(xhr,stats,error){
alert(error);
}
});