tutorial requestmapping proyecto mvc jasperreports jasperreport framework example espaƱol ejemplo crear java spring spring-mvc itext response

java - proyecto - requestmapping spring boot



Devuelve pdf generado usando Spring MVC (1)

Estoy usando Spring MVC. Tengo que escribir un servicio que tome la información del cuerpo de la solicitud, agregue los datos al pdf y devuelva el archivo pdf al navegador. El documento pdf se genera utilizando itextpdf. ¿Cómo puedo hacer esto usando Spring MVC? He intentado usar esto

@RequestMapping(value="/getpdf", method=RequestMethod.POST) public Document getPDF(HttpServletRequest request , HttpServletResponse response, @RequestBody String json) throws Exception { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment:filename=report.pdf"); OutputStream out = response.getOutputStream(); Document doc = PdfUtil.showHelp(emp); return doc; }

función de demostración de ayuda que genera el pdf. Solo estoy poniendo algunos datos aleatorios en el pdf por el momento.

public static Document showHelp(Employee emp) throws Exception { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("C:/tmp/report.pdf")); 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 document; }

Estoy seguro de que esto está mal. Quiero que se genere el pdf y que se abra el cuadro de diálogo de abrir / abrir a través del navegador, para que pueda almacenarse en el sistema de archivos del cliente. Por favor, ayúdame.


Estabas en el camino correcto con response.getOutputStream() , pero no estás usando su salida en ningún lugar de tu código. Esencialmente, lo que necesita hacer es transmitir los bytes del archivo PDF directamente a la secuencia de salida y purgar la respuesta. En primavera puedes hacerlo así:

@RequestMapping(value="/getpdf", method=RequestMethod.POST) public ResponseEntity<byte[]> getPDF(@RequestBody String json) { // convert JSON to Employee Employee emp = convertSomehow(json); // generate the file PdfUtil.showHelp(emp); // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp byte[] contents = (...); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.parseMediaType("application/pdf")); String filename = "output.pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(contents, headers, HttpStatus.OK); return response; }

Notas:

  • use nombres significativos para sus métodos: nombrar un método que escriba un documento PDF showHelp no es una buena idea
  • leyendo un archivo en un byte[] : ejemplo here
  • Sugeriría agregar una cadena al azar al nombre temporal del archivo PDF dentro de showHelp() para evitar sobrescribir el archivo si dos usuarios envían una solicitud al mismo tiempo