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")));
Related
I am working on a case where I will be supplied with data and I will create a excel file using that data.
Right now I am creating it in my local system and later adding that as an attachment and sending through email using Java Mail Service.
But I dont want to store excel file in my local system and I want to just pass the stream object to email service and send email. So that there wont be any local storage of file still able to send attachment.
Please reply if there is any solution ?
// Created WorkBook
HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream outputStream = new FileOutputStream(FILE_NAME)) workbook.write(outputStream);
here FILE_NAME is fully qualified system path where I will be storing file.
I want to skip this and directly send attachment
I'm using an approach like this and it is working fine:
File file = File.createTempFile("Report", "xlsx");
file.deleteOnExit();
Path path = file.toPath();
try (final FileOutputStream fileOut = new FileOutputStream(file)) {
try (final XSSFWorkbook workbook = new XSSFWorkbook()) {
//create your sheets here
workbook.write(fileOut);
return Files.readAllBytes(path);
} catch (Exception e) {
LOG.error("Error during creation of excel report", e);
throw e;
} finally {
if (path != null) {
try {
Files.delete(path);
} catch (final IOException e) {
LOG.error("Unable to delete file:" + path.toString(), e);
}
}
}
}
Write the data to a ByteArrayOutputStream, get the bytes, and use a ByteArrayDataSource to supply the data to JavaMail:
mbp.setDataHandler(new DataHandler(
new ByteArrayDataSource(bytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")));
Workbook workbook=new XSSFWorkbook();
Sheet sheet =workbook.createSheet(" ");
Font HearderFont=workbook.createFont();
HearderFont.setBold(true);
HearderFont.setFontHeightInPoints((short)9);
HearderFont.setColor(IndexedColors.RED.getIndex());
CellStyle hearderCellStyle=workbook.createCellStyle();
hearderCellStyle.setFont(HearderFont);
//excel file maker
int rownum=1;
for(MailModelClass mailModelonbj:dataStored) {
Row row=sheet.createRow(rownum++);
row.createCell(0).setCellValue(mailModelonbj.(any));
row.createCell(1).setCellValue(mailModelonbj.(any));
row.createCell(2).setCellValue(mailModelonbj.(any));
}
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.
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 have a POJO which in need to send to another end-poind (some server).
I have decided it do it using avro.
So far I have created my Avro schema and generated my DataFileWriter:
GenericRecord user1 = new GenericData.Record(schema);
user1.put("name", "Jenny");
user1.put("favorite_color", "green");
GenericRecord user2 = new GenericData.Record(schema);
user2.put("name", "Kevin");
user2.put("favorite_color", "red");
DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema);
DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter);
dataFileWriter.create(schema, schemaFile);
dataFileWriter.append(user1);
dataFileWriter.append(user2);
This is what I have so far and I'm missing the following:
I would like to compress the data before sending it, I rather doing it using snappy, how should I combine it with my code?
UPDATE:
Added these lines:
// use snappy compression
CodecFactory codecFactory = CodecFactory.snappyCodec();
dataFileWriter.setCodec(codecFactory);
But I'm not sure yet if it does the job.
Using this:
public byte[] serialize(T objectToSerialize) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DatumWriter<T> reflectDatumWriter = new ReflectDatumWriter<T>(avroSchema);
DataFileWriter<T> fileWriter = null;
try {
fileWriter = new DataFileWriter<T>(reflectDatumWriter);
fileWriter.setCodec(CodecFactory.snappyCodec());
fileWriter.create(avroSchema, out);
fileWriter.append(objectToSerialize);
fileWriter.close();
} catch (Exception e) {
LOG.error(e);
return null;
}
return out.toByteArray();
}
Please see the update question below (not the top one).
I tried to open any document type (especially PDF) on Liferay using this function. But I always get message Awt Desktop is not supported! as stated on the function. How can I enable the Awt Desktop? I tried searching over the internet and found nothing. Anyone help, pls? Thanks.
public void viewFileByAwt(String file) {
try {
File File = new File(getPath(file));
if (File.exists()) {
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(File);
} else {
System.out.println("Awt Desktop is not supported!");
}
} else {
//File is not exists
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Source: http://www.mkyong.com/java/how-to-open-a-pdf-file-in-java/
UPDATE
As you see the code below, both mode (1 for download and 2 for preview) is working pretty well, but unfortunately the second mode (preview mode) is works only for PDF.
Now what I want to do is, while user clicking the preview button, files another than PDF (limited only for extension: DOC, DOCX, XLS, XLSX, ODT, ODS) must be converted to PDF first, and then display it on the browser with the same way as below code explained. Is it possible to do that? If it's too hard to have all of the converter on a function, then on a separated function each extension would be fine.
public StreamedContent getFileSelected(final StreamedContent doc, int mode) throws Exception {
//Mode: 1-download, 2-preview
try {
File localfile = new File(getPath(doc.getName()));
FileInputStream fis = new FileInputStream(localfile);
if (mode == 2 && !(doc.getName().substring(doc.getName().lastIndexOf(".") + 1)).matches("pdf")) {
localfile = DocumentConversionUtil.convert(doc.getName(), fis, doc.getName().substring(doc.getName().lastIndexOf(".") + 1), "pdf");
fis = new FileInputStream(localfile.getPath());
}
if (localfile.exists()) {
try {
PortletResponse portletResponse = (PortletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
HttpServletResponse res = PortalUtil.getHttpServletResponse(portletResponse);
if (mode == 1) res.setHeader("Content-Disposition", "attachment; filename=\"" + doc.getName() + "\"");
else if (mode == 2) res.setHeader("Content-Disposition", "inline; filename=\"" + doc.getName() + "\"");
res.setHeader("Content-Transfer-Encoding", "binary");
res.setContentType(getMimeType(localfile.getName().substring(localfile.getName().lastIndexOf(".") + 1)));
res.flushBuffer();
OutputStream out = res.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
buffer = new byte[4096];
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
Liferay is a portal server; its user interface runs in a browser. AWT is the Java 1.0 basis for desktop UIs.
I don't think AWT is the way to display it.
Why can't you open the file and stream the bytes to the portlet using the application/pdf MIME type?
You have to first install openoffice on your machine
http://www.liferay.com/documentation/liferay-portal/6.1/user-guide/-/ai/openoffice
After configuring openoffice with liferay, you can use DocumentConversionUtil class from liferay to convert documents.
DocumentConversionUtil.convert(String id, InputStream is, String sourceExtension,String targetExtension)
Above code will return inputstream. After this conversion you can show pdf in your browser
Hope this helps you!!