jasper pdf report does not show up - pdf

my JSF 2.0 web application is intended to produce PDF reports.
the problem is that no PDF report is shown up in the explorer window.
I am using eclipse kepler, with apache-tomcat-7.0.52 and the version of jasper Ireport is 4.8
any help would be appreciated.
I will provide the whole java class :
package khldqr.beans;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
#ManagedBean
#SessionScoped
public class TestReport {
private List<Refugee> refugee;
public List<Refugee> connectRefugeeData() {
ResultSet rs = null;
PreparedStatement pst = null;
Connection con = Database.getConnection();
String stm = "Select R_NO, F_P_Name from M_MAIN_INFO where R_NO < 10";
refugee = new ArrayList<Refugee>();
try {
pst = con.prepareStatement(stm);
pst.execute();
rs = pst.getResultSet();
while (rs.next()) {
Refugee refugeelist = new Refugee();
refugeelist.setR_NO(rs.getInt(1));
refugeelist.setF_P_Name(rs.getString(2));
refugee.add(refugeelist);
}
} catch (SQLException e) {
e.printStackTrace();
}
return refugee;
}
public void PDF(ActionEvent actionEvent) throws IOException, JRException {
System.out.println("this is not my lucky day!!!!!");
File jasper = new File(FacesContext.getCurrentInstance().getExternalContext().getRealPath("report/Majd.jasper"));
byte[] bytes = JasperRunManager.runReportToPdf(jasper.getPath(),null,new JRBeanCollectionDataSource(refugee));
HttpServletResponse response =(HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
outputStream.write(bytes, 0 , bytes.length);
outputStream.flush();
outputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}
public TestReport() {
connectRefugeeData();
}
public List<Refugee> getRefugee() {
return refugee;
}
public void setRefugee(List<Refugee> refugee) {
this.refugee = refugee;
}
}
and here is xhtml file:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Hello To GOPA World!!</title>
</h:head>
<h:body dir="rtl">
<h:form>
<p:commandButton value = "PDF" actionListener="#{testReport.PDF}"></p:commandButton>
</h:form>
<h:dataTable value="#{testReport.refugee}" var="var">
<h:column>
<h:outputText value="#{var.r_NO}"></h:outputText>
</h:column>
<h:column >
<h:outputText value="#{var.f_P_Name}"></h:outputText>
</h:column>
</h:dataTable>
</h:body>
</html>
I can see the message on the console and the page gets refreshed but no PDF report is come up the explorer screen
I have replaced the above PDF method with the code below, but in vain, the same result: no PDF report is coming up the explorer screen.
JasperPrint jasperPrint;
public void init() throws JRException{
JRBeanCollectionDataSource beanCollectionDataSource=new JRBeanCollectionDataSource(refugee);
String reportPath= "e:\\Rita.jasper";
jasperPrint=JasperFillManager.fillReport(reportPath, new HashMap(),beanCollectionDataSource);
}
public void PDF(ActionEvent actionEvent) throws JRException, IOException{
init();
HttpServletResponse httpServletResponse=(HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
// httpServletResponse.addHeader("Content-disposition", "attachment; filename=report.pdf");
FacesContext.getCurrentInstance().getExternalContext().setResponseContentType("‌​application/pdf");
ServletOutputStream servletOutputStream=httpServletResponse.getOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
System.out.println("All done the report is done");
servletOutputStream.flush();
servletOutputStream.close();
FacesContext.getCurrentInstance().responseComplete();
}

the code is correct, and there is nothing wrong with it.
the problem was some kind of security issue.
I faced the above problem when the report was in a full access folder to all users.
put when I put both of the requested xhtml and the report in a secured folder, everything went OK.
I don't know why!! but that was the case with me.
hoping others will make use of this.
thx.

<p:commandButton value = "PDF" actionListener="#{testReport.PDF}" ajax="false" type="submit"></p:commandButton>
you cant use ajax when calling jasperReports

Related

docx to PDF conversion using docx4j

I am trying to convert docx file to pdf using docx4j. But I am getting an error
What I found that docx4j older versions were not able to support shapes inserted in the docs for pdf conversion.
Does any current version of docx4J, documents4j and docx4j-export-fo combination has these supported?
In the input file there were few lines drawn or inserted, as a place holder to populate values, these lines are erroring out while converting to PDF
```
import org.docx4j.Docx4J;
import org.docx4j.Docx4jProperties;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
public class Main {
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
public static final int FLAG_EXPORT_PREFER_XSL = 0;
public static void main(String[] args) {
Docx4jProperties.setProperty(
"com.plutext.converter.URL",
"https://converter-eval.plutext.com:443/v1/00000000-0000-0000-0000-000000000000/convert");
try {
InputStream templateInputStream = new FileInputStream("C:\\Documents\\Output_docx\\Directors.docx");
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
String outputfilepath = "C:\\Documents\\Output_docx\\Example_output_2.pdf";
FileOutputStream os = new FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
os.flush();
os.close();
} catch (Throwable e) {
LOGGER.warn("Conversion Error!");
e.printStackTrace();
}
}
}
```
See https://www.docx4java.org/blog/2020/09/office-pptxxlsxdocx-to-pdf-to-in-docx4j-8-2-3/ which compares the 3 approaches for generating PDF output.
In summary to handle those objects, use the documents4j approach (which uses Word), or Microsoft Graph.

Add a watermark on a pdf that contains images using pdfbox (1.7)

I have used the code suggested in:
PDFBox Overlay fails
to add a watermark to an existing pdf.
Unfortunately, the pdf produced is corrupted. The pdf reader complains when I open the document: "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem".
The document is opened but it does not show the images.
It seems to happen with all the pdfs. It could be worth saying that it happens also with a different implementation that simply uses the Overlay class.
The following url points to a pdf that I used for my testing:
A pdf with an image
The code to test this transformation is:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.PDExtendedGraphicsState;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectForm;
import org.apache.pdfbox.util.MapUtil;
/**
* This test is about overlaying with special effect.
*
* #author mkl
*/
public class OverlayWithEffect
{
final static File RESULT_FOLDER = new File("target/test-outputs", "assembly");
public static void overlayWithDarkenBlendMode(PDDocument document, PDDocument overlay) throws IOException
{
PDXObjectForm xobject = importAsXObject(document, (PDPage) overlay.getDocumentCatalog().getAllPages().get(0));
PDExtendedGraphicsState darken = new PDExtendedGraphicsState();
darken.getCOSDictionary().setName("BM", "Darken");
List<PDPage> pages = document.getDocumentCatalog().getAllPages();
for (PDPage page: pages)
{
if (page.getResources() == null) {
page.setResources(page.findResources());
}
if (page.getResources() != null) {
Map<String, PDExtendedGraphicsState> states = page.getResources().getGraphicsStates();
if (states == null) {
states = new HashMap<String, PDExtendedGraphicsState>();
}
String darkenKey = MapUtil.getNextUniqueKey(states, "Dkn");
states.put(darkenKey, darken);
page.getResources().setGraphicsStates(states);
PDPageContentStream stream = new PDPageContentStream(document, page, true, false, true);
stream.appendRawCommands(String.format("/%s gs ", darkenKey));
stream.drawXObject(xobject, 0, 0, 1, 1);
stream.close();
}
}
}
public static PDXObjectForm importAsXObject(PDDocument target, PDPage page) throws IOException
{
final PDStream xobjectStream = new PDStream(target, page.getContents().createInputStream(), false);
final PDXObjectForm xobject = new PDXObjectForm(xobjectStream);
xobject.setResources(page.findResources());
xobject.setBBox(page.findCropBox());
COSDictionary group = new COSDictionary();
group.setName("S", "Transparency");
group.setBoolean(COSName.getPDFName("K"), true);
xobject.getCOSStream().setItem(COSName.getPDFName("Group"), group);
return xobject;
}
public static void main(String[] args) throws COSVisitorException, IOException
{
InputStream sourceStream = new FileInputStream("x:/pdf-test.pdf");
InputStream overlayStream = new FileInputStream("x:/draft.pdf");
try {
final PDDocument document = PDDocument.load(sourceStream);
final PDDocument overlay = PDDocument.load(overlayStream);
overlayWithDarkenBlendMode(document, overlay);
document.save("x:/da-draft-5.pdf");
document.close();
}
finally {
sourceStream.close();
overlayStream.close();
}
}
}
I am using version 1.7 of pdfbox.
Thanks
As suggested by mkl, it is probably an issue with the version of pdfbox that I am using.

Issues converting docx to pdf using docx4j

I am using docx4j 2.8.1 and I tried to convert several different docx file, but i have always the same issue.
maybe the issue is coming from the version of the library or some dependency missing.
Code:
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.docx4j.convert.out.pdf.PdfConversion;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
public class pdfConverter {
public static void main(String[] args) {
createPDF();
}
private static void createPDF() {
try {
// 1) Load DOCX into WordprocessingMLPackage
InputStream is = new FileInputStream(
new File("D:/TestDoc/Res.docx"));
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.load(is);
// 2) Prepare Pdf settings
PdfSettings pdfSettings = new PdfSettings();
// 3) Convert WordprocessingMLPackage to Pdf
OutputStream out = new FileOutputStream(new File(
"D:/TestDoc/Res.pdf"));
PdfConversion converter = new org.docx4j.convert.out.pdf.viaXSLFO.Conversion(
wordMLPackage);
converter.output(out, pdfSettings);
} catch (Throwable e) {
e.printStackTrace();
}
}
}
Error:
org.docx4j.openpackaging.exceptions.Docx4JException: FOP issues
at org.docx4j.convert.out.pdf.viaXSLFO.Conversion.output(Conversion.java:374)
at test.pdfConverter.createPDF(pdfConverter.java:42)
at test.pdfConverter.main(pdfConverter.java:21)
Caused by: java.lang.NullPointerException
at org.docx4j.XmlUtils.transform(XmlUtils.java:842)
at org.docx4j.XmlUtils.transform(XmlUtils.java:802)
at org.docx4j.convert.out.pdf.viaXSLFO.Conversion.output(Conversion.java:349)
... 2 more
Solved by changing to jars. i used 2.8.0 and its fine now.

Parsing content from Word document using docx4j

Thanks to a previous answer, I'm now able to read my password-protected Word 2010 documents. (I have to translate them one by one from .doc to .docx. They go back to 1994, but that's okay.)
I wrote a simple Java class to get started:
package model.docx4j;
import model.JournalEntry;
import model.JournalEntryFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.Parts;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.LinkedList;
import java.util.List;
/**
* JournalEntryFactoryImpl using docx4j
* #author Michael
* #link
* #since 9/8/12 12:44 PM
*/
public class JournalEntryFactoryImpl implements JournalEntryFactory {
#Override
public List<JournalEntry> getEntries(InputStream inputStream, String password) throws IOException, GeneralSecurityException {
List<JournalEntry> journalEntries = new LinkedList<JournalEntry>();
if (inputStream != null) {
try {
OpcPackage opcPackage = OpcPackage.load(inputStream, password);
Parts parts = opcPackage.getParts();
} catch (Docx4JException e) {
LOGGER.error("Could not load document into docx4j", e);
throw new IOException(e);
}
}
return journalEntries;
}
}
And a JUnit test to drive it:
package model.docx4j;
import model.JournalEntry;
import model.JournalEntryFactory;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.OpcPackage;
import org.docx4j.openpackaging.parts.Parts;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.LinkedList;
import java.util.List;
/**
* JournalEntryFactoryImpl using docx4j
* #author Michael
* #link
* #since 9/8/12 12:44 PM
*/
public class JournalEntryFactoryImpl implements JournalEntryFactory {
#Override
public List<JournalEntry> getEntries(InputStream inputStream, String password) throws IOException, GeneralSecurityException {
List<JournalEntry> journalEntries = new LinkedList<JournalEntry>();
if (inputStream != null) {
try {
OpcPackage opcPackage = OpcPackage.load(inputStream, password);
Parts parts = opcPackage.getParts();
} catch (Docx4JException e) {
LOGGER.error("Could not load document into docx4j", e);
throw new IOException(e);
}
}
return journalEntries;
}
}
I put a breakpoint into the test to see what docx4j was doing once it read my document. I see a list of 8 parts, but I walked through the tree without finding the content.
Each document consists of a page with a date and content, but I can't find pages. Where do they live?
The main document content lives in the "main document part", which is often named "/word/document.xml".
The usual way to get it with docx4j is:
WordprocessingMLPackage wordMLPackage = (WordprocessingMLPackage)opcPackage;
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
but you'd expect your approach to work as well.

JAX RS file upload

I am trying to set up file upload example using JAX RS. I could set up the project when the client is a JSP page and there are no issues. But i would like to have the client as a java class which sends post request to the service. My server side code is as shown below.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;
#Path("/file")
public class UploadFileService {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "d://uploaded/"
+ fileDetail.getFileName();
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The client as a JSP page is as shown below.
<html>
<body>
<h1>File Upload with Jersey</h1>
<form action="http://localhost:9090/RESTfulExample/rest/file/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
Can someone please help me with a class file as a client?
You can use Apache's httpclient and httpmime to accomplish this:
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
public class Uploader {
public void uploadFile(String endpoint, File file) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(endpoint);
FileBody uploadFilePart = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", uploadFilePart);
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
//Check response for success
}
}
Which works with your sample server code. See this question, as well.