I am trying to read .rpt file and generate pdf using ReportClientDocument,ByteArrayInputStream and ByteArrayOutputStream. After generating the pdf file I am unable to open it. It is showing "It may be damaged or use a file format that Preview doesn’t recognise." My Source code is provided below
public static void generatePDFReport()
{
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
try {
ReportClientDocument rcd = new ReportClientDocument();
String rptPath="/Users/florapc/Desktop/Report/AcStatement.rpt";
String outputPath=String.format("/Users/florapc/Desktop/Report/%s.pdf",dtf.format(now));
File inputFile = new File(rptPath);
File outputFile = new File(outputPath);
rcd.open(rptPath, 0);
System.out.println(rptPath);
List<IParameterField> fld = rcd.getDataDefController().getDataDefinition().getParameterFields();
List<String> reportContent = new ArrayList<String>();
System.out.println(fld.size());
for (int i = 0; i < fld.size(); i++) {
System.out.println(fld.get(i).getDescription());
reportContent.add(fld.get(i).getDescription().replaceAll("[^a-zA-Z0-9]", " "));
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(reportContent);
byte[] bytes = bos.toByteArray();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
byte[] byteArray = new byte[byteArrayInputStream.available()];
int x = byteArrayInputStream.read(byteArray, 0, byteArrayInputStream.available());
System.out.println(x);
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();;
byteArrayOutputStream.write(byteArray, 0, x);
byteArrayOutputStream.writeTo(fileOutputStream);
System.out.println(fileOutputStream);
System.out.println("File exported succesfully");
byteArrayInputStream.close();
byteArrayOutputStream.close();
fileOutputStream.close();
rcd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I can read .rpt file and print it in console. Please help me finding the best way to generate pdf properly.
I'm not familiar with ReportClientDocument. As far as I understand it's not a PDF document itself but a report that can be saved as PDF. ObjectOutputStream won't achieve this as it's Java specific format and has nothing to do with PDF.
It looks as if a PrintOutputController is needed for PDF export. Thus your code would look more like so:
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
InputStream is = rcd.getPrintOutputController().export(ReportExportFormat.PDF);
copy(is, fileOutputStream);
fileOutputStream.close();
...
void copy(InputStream source, OutputStream target) throws IOException {
byte[] buf = new byte[8192];
int length;
while ((length = source.read(buf)) > 0) {
target.write(buf, 0, length);
}
}
Note that no byte array streams are needed. They are a detour, slowing down your program and drive up memory consumption.
Related
I am using java spring and jpa I have a query to retrieve the blob from an oracle db. I get the blob and if it is a text file it is downloading onto my local machine just fine - but if it is an image I have to go through a BufferedImage, and I am still working on PDF. So far I'm just seeing the extension of the file by getting it's original filename which is also stored in the DB, then filtering the string for the extension. When I get a PDF it says the file is corrupted or open in another window, which it is not.
So far, this is my code that tries to turn blob from DB into a file:
Blob blob = Service.retrieveBlob(ID);
if (blob == null){
return false;
}
String fileName = Service.getFileName(ID);
String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
System.out.println(extension);
if (extension.equals("jpg") || (extension.equals("png"))){
File file = new File("./DBPicture.png");
try(FileOutputStream outputStream = new FileOutputStream(file)) {
BufferedImage bufferedImage = ImageIO.read(blob.getBinaryStream());
ImageIO.write(bufferedImage, "png", outputStream);
System.out.println("Image file location: "+file.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
else {
InputStream ins = blob.getBinaryStream();
byte[] buffer = new byte[ins.available()];
ins.read(buffer);
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
}
available is simply that. it is not necessarily the length of the stream.
Try something like
InputStream ins = blob.getBinaryStream();
File targetFile = new File("./" + fileName);
OutputStream outStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[8000];
int count = 0;
while ((count = ins.read(buffer)) != -1) {
outStream.write(buffer);
}
// then close your output
outStream.close ();
I have a jpg image and I want to convert it to a tiff file, but when I create the output file from byteArrayOutputStream, the output file has 0 byte length.
public static void main(String[] args) throws Exception {
String root = "E:\\Temp\\imaging\\test\\";
File image = new File(root + "0riginalTif-convertedToJpg.JPG");
byte[] bytes = compressJpgToTiff(image);
File destination = new File(root + "OriginalJpg-compressedToTiff.tiff");
FileOutputStream fileOutputStream = new FileOutputStream(destination);
fileOutputStream.write(bytes);
}
public static byte[] compressJpgToTiff(File imageFile) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(255);
ImageOutputStream imageOutputStream = null;
try {
File input = new File(imageFile.getAbsolutePath());
Iterator<ImageWriter> imageWriterIterator = ImageIO.getImageWritersByFormatName("TIF");
ImageWriter writer = imageWriterIterator.next();
imageOutputStream = ImageIO.createImageOutputStream(byteArrayOutputStream);
writer.setOutput(imageOutputStream);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG");
param.setCompressionQuality(0.1f);
BufferedImage bufferedImage = ImageIO.read(input);
writer.write(null, new IIOImage(bufferedImage, null, null), param);
writer.dispose();
return byteArrayOutputStream.toByteArray();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (imageOutputStream != null)
imageOutputStream.close();
byteArrayOutputStream.close();
}
}
I want to reduce the size of output tiff as much as possible. Is there a better approach? Is it even possible to reduce the size of a tiff image?
return byteArrayOutputStream.toByteArray(); but you didn't wirite data to byteArrayOutputStream. Look, you just added data to writer.
About compression of tiff file, you have already done it with - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
Your byteArrayOutputStream object is getting closed in finally block before you converting byteArrayOutputStream to byteArray using byteArrayOutputStream.toByteArray() thats why you getting content length to be 0. So modify your code once as below :
public static byte[] compressJpgToTiff(File imageFile) throws Exception {
//Add rest of your method code here
writer.dispose();
byte[] bytesToReturn = byteArrayOutputStream.toByteArray();
return bytesToReturn;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (imageOutputStream != null)
imageOutputStream.close();
byteArrayOutputStream.close();
}
}
I have created a video thumbnail from a video file. What I need to do is to create a java.io.File from the Bitmap in order to upload the thumbnail to a server. How could achieve this?
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(videoFile.getPath(), MediaStore.Video.Thumbnails.FULL_SCREEN_KIND);
File thumbFile = ?
can use the following code:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
//f.createNewFile(); (No need to call as FileOutputStream will automatically create the file)
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
you can also try this method: it does not convert bitmap to byte Array..
private static void bitmap_to_file(Bitmap bitmap, String name) {
File filesDir = getAppContext().getFilesDir();
File imageFile = new File(filesDir, name + ".jpg");
OutputStream os;
try {
os = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
}
}
When I try upload the file from server, I use this code. I get the file size of 500kb, when the original file size about 300kb.
What am I doing wrong?
attachmentContent = applicationApi.getApplicationAttachmentContent(applicationame);
InputStream in = new BufferedInputStream(attachmentContent.getAttachmentContent().getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while (-1 !=(n=in.read(buf)))
{
out.write(buf,0,n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
File transferredFile = new File(attachmentName);
FileOutputStream outStream = new FileOutputStream(transferredFile);
attachmentContent.getAttachmentContent().writeTo(outStream);
outStream.write(response);
outStream.close();
Simplify. The same result:
File transferredFile = new File(attachmentName);
FileOutputStream outStream = new FileOutputStream(transferredFile);
attachmentContent.getAttachmentContent().writeTo(outStream);
outStream.close();
The ByteArrayOutputStream is a complete waste of time and space. You're reading the attachment twice, and writing it twice too. Just read from the attachment and write directly to the file. Simplify, simplify. You don't need 90% of this.
i try to download a pdf file from url using the code below. It works fine when the file size is under 8k and if the file is up to 8k, it downloads the pdf file but the file is not readable.
Code
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
FileOutputStream fos = new FileOutputStream(new File("C:\\temp\\TEST.pdf"));
fos.write(response);
fos.close();
System.out.println("Download Finished");
You may try using the IOUtils.copy(InputStream input, OutputStream output)
You can minimize the lines of code.
Apache IOUtils