簡體   English   中英

如何在 spring mvc 中下載 PDF 文件?

[英]How can i download the PDF file in spring mvc?

這是我的文件路徑

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

}

你可以嘗試這樣的事情:

@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>

方法在這里,希望能幫到你。

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

您需要創建 AbstractPdfView 的實現來實現這一點。您可以參考此鏈接https://www.mkyong.com/spring-mvc/spring-mvc-export-data-to-pdf-file-via-abstractpdfview/

這是您問題的詳細答案。 讓我從服務器端代碼開始:

下面的類用於創建具有一些隨機內容的 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 並使用帶有適當標頭的響應實體發送到客戶端。

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

標題應設置為“應用程序/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);
            }  
        }); 

嘗試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM