Chrome pdf api doesn't download ServletOutputStream jasper pdf file [duplicate] - jsf

This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 6 years ago.
I'm trying to show a web printed report made with JasperReports 6.2.0 in an application with JSF 2.2.
Happens that the report is correctly shown, in a new tab, after setting target="_blank" on my h:form, but the download button doesn't work.
Here's the code:
HttpServletResponse response = (HttpServletResponse) FacesContext context = FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream responseStream = response.getOutputStream();
ByteArrayInputStream relatorioSourceStream = new ByteArrayInputStream(reportJasper);
JasperPrint jp = JasperFillManager.fillReport(relatorioSourceStream, parameters, getConnection());
File file = new java.io.File(path);
if (file.exists()) {
file.delete();
} else if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
file.createNewFile();
}
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jp));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(file));
SimplePdfExporterConfiguration conf = new SimplePdfExporterConfiguration();
exporter.setConfiguration(conf);
exporter.exportReport();
InputStream is = new FileInputStream(file);
int read = 0;
byte[] bytes = new byte[4096];
while ((read = is.read(bytes)) != -1) {
responseStream.write(bytes, 0, read);
}
responseStream.flush();
responseStream.close();
Happens that the report is correctly shown, but the download won't do anything.
It's not quite a "save as" option that I want to be shown when the report tab is loaded, It happens that the chrome api's download button tries to save my page (html) instead of saving the content as a .pdf file.
Thanks in advance.

Successfully generated your error: on chomre:Version 51.0.2704.106 m, You have one alternate way on this. You can directly download such file by using
httpServletResponse.addHeader("Content-disposition", "attachment; filename=" + outputFileName);
command also define file name. Hope will find solution to the problem.

Related

Downloading Excel using POST Rest Service

I'm using REST web services provided by Spring Framework.
I need to download an excel sheet but i also need to donwload the sheet on basis of some selected parameters. I'm sending a request class object as the Body to a POST Rest call(#RequestBody)
I could not download the excel using a POST Method. Please help me to achieve this.
#RequestMapping(value = "/search/export", method = RequestMethod.POST,, produces = MediaType.APPLICATION_JSON_VALUE)
public void searchResultToExcel(#RequestBody SearchRequest searchRequest, HttpServletResponse response, HttpServletRequest request) throws Exception
This is my method signature
I've found this thread Return Excel downloadable file from Spring that may be useful.
I also think that content-type you're forcing (produces = MediaType.APPLICATION_JSON_VALUE) might be in the way, at least as far as I could understand the question. I think you should be forcing for an EXCEL content type there (application/vnd.ms-excel).
It says:
You need to set the Content-Disposition header.
response.setHeader("Content-disposition","attachment; filename=" + yourFileName);
and write your bytes directly to the response OutputStream.
File xls = new File("exported.xls"); // or whatever your file is
FileInputStream in = new FileInputStream(xls);
OutputStream out = response.getOutputStream();
byte[] buffer= new byte[8192]; // use bigger if you want
int length = 0;
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
The above is relatively old. You can construct a ResponseEntity with FileSystemResource now. A ResourceHttpMessageConverter will then copy the bytes, as I have suggested above, for you. Spring MVC makes it simpler for you rather than having you interact with interfaces from the Servlet specification.
#Post
#Path("downloadMyReport")
#Produces("application/excel")
public static Response generatemyExcelReport()throws BusinessException {
try {
File file=null;
Date reportDate=new Date() ;
path="/home/Documents/excelReport/"
file=getReportByName(path);
if(file==null){
logger.info("File is null");
else{
name=capitalizeFirstLater(name);
getReportSummary(reportDate);
FileUtils.writeByteArrayToFile(new File(path),createExcelForReport(fileName,path));
file=getReportByName(path);
}
ResponseBuilder response = Response.ok(file);
response.header("Content-Disposition", "attachment; filename=\"" + fileName2 + "\"");
return response.build();
}
}catch (BusinessException e) {
throw e;
}catch (Exception e) {
logger.error("Exception while generating ExcelSheetForMyReport {}",Utils.getStackTrace(e));
throw new BusinessException("Error in downloading ExcelSheetForMyReport");
}
}
ResponseBuilder response = Response.ok(file);
response.header("Content-Disposition", "attachment; filename=\"" + fileName2 + "\"");
return response.build();

Download user selected file/upload a file to a user selected directory both with primefaces

I want to download user selected files with primefaces. I was able to do so for a specific file as described in the primface showcase for "file Download". But what I actually want is, that after pressing the "download Button" a file dialog should open, so the user can select a file for himself to download. Is that possible?
My current code for a specific file download lokks like this:
public void handleLanguageFileDownload() throws FileNotFoundException, IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
File fileToDownload = new File(DataManager.configreader.getLang_source());
String fileName = fileToDownload.getName();
String contentType = ec.getMimeType(fileName);
int contentLength = (int) fileToDownload.length();
ec.responseReset();
ec.setResponseContentType(contentType);
ec.setResponseContentLength(contentLength);
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream output = ec.getResponseOutputStream();
Files.copy(fileToDownload.toPath(), output);
fc.responseComplete();
}
I want the exact same behaviour for file upload, so the user can select the folder to upload files to for himself. My current implementation uploads the file only to a specific folder.
My current code for uploading files to a specific folder looks like this:
public void handleLanguageFileUpload(FileUploadEvent event) throws IOException {
if (!this.role.canManageLanguage){
return;
}
String [] filePathParts = DataManager.configreader.getLang_source().split("/");
String uploadPathString = DataManager.configreader.getLang_source().replaceAll(filePathParts[filePathParts.length - 1],""); //event.getFile().getFileName()
File uploadPath = new File(uploadPathString);
File fileToUpload = new File(uploadPath, event.getFile().getFileName());
try (InputStream input = event.getFile().getInputstream()) {
if(event.getFile().getFileName().equals(filePathParts[filePathParts.length - 1])) { //fileToUpload.getName()
Files.copy(input, fileToUpload.toPath(), StandardCopyOption.REPLACE_EXISTING);
uiManager.userMessage.info (event.getFile().getFileName() + " " + this.translate("msg_has_been_uploaded") + " !");
this.getOwnTreeVersion();
}
else {
uiManager.userMessage.error (event.getFile().getFileName() + " " + this.translate("msg_is_wrong_cannot_be_uploaded") +": " + filePathParts[filePathParts.length - 1] + " !");
}
}
}
Thank you in advance for your help!!!
working with file chooser is only possible with the Upload method look at this post to understand how to implement it in your project Upload File Step by Step and you can even read more in the Primefaces web site Primefaces Upload File if you need to add a FileSizeLimite and many other features.
Now for the download method i told you that it's impossible because you have a default file location (generally it's Download) you can read more about it in the Primefaces web site Primefaces Download File you can set it manually but it will not be dynamic look at this post Change Download Path.

Java iText Pdf Writer and PrimeFaces Not Refreshing PDF content

Good morning!
I'm using the iText library to create a pdf template and Primefaces to display the content on a web application.
When I ran the first test to see if all the libraries were all set, it was displayed normally. But then I made some changes, and it seems that something is caching my first test in memory and it is the only thing displayed, no matter what changes I make it keeps the same first content. I´ve already cleaned up my netbeans project, closed the IDE and also restarted the computer.
Thats is my tag on the jsf page:
<p:media value="#{atividadeController.pdfContent}" player="pdf" width="100%" height="700px"/>
And here is my method in the managed bean, which is a SessionScoped:
public String preparePdf()
{
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
Font fontHeader = new Font(Font.FontFamily.HELVETICA, 20, Font.BOLD);
Font fontLine = new Font(Font.FontFamily.TIMES_ROMAN, 14);
Font fontLineBold = new Font(Font.FontFamily.TIMES_ROMAN, 14, Font.BOLD);
Document document = new Document();
PdfWriter.getInstance(document, output);
document.open();
//Writing document
Chunk preface = new Chunk("GERAL", fontHeader);
document.add(preface);
Calendar cal = Calendar.getInstance();
cal.setTime(current.getData());
int year = cal.get(Calendar.YEAR);
int month = 1 + cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
String dateStr = day+"/"+month+"/"+year;
Paragraph dataAndHour = new Paragraph(dateStr, fontLine);
document.add(dataAndHour);
document.close();
pdfContent = new DefaultStreamedContent(new ByteArrayInputStream(output.toByteArray()), "application/pdf");
} catch (Exception e) {
e.printStackTrace();
}
return "/views/view_atividade_pdf";
}
There is no exception on the server log.
I really aprecciate any help. Thanks in advance

I can't see pdf generated by DynamicReport

i'm making a pdf report, i'm using Jsf, primefaces, actually i can see the report in a dialog without problems but when i download the pdf, it's can't show. The message from adobe reader is that file is damaged.
This is my code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
DynamicReports.report()
.setTemplate(Plantillas.reportTemplate)
.columns(stateColumn, statePorc)
.title(Templates.createTitleComponent2("Tittle"))
.summary(
DynamicReports.cht.barChart()
.setTitleFont(boldFont)
.setCategory(stateColumn)
.series(
DynamicReports.cht.serie(itemColumn).setSeries(stateColumn)
)
.setCategoryAxisFormat(DynamicReports.cht.axisFormat().setLabel("Label"))
)
.pageFooter(Templates.footerComponent)
.setDataSource(createDataSource3())
.toPdf(baos);
InputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
barStream = new DefaultStreamedContent(inputStream, "application/pdf", "example.pdf");
setBarStream(barStream);
} catch (DRException e) {
e.printStackTrace();
}
set this way to export.
report.toPdf(new FileOutputStream(new File("D:/report11.pdf")));

Sending OutputStream to browser and let browser save it [duplicate]

This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 7 years ago.
I want to export Data from a Rich Faces Data Table I have created outputStream from the data in the Data Table. Now want to send this OutputStream to browser and let it save. How can I do this?
FileOutputStream stream = new FileOutputStream(new File(PATH));
OutputStream out = myMthodToCreateOutPutStream();
Now how to save this out to browser .
It's not clear where you are reading your data from. You need to create an InputStream to read the data.
Then, you first need to set the response headers to
HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");
Use whatever filename you need.
Then set the mime-type:
response.setContentType("application/vnd.ms-excel");
Use the mime-type you need.
Then need to use the response object to get its outputstream -
OutputStream outStream = response.getOutputStream();
Now write to it:
byte[] buf = new byte[4096];
int len = -1;
//Write the file contents to the servlet response
//Using a buffer of 4kb (configurable). This can be
//optimized based on web server and app server
//properties
while ((len = inStream.read(buf)) != -1) {
outStream.write(buf, 0, len);
}
outStream.flush();
outStream.close();

Resources