How to show two pdf in differents tabs from java - jsf

Sorry for my poor english but I really want to show two pdf reports from jasper report at the same time in differents tabs on browser. I´m working with java jsf, primefaces. The principal idea is when the button is clicked show this reports in diferents tabs. I try to do this:
I have this in the Managed Bean:
public void showReports() {
RequestContext.getCurrentInstance().execute("document.getElementById('fromGeneral:rep2').click();");
RequestContext.getCurrentInstance().execute("document.getElementById('fromGeneral:rep3').click();");
}
public void printReport(String name) {
try {
Map<String, Object> mapParametros = new HashMap<>();
mapParametros.put("CORR", corr);
printJasper(mapParametros, new File("/Jasper/Reports/" + name));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void printJasper(Map<String, Object> reportValues, File fileJ) {
ByteArrayInputStream input = null;
BufferedOutputStream output = null;
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
try {
facesContext = FacesContext.getCurrentInstance();
externalContext = facesContext.getExternalContext();
response = (HttpServletResponse) externalContext.getResponse();
FileInputStream file = new FileInputStream(fileJ);
JasperReport compiledTemplate = (JasperReport) JRLoader.loadObject(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
JasperPrint jasperPrint = JasperFillManager.fillReport(compiledTemplate, reportValues, dataSourceP.getConnection());
JRExporter exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
exporter.setParameter(JRPdfExporterParameter.PDF_JAVASCRIPT, "this.print();");
exporter.exportReport();
input = new ByteArrayInputStream(out.toByteArray());
response.reset();
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(out.toByteArray().length));
response.setHeader("Content-Disposition", "inline; filename=\"ticket.pdf\"");
output = new BufferedOutputStream(response.getOutputStream(), Constants.DEFAULT_BUFFER_SIZE);
byte[] buffer = new byte[Constants.DEFAULT_BUFFER_SIZE];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
} catch (Exception exception) {
System.out.println(exception.getMessage());
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
} catch (Exception exception) {
/* ... */
}
}
facesContext.responseComplete();
}
An this in my view:
<h:form>
<p:commandButton value="Show them" action="#{reportBean.showReports()}"/>
<p:commandButton value="REPORT 1" id="rep1" style="font-size: 25px; float:right;visibility: hidden;" action="#{reportBean.printReport("Report1")}" ajax="false" onclick="this.form.target = '_blank';"/>
<p:commandButton value="REPORT 2" id="rep2" style="font-size: 25px; float:right;visibility: hidden;" action="#{reportBean.printReport("Report2")}" ajax="false" onclick="this.form.target = '_blank';"/>
</h:form>
But doesn´t work, it just show the second report.
Help!.
Thanks!

Try a hit using p:commandLink like i am using.
<p:commandLink id="PreviewR1" value="Print Preview" ajax="false" action="#{reportBean.printReport("Report1")}" target="_blank" />
<p:commandLink id="PreviewR2" value="Print Preview" ajax="false" action="#{reportBean.printReport("Report2")}" target="_blank" />
It will open the report 1 & 2 in separate browser tab while your original web page will remains the same.

You just don't click the correct buttons:
public void showReports() {
RequestContext.getCurrentInstance().execute("document.getElementById('fromGeneral:rep2').click();");
RequestContext.getCurrentInstance().execute("document.getElementById('fromGeneral:rep3').click();");
}
You're clicking on rep2 and rep3. rep3 doesn't exists, you need to click on rep1 instead. That should be the reason why only the 2nd report is shown.

Finally I found other way to solve it.
The method showReports() instead to click two buttons, this open two xhtml that each one has inside of <h.form> a remotecommand with autorun true, that show the reports. I don´t know if it´s the best way to do it, but It works.
Thanks for all your comments

Related

How to display pdf on JSF

Hi my code is as follows:
public StreamedContent getTempPdfFile() throws IOException {
File testPdfFile = new File("D:\\AFC150_20180819_0103.pdf");
streamedContent = new DefaultStreamedContent(new FileInputStream(testPdfFile), "application/pdf",
"AFC150_20180819_0103.pdf");
return streamedContent;
}
<h:panelGrid columns="1" cellpadding="5">
<p:media value="#{realReport.tempPdfFile}" player="pdf" width="1000px" height="300px">
<f:param name="id" />
</p:media>
</h:panelGrid>
But the PDF file is not getting displayed on the page.
Here is my sample, hope it helps, the code has the inline and attachment:
void sendBackPDFToClient()
{
//File temp = File.createTempFile(fileName, ".pdf");
File testPdfFile = new File("D:\AFC150_20180819_0103.pdf");
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/pdf");
ec.setResponseContentLength((int)testPdfFile.length());
//Inline
//ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + testPdfFile.getName() + "\"");
//Attach for Browser
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + testPdfFile.getName() + "\"");
OutputStream output = ec.getResponseOutputStream();
Files.copy(testPdfFile.toPath(), output);
fc.responseComplete();
}
Have you tried the Document Viewer component of PrimeFaces Extensions?
I think its much easier to use than p:media and offers more features including ability to load it from a URL, a Stream, or a Resource. That basic example shows you how to do it with all 3 types.
JAVA:
public StreamedContent getTempPdfFile() throws IOException {
File testPdfFile = Paths.get("D:\\AFC150_20180819_0103.pdf").toFile();
return new DefaultStreamedContent(new FileInputStream(testPdfFile), "application/pdf",
"AFC150_20180819_0103");
}
XHTML:
<pe:documentViewer height="500" width="1000" value="#{realReport.tempPdfFile}"/>

the web camera in primefaces is not increse either the width or the heigh of the camera in primefaces code blow

in primefaces web camera is not increase the size of the photo or the camera in JSF code how to solve this proble
<p:photoCam widgetVar="pc" listener="#{photoCamView.oncapture}" update="photo" />
<p:commandButton type="button" value="Capture" onclick="PF('pc').capture()"/>
<p:outputPanel id="photo">
<p:graphicImage name="#{photoCamView.filename}" rendered="#{not empty photoCamView.filename}"/>
</p:outputPanel>
</h:form>
<br />
and the Java code is
public void oncapture(CaptureEvent captureEvent) {
filename = getRandomImageName();
byte[] data = captureEvent.getData();
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
System.out.println("HH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!11");
File newFileName = new File("C:\\Users\\adane\\Desktop\\PhotoCam\\Image"+filename + ".jpeg");
FileImageOutputStream imageOutput;
try {
imageOutput = new FileImageOutputStream(newFileName);
imageOutput.write(data, 0, data.length);
imageOutput.close();
}
catch(IOException e) {
throw new FacesException("Error in writing captured image.", e);
}
}

How to display PDF in JSF, with content from ServletResponse

In my application, I use jsf & richfaces, I want to display a generated pdf in web browser , I have generated this PDF in serverside and it is available in ServletResponse, but I am unable to display it in my web page.
I have tried this question but, it did not solve my problem.
Is there any libraries or special ways to do this?
What I have tried to do is given below.
<h:commandLink rendered="#{ fileImportOptionsViewBean.isFileExist(status.myPdf) }" action="#
{fileImportOptionsViewBean.downloadFile(satus.myPdf)}" target="_blank">
<h:graphicImage url="../../resources/xyz/icons/pdf.png" /></h:commandLink>
downloadFile method
public void downloadFile(String filePath){
try {
File file=new File(filePath);
if(file.exists()){
FacesContext fc=FacesContext.getCurrentInstance();
ExternalContext ec=fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/pdf");
ec.setResponseHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
ec.setResponseBufferSize(8192);
OutputStream output = ec.getResponseOutputStream();
URL url = file.toURL();
try(
BufferedInputStream bis = new BufferedInputStream(url.openStream());
BufferedOutputStream bos = new BufferedOutputStream(output);
){
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}
fc.responseComplete();
}
} catch (Exception e) {
}
}
Any help is appreciated,Thanks.
I don't see anything wrong with your current setup.Most probably the problem lies in your XHTML page and something is causing your h:commandLink not to fire the event.Please refer this post for further details,surely this will be of some help to you.

How to Download *.txt or *.log file in JSF [duplicate]

This question already has answers here:
How to provide a file download from a JSF backing bean?
(5 answers)
Closed 5 years ago.
I want to download a .txt/.log file saved in hard disk in JSF, am not getting any error but the issue is am not able to download the file, need some help..
note : am trying to zip the file first and then download.
I have tried :
response.setContentType("text/html");
response.setContentType("text/plain");
Code in page.xhtml:
<h:form>
<a4j:outputPanel id="downloadPanel">
<table><tr>
<td>
<h:commandButton id="dldFiles" title="Download File" image="/images/download.png"
style="width:20px; height:20px;"/>
</td>
<td>
<h:outputText value="Download log file" style="font-size: 11px; color:#56ADF8; font-weight: bold; cursor:pointer;"/>
</td>
</tr></table>
<a4j:support event="onclick" action="#{sqlLoaderAction.downloadFile}" reRender="uploadForm"></a4j:support>
</a4j:outputPanel>
</rich:panel>
</h:form>
In Actin Bean Methods:
public String downloadFile(){
System.out.println("--inside exportGoogleFeed--");
FacesContext fc = FacesContext.getCurrentInstance();
try{
User user = getUserBean();
Object sp = getServiceProxy(user);
HttpServletResponse response = ((HttpServletResponse)fc.getExternalContext().getResponse());
fc.responseComplete();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=downloadname.zip");
OutputStream respOs = response.getOutputStream();
String dldFileName = "SQLLDR_28.txt";
PrintWriter pw1 = new PrintWriter(new FileWriter(dldFileName , false));
BufferedReader readbuffer = new BufferedReader(new FileReader("D:/Sqlldr_Container/downloadFile.txt"));
String strRead;
while((strRead=readbuffer.readLine())!=null){
pw1.println(strRead);
}
pw1.close();
File fil = new File(dldFileName);
ZipUploadStatusFile(dldFileName, respOs);
boolean bool = fil.delete();
System.out.println("-------Temp file Created deleted - "+bool+" ------------");
readbuffer.close();
}
catch (UnAuthenticatedException e) {
e.printStackTrace();
} /*catch (UnAuthorizedAccessException e) {
e.printStackTrace();
}*/ catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void ZipUploadStatusFile(String fileName, OutputStream respOs){
try{
ZipOutputStream out = new ZipOutputStream(respOs);
byte[] data = new byte[1000];
BufferedInputStream in = new BufferedInputStream
(new FileInputStream(fileName));
int count;
out.putNextEntry(new ZipEntry(fileName));
while((count = in.read(data,0,1000)) != -1){
out.write(data, 0, count);
}
in.close();
out.flush();
out.close();
System.out.println("Your file is zipped");
}catch(Exception e){
e.printStackTrace();
}
}
After executing the above method am getting below screen:
Thank you.....
You can't download files by ajax. JavaScript has due to security reasons no facilities to force a Save As dialogue. The best it could do in your particular case is to display the response inline.
Get rid of the <a4j:support> and make it a fullworthy synchronous request by putting the action method straight in the <h:commandButton>.
This is the code that will fulfill the needs of downloading text file in to client system.
public String downloadFileText() {
File file = new File(GlobalPath);
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setHeader("Content-Disposition", "attachment;filename=file.txt");
response.setContentLength((int) file.length());
ServletOutputStream out = null;
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
out = response.getOutputStream();
int i = 0;
while ((i = input.read(buffer)) != -1) {
out.write(buffer);
out.flush();
}
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
return null;
}
I dont think that the code will run fine because the code is in JSF MAnaged beans and it is running at server side, so file will be downloaded at the system where application server is running, now what you need to do is to check , use two pcs,
In one pc deploy the web and try to download file from other pc, then check the behaviour of code, if the file could be downloaded in client pc then thats fine other wise you need to find alternatives

JSF PrimeFaces FileDownload problem

I'm using PrimeFaces for a new project and it's quite an impressive set of components.
Anyway, I have problem with "real world" use of filedownload component.
In my page I have a datalist that shows the attachments related to a particular document, and I want provide a link to directly download that file inside the datalist item.
Here's my xhtml code:
<p:dataList id="ListaAllegati" value="#{documentBean.documento.allegati}" type="definition" var="attach" style="border: none" ">
<f:facet name="description">
<h:outputText value="#{attach.name}" />
<p:commandLink ajax="false" title="Download" action="#{documentBean.selectAttach}>
<h:graphicImage style="margin-left: 10px; border: none" value="./images/article.png" height="24" width="24" ></h:graphicImage>
<p:fileDownload value="#{documentBean.downloadFile}"/>
<f:setPropertyActionListener target="#{documentBean.selectedAttach}" value="#{attach}" />
</p:commandLink>
</f:facet>
</p:dataList>
and the relative java bean (request scoped):
private StreamedContent downloadFile;
public StreamedContent getDownloadFile() {
log.info("getter dell'allegato invocato");
InputStream stream = null;
byte[] rawFile = null;
if (selectedAttach == null) {
log.warn("Nessun allegato passato");
return null;
} else {
try {
log.info("Recupero del file " + selectedAttach.getGuid());
rawFile = attachManager.retrieveFile(selectedAttach.getGuid());
} catch (Exception e) {
String msg = "Errore durante il recupero del file";
log.error(msg, e);
FacesMessage fmsg = new FacesMessage(msg, "");
FacesContext.getCurrentInstance().addMessage(null, fmsg);
}
stream = new ByteArrayInputStream(rawFile);
DefaultStreamedContent file = new DefaultStreamedContent(stream,
selectedAttach.getMimeType(), selectedAttach.getName());
return file;
}
}
public void selectAttach() {
log.info("commandLink action invocata");
}
private Allegato selectedAttach;
public Allegato getSelectedAttach() {
return selectedAttach;
}
public void setSelectedAttach(Allegato selectedAttach) {
log.info("Allegato selezionato");
if (selectedAttach==null) log.warn("L'allegato passato è nullo");
this.selectedAttach = selectedAttach;
}
So, couple of question:
Am I doing the right thing trying to pass the selected attachment that way? Otherwise, how can I pass a parameter to tell the bean wich attachment has been clicked?
Why the first time I click the command link, nothing happen? It make a roundtrip with server, but nothing happens. Second time, it gives me an exception.
Why documentBean.selectAttach is never called and the documentBean.selectedAttach property is never set (neither the second time)?
Thanks to anyone for any hint
How to get the row object from the datatable is answered in this question:
How can I pass selected row to commandLink inside dataTable?
This answers basically all the three questions.
As to the exception in the second click, that's likely because you didn't return from the catch block when an exception is been thrown in your getDownloadFile() method. You're continuing the remnant of the code flow while the rawFile is still null. Fix it accordingly as well. Add a return null to the end of catch or something. Better yet, you should be posting the entire stacktrace in the question as you don't seem to be able to understand it. It basically already contains the answer :)
Primefaces has its own dedicated servlet for file download and upload components that handle all of this asynchronously.
Try doing something like what I have in my code
<p:commandLink ajax="false" actionListener="#{managedBean.downloadAction(object)}">
<span class="ui-icon icoFolderGo" style="padding-right: 1.5em;" />
<p:fileDownload value="#{managedBean.downloadContentProperty}" />
</p:commandLink>
And in the managed bean,
public void downloadAction(Object object) {
try {
InputStream stream = // get input stream from argument
this.setDownloadContentProperty(new DefaultStreamedContent(stream, "application/pdf", "filename.pdf");
} catch (Exception e) {
log.error(e);
}
}
public void setDownloadContentProperty(StreamedContent downloadContentProperty) {
this.downloadContentProperty = downloadContentProperty;
}
public StreamedContent getDownloadContentProperty() {
return downloadContentProperty;
}

Resources