Open ResponseEntity PDF in new browser tab
SpringBoot 2
Use this code to display the pdf in the browser. (PDF in directory resources -> CLASSPATH) Using ResponseEntity<?>
@GetMapping(value = "/showPDF")
public ResponseEntity<?> exportarPDF( ){
InputStreamResource file = new InputStreamResource(service.exportPDF());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "inline;attachment; filename=ayuda.pdf")
.contentType(MediaType.APPLICATION_PDF)
.body(file);
}
@Service
public class AyudaServiceImpl implements AyudaService {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadPDF.class);
LoadPDF pdf = new LoadPDF();
public InputStream exportPDF() {
LOGGER.info("Inicia metodo de negocio :: getPDF");
return pdf.getPDF();
}
}
---CLASE
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
public class LoadPDF {
private static final Logger LOGGER = LoggerFactory.getLogger(LoadPDF.class);
public InputStream getPDF(){
try {
File file = ResourceUtils.getFile("classpath:ayuda.pdf");
LOGGER.debug("Ruta del archivo pdf: [" + file + "]");
InputStream in = new FileInputStream(file);
LOGGER.info("Encontro el archivo PDF");
return in;
} catch (IOException e) {
LOGGER.error("No encontro el archivo PDF",e.getMessage());
throw new AyudaException("No encontro el archivo PDF", e );
}
}
}
Try
httpServletResponse.setHeader("Content-Disposition", "inline");
But using the responseEntity as follows.
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "attachment; filename=" + fileName)
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(
pdfContents, headers, HttpStatus.OK);
It should work
Not sure about this, but it seems you are using bad the setContentDispositionFormData, try>
headers.setContentDispositionFormData("attachment", fileName);
Let me know if that works
UPDATE
This behavior depends on the browser and the file you are trying to serve. With inline, the browser will try to open the file within the browser.
headers.setContentDispositionFormData("inline", fileName);
Or
headers.add("content-disposition", "inline;filename=" + fileName)
Read this to know difference between inline and attachment