在Spring MVC中如何下载PDF文件?

4

这是我的文件路径

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());
    }

}
5个回答

4
您可以尝试像这样做:

您可以尝试类似以下的操作:

@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);
        }
    }

在您的网页中,您可以按照以下方式编写链接:

<a href="/yourWebAppCtx/yourControllerRoot/downloadPdf" target="_blank"> download PDF </a>

ResponseEntity 是从哪里导入的? - Hussain

4
这是方法,希望能帮到您。
@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());
    }
}

错误基本上是404未找到。当我点击下载按钮时,它会重定向到新标签页并显示“404未找到”。我需要添加<mvc:resources mapping =“/ getpdf / **”location =“D:/ Hotels / pdf /”/>这部分,我正在使用4.0.1 Spring框架..itext用于PDF生成。 - Nikil Karanjit
你所执行的指令是:1. 将我的文件复制到将要写入客户端(在这种情况下是浏览器)的缓冲区。2. 告诉客户端将要处理的文件内容和名称。3. 将此文件提交给客户端。 - Gabriel Villacis
我完成了我的POC,并且使用Chrome打开其PDF查看器获取了我的PDF。因此,我认为你的问题是一个大小写敏感的问题。 - Gabriel Villacis
嗨@Gabriel,我正在使用相同的代码下载PDF文件。但是我注意到的是-它会下载一个空文件。假设要下载的文件中有5页,则下载版本具有这5页,但全部为空白页。 - ABHINEET SINGH
当我在控制器类中使用 produces app/pdf 属性时,PDF 文件可以正确下载。但是在这种情况下我无法抛出异常,因为它会返回 [object object]。 - ABHINEET SINGH
显示剩余8条评论

1

好的,我正在处理。如果我想在浏览器中打开文件并在下一个选项卡中显示呢? - Nikil Karanjit

0

这是关于您问题的详细答案。 让我从服务器端代码开始:

下面的类用于创建带有一些随机内容的PDF,并返回等效的字节数组输出流。

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;   
}

}

接下来是控制器代码:在这里,bytearrayoutputstream 被转换为 bytearray,并使用带有适当标头的 response-entity 发送到客户端。
@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");
    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;
}
应将头部设置为“application/pdf”

接下来是客户端代码: 您可以向服务器发出ajax请求,在浏览器的新标签页中打开pdf文件。

 $.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);
            }  
        }); 

OutputStream out = response.getOutputStream(); 没有被使用... - tonyfarney
谢谢,我已经更新了代码,请在它正常工作的情况下点赞 :) - naveen

0

试试这个

@Controller
@RequestMapping("/download")
public class FileDownloadController 
{
    @RequestMapping("/pdf/{fileName}")
    public void downloadPDFResource( HttpServletRequest request, 
                                     HttpServletResponse response, 
                                     @PathVariable("fileName") String fileName) 
    {
        //If user is not authorized - he should be thrown out from here itself
         
        //Authorized user will download the file
        String dataDirectory = request.getServletContext().getRealPath("/WEB-INF/downloads/pdf/");
        Path file = Paths.get(dataDirectory, fileName);
        if (Files.exists(file)) 
        {
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename="+fileName);
            try
            {
                Files.copy(file, response.getOutputStream());
                response.getOutputStream().flush();
            } 
            catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接