如何在客户端保存pdf文件?

时间:2018-12-05 22:39:13

标签: java pdf servlets itext report

我有一项已经保存了pdf但已将其保存在服务器中的服务, 我将不胜感激,我尝试使用servlet,但我认为我做得不好 这是我的代码:

@POST
@Path("reporteComisiones")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public void reporteComisiones (Dtorest2 dtorest2) throws DocumentException, FileNotFoundException, ParseException, IOException
{      
        Date fecha = new Date();

        SimpleDateFormat formateador = new SimpleDateFormat("dd-MM-yyyy");
        List<DtoOutrest2> lista = serComisiones(dtorest2);
        Document document = new Document();
        FileOutputStream FOS = new FileOutputStream("C:\\reportes\\"+dtorest2.persona_id+"-"+formateador.format(fecha)+".pdf");
        PdfWriter.getInstance(document, FOS);
        document.open();
        Paragraph titulo = new Paragraph("Reporte Comisiones",FontFactory.getFont(FontFactory.TIMES_BOLD,20,Font.BOLD,BaseColor.BLUE));

        titulo.setAlignment(titulo.ALIGN_CENTER);
        document.add(titulo);
        Paragraph Indicefecha = new Paragraph("Del "+ dtorest2.FechaIni + "hasta el "+ dtorest2.FechaFin,FontFactory.getFont(FontFactory.TIMES_BOLD,12));
        Indicefecha.setAlignment(Indicefecha.ALIGN_CENTER);
        document.add(Indicefecha);
        document.add(new Paragraph("----------------------------------------------------------------------------------------------------------------------------------"));

        document.close();
       /*HttpServletResponse response = null;
       try{ 
            FileInputStream archivo = new FileInputStream("C:/reportes/"+dtorest2.persona_id+"-"+formateador.format(fecha)+".pdf"); 
            int longitud = archivo.available(); 
            byte[] datos = new byte[longitud]; 
            archivo.read(datos); 
            archivo.close(); 
            response.setContentType("application/pdf"); 
            response.setHeader("Content-Disposition","attachment;filename="+dtorest2.persona_id+"-"+formateador.format(fecha)+".pdf"); 
            ServletOutputStream ouputStream = response.getOutputStream(); 
            ouputStream.write(datos); 
            ouputStream.flush(); 
            ouputStream.close(); 
          }catch(Exception e){  
              e.printStackTrace();  
          }  
        */
    }

1 个答案:

答案 0 :(得分:0)

在服务器端生成文件后,您可以将其下载到客户端。此代码可以帮助您:

@RequestMapping(path = "/download", method = RequestMethod.GET)
public ResponseEntity<Resource> download(String param) throws IOException {

    //First generate your file here (jasper, etc)

    InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

    return ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);
}