Open generated PDF file into browser tab programmatically - jsf

I have created Pdf file on click action of Print button using Apache PDFBox api as shown below. As of now I saved that file into my drive(file system). What I need is to open up Pdf file directly into browser without saving into drive so that it can be print or download as require.
TestPdfBean.java
#ManagedBean(name = "pdfBean")
#ViewScoped
public class TestPdfBean implements Serializable {
public void createAndOpenPdf() {
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDFont font = PDType1Font.HELVETICA;
PDPageContentStream content = new PDPageContentStream(doc,page);
content.beginText();
content.setFont(font, 12);
content.moveTextPositionByAmount(100, 700);
content.drawString(" Generating Pdf content...");
content.endText();
content.close();
document.save("/home/ck/Test/test.pdf");
document.close();
}
}
Code snippet of test.xhtml
<h:form id="pdfForm">
<p:panelGrid columns="2">
<h:outputText value="Create Pdf file.." />
<p:commandButton value="Print" actionListener="#{pdfBean.createAndOpenPdf}" />
</p:panelGrid>
</h:form>
I have deployed above portlet into liferay-portal-6.1.1.
Is there any way to open up pdf file directly into browser by Primefaces Or by Jsf Or by Liferay ?

I would recommend that you take a look at the Liferay Faces jsf2-export-pdf-portlet demo for Liferay 6.1. It has an example of a JSF 2.x ResourceHandler that enables the PDF to be generated and downloaded.

Create an HttpServlet and give back the PDF in the response.
Then just link your commandButton to the URL of the servlet and you´re done ...

The browser will open the document if you return a ByteArrayOutputStream.
`FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachement;filename=Quote_.pdf");
response.encodeRedirectURL("_blank");
byte[] bytes = printPDFBean.createQuotationPDF(current, cfgDoc, cfgEntity, quoteDetailList, customer).toByteArray();
response.getOutputStream().write(bytes);
context.responseComplete();`
This code calls my createQuotationPDF method which returns ByteArrayOutputStream object. The issue is, the document is opened in the current window and not a new one.
`public ByteArrayOutputStream createQuotationPDF(Quotation currentQuote, CfgDoc cfgDoc, CfgEntity cfgEntity, List<QuotationDetail> quoteDetailList, Customer customer) {
String filePath = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/");
String imagesFolder = filePath + FacesContext.getCurrentInstance().getExternalContext().getInitParameter("smefin.images");
String fontsFolder = filePath + FacesContext.getCurrentInstance().getExternalContext().getInitParameter("smefin.fonts");
PDDocument doc = null;
PDPage page = null;
ByteArrayOutputStream output;
output = new ByteArrayOutputStream();
try {
doc = new PDDocument();
page = new PDPage();
doc.addPage(page);
File fontLatoBlackFile = new File(fontsFolder + "Lato-Black.ttf");
File fontLatoLiteFile = new File(fontsFolder + "Lato-Light.ttf");
Encoding encoding = new WinAnsiEncoding();
PDFont fontLatoBold = PDTrueTypeFont.load(doc, fontLatoBlackFile, encoding);
PDFont fontLatoLite = PDTrueTypeFont.load(doc, fontLatoLiteFile, encoding);
content.beginText();
content.setFont(fontLatoBold, 11);
content.newLineAtOffset(50, 60);
content.showText("Text");
content.endText();
}
doc.save("D:/TestData/Quote_.pdf");
doc.close();
} catch (Exception e) {
System.out.println("" + e);
}
return output;
}`

Related

Primefaces Handle error on media PDF load

Is it possible to somehow handle error on loading a PDF?
<p:media value="/resources/media/myDoc.pdf" width="100%" height="800px" zoom="100" player="pdf" cache="false"<>/p:media>
Let's say the PDF document it's not there and won't find it, If that happens my web app crash. Possible to handle it? So I show an error message instead in growl for example?
Thanks
You can check the #Jasper de Vries comment, otherwise you can verify if the file is present using a bean method like this:
MyBean.java
public String findFileURL() {
String fileName = "myDoc.pdf";
String relativeWebPath = "/resources/media/" + fileName;
FacesContext facesContext = FacesContext.getCurrentInstance();
String absoluteDiskPath = ((ServletContext) facesContext.getExternalContext().getContext())
.getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
if (file.isFile()) {
return relativeWebPath;
} else {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "File: " + fileName + " not found.", "");
facesContext.addMessage(null, message);
return "";
}
}
MyPage.xhtml
<p:media value="#{myBean.findFileURL()}" width="100%" height="800px" zoom="100" player="pdf" cache="false"/>

How to show two pdf in differents tabs from java

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

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.

JSF not showing "save as" browser popup when downloading files using faces context [duplicate]

As soon as I add the librarys icefaces.jar icepush.jar icefaces_ace.jar to my classpath in order to use ACE components, my SaveAs dialog won't popup? I'm not sure if this is a bug but without the librarys in classpath it works. Here's my save as method :
public void downloadFile(String propertyPath) throws IOException {
ProxyFile fileToDownload = repBean.downloadFile(propertyPath);
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.reset(); response.setContentType(fileToDownload.getContentType());
response.setHeader("Content-Length", String.valueOf(fileToDownload.getLength()));
response.setHeader("Content-disposition", "attachment; filename=\"" + fileToDownload.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
input = new BufferedInputStream(fileToDownload.getContent());
output = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[10240];
for (int length; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
} finally {
output.close();
input.close();
facesContext.responseComplete();
}
}
You can't download files using ajax.
Ajax is under the covers executed by JavaScript's XMLHttpRequest object. The request will be successfully executed and the response will be successfully retrieved. However, JavaScript has no facility to write the response to client's disk file system, nor to force a Save As dialogue with the given response. That would be a huge security breach.
The cause of your concrete problem is ICEfaces itself. Namely, when you integrate ICEfaces in a JSF web application, all standard <h:commandXxx> links/buttons will silently be turned into ajax-enabled ones which indeed causes confusion among starters. Make sure that the download link/button isn't implicitly using ICEfaces-introduced ajax facility. As per their wiki page on the subject, you need to explicitly nest a <f:ajax disabled="true"> to disable this.
Disable Ajax for a Component
You can also disable Ajax at the level of the individual component:
<h:commandButton value="Send" actionListener="#{bean.sendMessage}">
<f:ajax disabled="true"/>
</h:commandButton>
Apply it on your download link/button.

How to provide a file download from a JSF backing bean?

Is there any way of providing a file download from a JSF backing bean action method?
I have tried a lot of things. Main problem is that I cannot figure how to get the OutputStream of the response in order to write the file content to. I know how to do it with a Servlet, but this cannot be invoked from a JSF form and requires a new request.
How can I get the OutputStream of the response from the current FacesContext?
Introduction
You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.
On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.
Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.
Turn off ajax / don't use remote command!
You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.
In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.
Generic JSF 2.x example
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = ec.getResponseOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
Generic JSF 1.x example
public void download() throws IOException {
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();
response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.
OutputStream output = response.getOutputStream();
// Now you can write the InputStream of the file to the above OutputStream the usual way.
// ...
fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}
Common static file example
In case you need to stream a static file from the local disk file system, substitute the code as below:
File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();
// ...
Files.copy(file.toPath(), output);
Common dynamic file example
In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.
E.g. iText PDF:
String fileName = "dynamic.pdf";
String contentType = "application/pdf";
// ...
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();
E.g. Apache POI HSSF:
String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";
// ...
HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();
Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.
Utility method
If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).
public void download() throws IOException {
Faces.sendFile(file, true);
}
Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.
public void download() throws IOException
{
File file = new File("file.txt");
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) facesContext.getExternalContext().getResponse();
response.reset();
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=file.txt");
OutputStream responseOutputStream = response.getOutputStream();
InputStream fileInputStream = new FileInputStream(file);
byte[] bytesBuffer = new byte[2048];
int bytesRead;
while ((bytesRead = fileInputStream.read(bytesBuffer)) > 0)
{
responseOutputStream.write(bytesBuffer, 0, bytesRead);
}
responseOutputStream.flush();
fileInputStream.close();
responseOutputStream.close();
facesContext.responseComplete();
}
This is what worked for me:
public void downloadFile(String filename) throws IOException {
final FacesContext fc = FacesContext.getCurrentInstance();
final ExternalContext externalContext = fc.getExternalContext();
final File file = new File(filename);
externalContext.responseReset();
externalContext.setResponseContentType(ContentType.APPLICATION_OCTET_STREAM.getMimeType());
externalContext.setResponseContentLength(Long.valueOf(file.lastModified()).intValue());
externalContext.setResponseHeader("Content-Disposition", "attachment;filename=" + file.getName());
final HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
FileInputStream input = new FileInputStream(file);
byte[] buffer = new byte[1024];
final ServletOutputStream out = response.getOutputStream();
while ((input.read(buffer)) != -1) {
out.write(buffer);
}
out.flush();
fc.responseComplete();
}
This is my solution, an extension of BalusC's answer
public static void download(
ByteArrayOutputStream baos,
String downloadFileName,
String contentType
) {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
externalContext.responseReset();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
response.reset();
response.setContentType(contentType);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
Integer size = baos.size();
response.setHeader("Content-Length", size.toString());
response.setHeader(
"Content-Disposition",
"attachment; filename=\"" + downloadFileName + "\""
);
try {
try (OutputStream responseOs = response.getOutputStream()) {
baos.writeTo(responseOs);
}
}
catch (IOException e) {
throw new IOUncheckedException(e);
}
context.responseComplete();
}
here is the complete code snippet http://bharatonjava.wordpress.com/2013/02/01/downloading-file-in-jsf-2/
#ManagedBean(name = "formBean")
#SessionScoped
public class FormBean implements Serializable
{
private static final long serialVersionUID = 1L;
/**
* Download file.
*/
public void downloadFile() throws IOException
{
File file = new File("C:\\docs\\instructions.txt");
InputStream fis = new FileInputStream(file);
byte[] buf = new byte[1024];
int offset = 0;
int numRead = 0;
while ((offset < buf.length) && ((numRead = fis.read(buf, offset, buf.length -offset)) >= 0))
{
offset += numRead;
}
fis.close();
HttpServletResponse response =
(HttpServletResponse) FacesContext.getCurrentInstance()
.getExternalContext().getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=instructions.txt");
response.getOutputStream().write(buf);
response.getOutputStream().flush();
response.getOutputStream().close();
FacesContext.getCurrentInstance().responseComplete();
}
}
You may change the file reading logic in case you want file to get generated at runtime.

Resources