I'm searching a method with JRGraphics2DExporter to export report as JPG.
Is there any kind of possibility to do that with JRGraphics2DExporter?
You want to use the JRGraphics2DExporter, but this can also be done directly using the JasperPrintManager
Example of code contemplenting multiple images 1 for every page
//Get my print, by filling the report
JasperPrint jasperPrint = JasperFillManager.fillReport(report, map,datasource);
final String extension = "jpg";
final float zoom = 1f;
String fileName = "report";
//one image for every page in my report
int pages = jasperPrint.getPages().size();
for (int i = 0; i < pages; i++) {
try(OutputStream out = new FileOutputStream(fileName + "_p" + (i+1) + "." + extension)){
BufferedImage image = (BufferedImage) JasperPrintManager.printPageToImage(jasperPrint, i,zoom);
ImageIO.write(image, extension, out); //write image to file
} catch (IOException e) {
e.printStackTrace();
}
}
If you like 1 image with all the pages, you should set the isIgnorePagination="true" on the jasperReport tag
You could instruct to the exporter in order to dump the report to an image in memory and then save it to disk.
Create the image (set the proper width, height and format):
BufferedImage image = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
Create the exporter, configure it (maybe some other parameters should be set) and export the report:
JRGraphics2DExporter exporter = new JRGraphics2DExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, (Graphics2D)image.getGraphics());
exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, Float.valueOf(1));
exporter.exportReport();
Dump the image to disk:
ImageIO.write(image, "PNG", new File("image.png"));
Related
This code is to compress a jpeg image, but if I want to compress an image without specifying the type of image, how can I do that? , How do I modify the code ?
File originalImage = new File("C:\\Users\\Super\\Desktop\\man.jpg");
File compressedImage = new File("C:\\Users\\Super\\Desktop\\compressedImage.jpg");
try{
compressJPEGImage(originalImage, compressedImage,0.5f );
System.out.println("Done!");
}
catch(IOException e){
}
}
public static void compressJPEGImage(File originalImage , File compressedImage , float
compressionQuality) throws IOException{
RenderedImage image = ImageIO.read(originalImage);
ImageWriter jpegwriter = ImageIO.getImageWritersByFormatName("jpg").next();
ImageWriteParam jpegWriteParam=jpegwriter.getDefaultWriteParam();
jpegWriteParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
jpegWriteParam.setCompressionQuality(compressionQuality);
try(ImageOutputStream output=ImageIO.createImageOutputStream(compressedImage)){
jpegwriter.setOutput(output);
IIOImage outputImage = new IIOImage(image,null,null);
jpegwriter.write(null,outputImage,jpegWriteParam);
}
jpegwriter.dispose();
}
Convert image to base64 or byte array of any type, then you can try for compressing it.
I am trying to capture one of my layout but getting black border in screenshot like below. How can I remove it ?
My code for taking screenshot is like below
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
Thanks
Actually, I didn't get your code,
View v1= findViewById(R.id.quoteViewPager);
v1.getRootView();
it should be :
v1 = v1.getRootView();
Hope it will help you :)
I have a pdf file (obtained from a byte[] generated by iText) I need to send to a signature hardware.
Due some incompatibility with the java printer driver I can't send the PDF directly, so i need to convert it to images before. I've succeed converting each PDF page to a jpg file, but customer does not like solution cause signatures are not in all the document, only in individual pages.
As I've not found any free library, I decided to make it in four steps:
STEP1: generate PDF with itext and persist it.
FileOutputStream fos = new FileOutputStream("tempFile.pdf");
fos.write(myByteArray);
fos.close();
fos.flush();
STEP 2: convert from PDF multipaged to List<java.awt.Image>
List<Image> images = null;
Ghostscript.getInstance(); // create gs instance
PDFDocument lDocument = new PDFDocument();
lDocument.load(new File("tempFile.pdf"));
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(300);
try
{
images = renderer.render(lDocument);
}
catch (RendererException | DocumentException e)
{
e.printStackTrace();
}
Step 3: Now I iterate over List<java.awt.Image> to convert to an individual TIFF's.
int filename = 1;
TIFFEncodeParam params = new TIFFEncodeParam();
Iterator<Image> imageIterator = images.iterator();
while (imageIterator.hasNext()) {
BufferedImage image = (BufferedImage) imageIterator.next();
FileOutputStream os = new FileOutputStream(/*outputDir + */ filename + ".tif");
JAI.create("encode", image , os, "TIFF", params);
filename ++;
}
STEP 4: create multipaged TIFF from various individual TIFF files
BufferedImage image[] = new BufferedImage[paginas];
for (int i = 0; i < paginas; i++) {
SeekableStream ss = new FileSeekableStream((i + 1) + ".tif");
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
PlanarImage pi = new NullOpImage(decoder.decodeAsRenderedImage(0),null,null,OpImage.OP_IO_BOUND);
image[i] = pi.getAsBufferedImage();
ss.close();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);
OutputStream out = new FileOutputStream(nombre +".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
List <BufferedImage>list = new ArrayList<BufferedImage>(image.length);
for (int i = 1; i < image.length; i++) {
list.add(image[i]);
}
params.setExtraImages(list.iterator());
encoder.encode(image[0]);
out.close();
System.out.println("Done.");
DONE. Hope that helps for someone else with same problem.
I had same issue a while ago. I got lot of help from here:
Multiple page tif
Allso check:
JAI (Java Advance Image)
Here is the conde snippet to convert pdf pages to png images (using org.apache.pdfbox library):
PDDocument document = null;
document = PDDocument.load(pdf1);
int pageNum = document.getNumberOfPages();
PDFImageWriter writer = new PDFImageWriter();
String filename = pdf1.getPath() + "-";
filename = filename.replace(".pdf", "");
writer.writeImage(document, "png", "", 1, Integer.MAX_VALUE, filename);
document.close();
And after that i converted each PNG image to TIFF and then from multiple TIFF images to single multi paged TIFF.
I am desperately trying to insert an image into an existing pdf with droidtext.
The original version of this project was made with iText.
So the code already exists and was modified to fit for Android.
What I do is I take an existing PDF as background.
Insert text and crosses at specified positions within this pdf.
Like filling out a form.
This works quite well so far without changing the code drastically.
Now I want to set an image to the bottom of the page to sign the form.
I used my original code and adapted it a little.
Which doesn't work at all.
I tried to set the image at a specific position. Maybe that was the error.
So i tried to do it the "official" way.
The Pengiuns.jpg image is located on the sd-card.
try {
Document document = new Document();
File f=new File(Environment.getExternalStorageDirectory(), "SimpleImages.pdf");
PdfWriter.getInstance(document,new FileOutputStream(f));
document.open();
document.add(new Paragraph("Simple Image"));
String path = Environment.getExternalStorageDirectory()+"/Penguins.jpg";
if (new File(path).exists()) {
System.out.println("filesize: " + path + " = " + new File(path).length());
}
Image image =Image.getInstance(path);
document.add(image);
document.close();
} catch (Exception ex) {
System.out.println("narf");
}
But still no image at all.
What I get is an PDF with the words "Simple Image" on it and nothing else.
I can access the picture. I get the correct filesize by the if().
No exceptions are thrown.
So my questions are, how do I get an Image located on the SD-Card into my pdf?
What is the mistake here?
But most importantly how do I set the image to a specific location with size within the pdf?
In my original code i use setAbsolutePosition( x, y ) for that.
Eclipse is not complaining when I use it in the code but is it really working?
The reason why you are getting the "Simple Image" is because you have it in Paragraph. In order to add an image, use:
Image myImg1 = Image.getInstance(stream1.toByteArray());
If you want to have it as a footer in the last page you can use the following code but it works with text. You can try to manipulate it for image:
Phrase footerText = new Phrase("THIS REPORT HAS BEEN GENERATED USING INSPECTIONREPORT APP");
HeaderFooter pdfFooter = new HeaderFooter(footerText, false);
doc.setFooter(pdfFooter);
Here is sample code. Here I have uploaded an image to Imageview and then added to pdf. Hope this helps.
private String NameOfFolder = "/InspectionReport";
Document doc = new Document();
try { //Path to look for App folder
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + NameOfFolder;
String CurrentDateAndTime= getCurrentDateAndTime();
// If App folder is not there then create one
File dir = new File(path);
if(!dir.exists())
dir.mkdirs();
//Creating new file and naming it
int i = 1;
File file = new File(dir, "Inspection"+Integer.toString(i)+"-" + CurrentDateAndTime+".pdf");
while(file.exists()) {
file = new File(dir, "Inspection"+Integer.toString(i++)+"-" + CurrentDateAndTime+".pdf");}
String filep= file.toString();
FileOutputStream fOut = new FileOutputStream(file);
Log.d("PDFCreator", "PDF Path: " + path);
PdfWriter.getInstance(doc, fOut);
Toast.makeText(getApplicationContext(),filep , Toast.LENGTH_LONG).show();
//open the document
doc.open();
ImageView img1 = (ImageView)findViewById(R.id.img1);
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
Bitmap bitmap1 = ((BitmapDrawable)img1.getDrawable()).getBitmap();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 100 , stream1);
Image myImg1 = Image.getInstance(stream1.toByteArray());
myImg1.setAlignment(Image.MIDDLE);
doc.add(myImg1);
Try following code:
/* Inserting Image in PDF */
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(getBaseContext().getResources(), R.drawable.android);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
//add image to document
doc.add(myImg);
Is it possible to generate a new image name for each image that is processed using the following code (I have highlighted the relevant section)?
public static void makeBinary(File image) {
try{
//Read in original image.
BufferedImage inputImg = ImageIO.read(image);
//Obtain width and height of image.
double image_width = inputImg.getWidth();
double image_height = inputImg.getHeight();
//New images to draw to.
BufferedImage bimg = null;
BufferedImage img = inputImg;
//Draw the new image.
bimg = new BufferedImage((int)image_width, (int)image_height, BufferedImage.TYPE_BYTE_BINARY);
Graphics2D gg = bimg.createGraphics();
gg.drawImage(img, 0, 0, img.getWidth(null), img.getHeight(null), null);
// ************* THIS IS WHERE I AM HAVING DIFFICULTY ***************
//Save new binary (output) image.
String temp = "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
// ******************************************************************
}
catch (Exception e){
System.out.println(e);
}
}
I have 300 images, numbered 001.jpg - 300.jpg, and what I would like is for each new outputted image to be named something along the lines of, binary_001.jpg - binary_300.jpg.
The method that calls makeBinary() is located in another class and is:
public static void listFiles() {
File dir = new File("images");
File imgList[] = dir.listFiles();
if(dir.isDirectory()){
for(File img : imgList){
if(img.isFile()){
MakeBinary.makeBinary(img);
System.out.println(img + ": processed successfully.");
}
else{
System.out.println("Directory detected; skipping to next file,");
}
}
}
}
How can I go about achieving this?
Many thanks.
Get the filename from your File image parameter and add it to the new filename:
String temp = image.getName() + "_inverted";
File fi = new File("images\\" + temp + ".jpg");
ImageIO.write(bimg, "jpg", fi);
You can just concatenate name from the original image (in your code 'image' you pass to ImageIO with the string "_inverted", this way you would have original name for each image you process: image.jpg -> image_inverted.jpg
File fi = new File("images\\" + "binary_" + image.getName());
Should do the trick.
Or even better:
File fi = new File(image.getParent(), "binary_" + image.getName());