Zoom option in PDF-Renderer library - java

I am checking the api of https://pdf-renderer.dev.java.net/
I want to convert the PDF to image at zoom level 100%.
Does any one tried that?

int widthPage = (int)page.getBBox().getWidth();
int heightPage = (int)page.getBBox().getHeight();
if(page.getAspectRatio()<1){
widthPage = (int)(widthPage / page.getAspectRatio() );
heightPage = (int)(heightPage / page.getAspectRatio() );
}
// get the width and height for the doc at the default zoom
Rectangle rect = new Rectangle(0, 0, (int) widthPage, (int) heightPage);
// generate the image
Image img = page.getImage(rect.width, rect.height, // width & height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
// save it as a file

I would suggest iText for PDF viewing. It has been pretty good for me so far.

Just change the Image dimensions. When you zoom the Image all the characters appeared in clear view if the image dimensions are high. Download 04-Request-Headers.pdf file and paste it in C drive, converted files are saved in PDFConvertedFiles folder. Jars Required PDFRenderer-0.9.0
package com.pdfrenderer.examples;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import javax.imageio.ImageIO;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
public class ConvertAllPDFPagesToImageWithDimenstions {
public static void main(String[] args) {
try {
String sourceDir = "C:/04-Request-Headers.pdf";// PDF file must be placed in DataGet folder
String destinationDir = "C:/PDFConvertedFiles/";//Converted PDF page saved in this folder
File sourceFile = new File(sourceDir);
File destinationFile = new File(destinationDir);
String fileName = sourceFile.getName().replace(".pdf", "");
if (sourceFile.exists()) {
if (!destinationFile.exists()) {
destinationFile.mkdir();
System.out.println("Folder created in: "+ destinationFile.getCanonicalPath());
}
RandomAccessFile raf = new RandomAccessFile(sourceFile, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdf = new PDFFile(buf);
System.out.println("Total Pages: "+ pdf.getNumPages());
int pageNumber = 1;
for (int i = 0; i < pdf.getNumPages(); i++) {
PDFPage page = pdf.getPage(i);
// image dimensions
int width = 1200;
int height = 1400;
// create the image
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox().getWidth(), (int) page.getBBox().getHeight());
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// width & height, // clip rect, // null for the ImageObserver, // fill background with white, // block until drawing is done
Image image = page.getImage(width, height, rect, null, true, true );
Graphics2D bufImageGraphics = bufferedImage.createGraphics();
bufImageGraphics.drawImage(image, 0, 0, null);
File imageFile = new File( destinationDir + fileName +"_"+ pageNumber +".png" );// change file format here. Ex: .png, .jpg, .jpeg, .gif, .bmp
ImageIO.write(bufferedImage, "png", imageFile);
pageNumber++;
System.out.println(imageFile.getName() +" File created in Folder: "+ destinationFile.getCanonicalPath());
}
} else {
System.err.println(sourceFile.getName() +" File not exists");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

how convert multiple images to single PDF from folder in android?

I want to make android app to merge multiple image from single folder into single pdf file.
ex :
folder name :
- images
- 1.jpg
- 2.jpg
- 3.jpg
- 4.jpg
- 5.jpg
there are 5 images are in folder named images
how can i make pdf of that images?
if anyone have possible solution then please comment answer :)
Try this after 4.4 version it will work.
private void createPDF() {
final File file = new File(uploadFolder, "AnswerSheet_" + queId + ".pdf");
final ProgressDialog dialog = ProgressDialog.show(this, "", "Generating PDF...");
dialog.show();
new Thread(() -> {
Bitmap bitmap;
PdfDocument document = new PdfDocument();
// int height = 842;
//int width = 595;
int height = 1010;
int width = 714;
int reqH, reqW;
reqW = width;
for (int i = 0; i < array.size(); i++) {
// bitmap = BitmapFactory.decodeFile(array.get(i));
bitmap = Utility.getCompressedBitmap(array.get(i), height, width);
reqH = width * bitmap.getHeight() / bitmap.getWidth();
Log.e("reqH", "=" + reqH);
if (reqH < height) {
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
} else {
reqH = height;
reqW = height * bitmap.getWidth() / bitmap.getHeight();
Log.e("reqW", "=" + reqW);
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
}
// Compress image by decreasing quality
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.WEBP, 50, out);
// bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
//bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
//Create an A4 sized page 595 x 842 in Postscript points.
//PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(reqW, reqH, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Log.e("PDF", "pdf = " + bitmap.getWidth() + "x" + bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
}
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(() -> {
dismissDialog(dialog);
});
}).start();
}
If you want to create a pdf file with multiple images you can use PdfDocument from Android. Here is a demo:
private void createPDFWithMultipleImage(){
File file = getOutputFile();
if (file != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < images.size(); i++){
Bitmap bitmap = BitmapFactory.decodeFile(images.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile(){
File root = new File(this.getExternalFilesDir(null),"My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()){
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
}
else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
Here images is the ArrayList of the images with path.
Break your problem down into smaller problems. It's a fairly simple application.
Get the folder name from the user. See the native file open dialog to find a folder. See here.
Search its files for images
Create a pdf of the images. Use a library such as apache pdfbox.
Use this iText library
Create a document
String FILE = "{folder-path}/FirstPdf.pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
Add image in the document
try {
// get input stream
String fileName = "OfflineMap/abc.jpg";
String path =
Environment.getExternalStorageDirectory()+"/"+fileName;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream ims = getAssets().open("myImage.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
document.close();
}
catch(IOException ex)
{
return;
}

Convert PDF to png file with transparency (keep alpha)

I have been trying to convert PDF to png file with transparency without success.
I tried to solve it with many ways but I didn't succeed.
I'm writing my ways hoping someone will find where it went wrong:
1.
try (final PDDocument document = PDDocument.load(new File(srcpath))){
PDFRenderer pdfRenderer = new PDFRenderer(document);
for (int page = 0; page < document.getNumberOfPages(); ++page)
{
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
String fileName = imageConverted;
boolean hasAlpha = bim.getColorModel().hasAlpha();
System.out.println(hasAlpha);
ImageIOUtil.writeImage(bim, fileName, 300);
}
document.close();
} catch (IOException e){
System.err.println("Exception while trying to create pdf document - " + e);
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
// draw the first page to an image
int num=pdffile.getNumPages();
for(int i=0;i<num;i++)
{
PDFPage page = pdffile.getPage(i);
//get the width and height for the doc at the default zoom
int width=(int)page.getBBox().getWidth();
int height=(int)page.getBBox().getHeight();
Rectangle rect = new Rectangle(0,0,width,height);
int rotation=page.getRotation();
Rectangle rect1=rect;
if(rotation==90 || rotation==270)
rect1=new Rectangle(0,0,rect.height,rect.width);
//generate the image
BufferedImage img = (BufferedImage)page.getImage(
rect.width, rect.height, //width & height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
Graphics2D graphics = (Graphics2D)img.getGraphics();
graphics.setBackground( new Color( 255, 255, 255, 0 ) );
ImageIO.write(img, "png", new File(imageConverted));
}
}
catch (FileNotFoundException e1) {
System.err.println(e1.getLocalizedMessage());
} catch (IOException e) {
System.err.println(e.getLocalizedMessage());
}
3.
// Instantiating the PDFRenderer class
PDFRenderer renderer = new PDFRenderer(document);
// Rendering an image from the PDF document
BufferedImage image = null;
try {
image= renderer.renderImage(0);
} catch (IOException e1) {
return "N/A";
}
// Writing the image to a file
try {
ImageIO.write(image, "png", new File(imageConverted));
} catch (IOException e) {
return "N/A";
}
But I get the png with white background...
Any idea?
Thanks in advance!!!
change this line
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);
to
BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGBA);
this will get you a transparent image.

Unable to down scale gray scale image

I have an grayscale image with dimension 256*256.I am trying to downscale it to 128*128.
I am taking an average of two pixel and writing it to the ouput file.
class Start {
public static void main (String [] args) throws IOException {
File input= new File("E:\\input.raw");
File output= new File("E:\\output.raw");
new Start().resizeImage(input,output,2);
}
public void resizeImage(File input, File output, int downScaleFactor) throws IOException {
byte[] fileContent= Files.readAllBytes(input.toPath());
FileOutputStream stream= new FileOutputStream(output);
int i=0;
int j=1;
int result=0;
for(;i<fileContent.length;i++)
{
if(j>1){
// skip the records.
j--;
continue;
}
else {
result = fileContent[i];
for (; j < downScaleFactor; j++) {
result = ((result + fileContent[i + j]) / 2);
}
j++;
stream.write( fileContent[i]);
}
}
stream.close();
}
}
Above code run successfully , I can see the size of output file size is decreased but when I try to convert
output file (raw file) to jpg online (https://www.iloveimg.com/convert-to-jpg/raw-to-jpg) it is giving me an error saying that file is corrupt.
I have converted input file from same online tool it is working perfectly. Something is wrong with my code which is creating corrupt file.
How can I correct it ?
P.S I can not use any library which directly downscale an image .
Your code is not handling image resizing.
See how-to-resize-images-in-java.
Which, i am copying a simple version here:
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageResizer {
public static void resize(String inputImagePath,
String outputImagePath, int scaledWidth, int scaledHeight)
throws IOException {
// reads input image
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
// creates output image
BufferedImage outputImage = new BufferedImage(scaledWidth,
scaledHeight, inputImage.getType());
// scales the input image to the output image
Graphics2D g2d = outputImage.createGraphics();
g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
g2d.dispose();
// extracts extension of output file
String formatName = outputImagePath.substring(outputImagePath
.lastIndexOf(".") + 1);
// writes to output file
ImageIO.write(outputImage, formatName, new File(outputImagePath));
}
public static void resize(String inputImagePath,
String outputImagePath, double percent) throws IOException {
File inputFile = new File(inputImagePath);
BufferedImage inputImage = ImageIO.read(inputFile);
int scaledWidth = (int) (inputImage.getWidth() * percent);
int scaledHeight = (int) (inputImage.getHeight() * percent);
resize(inputImagePath, outputImagePath, scaledWidth, scaledHeight);
}
public static void main(String[] args) {
String inputImagePath = "resources/snoopy.jpg";
String outputImagePath1 = "target/Puppy_Fixed.jpg";
String outputImagePath2 = "target/Puppy_Smaller.jpg";
String outputImagePath3 = "target/Puppy_Bigger.jpg";
try {
// resize to a fixed width (not proportional)
int scaledWidth = 1024;
int scaledHeight = 768;
ImageResizer.resize(inputImagePath, outputImagePath1, scaledWidth, scaledHeight);
// resize smaller by 50%
double percent = 0.5;
ImageResizer.resize(inputImagePath, outputImagePath2, percent);
// resize bigger by 50%
percent = 1.5;
ImageResizer.resize(inputImagePath, outputImagePath3, percent);
} catch (IOException ex) {
System.out.println("Error resizing the image.");
ex.printStackTrace();
}
}
}

Resizing image in java - what do i need to change?

I was just wondering how I would resize an image in java?
This is for an assignment where I have to locate an image and then save it as a .png file that is half the resolution as the original.
This is my code so far;
enter code here
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class saveimage {
public static void main(String[] args) // IOException
{
String sourceLocation;
sourceLocation = (args[0]);
int width = 963;
int height = 640;
int halfwidth = width / 2;
int halfheight = height / 2;
BufferedImage image1 = null;
BufferedImage imagehalf = null;
File readfile = null;
try {
readfile = new File(sourceLocation);
image1 = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
image1 = ImageIO.read(readfile);
imagehalf = new BufferedImage(halfwidth, halfheight,
BufferedImage.TYPE_INT_ARGB);
imagehalf = ImageIO.read(readfile);
System.out.println("reading complete");
}
catch (IOException e) {
System.out.println("Error: " + e);
}
try {
readfile = new File("LOCATION OF FILE");
ImageIO.write(image1, "png", readfile);
System.out.println("Writing complete");
} catch (IOException fail1) {
System.out.println("Error:" + fail1);
}
try {
readfile = new File "LOCATION OF OUTPUT");
ImageIO.write(imagehalf, "png", readfile);
System.out.println("writing half is complete");
} catch (IOException fail2) {
System.out.println("Error:" + fail2);
}
}
}
As you can see I have just halved the integer values at the start as I thought it would have just halved the output size but it didn't...is there anything i am doing wrong?
The next part of the assignment is that i need to tile the image but i am just doing one step at a time :)
Thanks in advance
AFAIK imagehalf = ImageIO.read(readfile); would just read the image file and create a BufferedImage of the original size. What you're basically doing is create a fresh BufferedImage and then replace it with one read from the file, which can't work.
What you'd have to do instead: read the original image, create a half sized BufferedImage and draw the original image to the half sized one.
Use the getGraphics() method and call drawImage(...) with the necessary parameters on the returned Graphics object.
Note that you could use BufferedImage#getScaledInstance(...) but you might want to start using the Graphics object to be prepared for your future assignments.
Hey feel free to use this code i posted below:
public ImageIcon resizeImage(ImageIcon imageIcon, int width, int height, boolean max)
{
Image image = imageIcon.getImage();
Image newimg = image.getScaledInstance(-1, height, java.awt.Image.SCALE_SMOOTH);
int width1 = newimg.getWidth(null);
if ((max && width1 > width) || (!max && width1 < width))
newimg = image.getScaledInstance(width, -1, java.awt.Image.SCALE_SMOOTH);
return new ImageIcon(newimg);
}
I actually don't know what the boolean max does i found it on the internet somewhere.
You need to get a graphics context for the resizedImage and then draw the original image into it with the dimensions you want. Depending on how it looks you may want to look at Java's RenderingHints as well.
BufferedImage imageHalf = new BufferedImage(halfwidth, halfheight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = imageHalf.createGraphics();
g.drawImage(fullImage, 0, 0, halfwidth, halfheight, null);
g.dispose();

Java: Splitting .GIF image in BufferedImages Gives Malformed Images

So I have a very small piece of code, which takes a .gif image as input, and then it splits this .gif image into an array of BufferedImage. After that, it stores the images in the array on the disk. When I do this, the output images contain heavy white-pixel noise which isn't visible in the input .gif image.
Example of the input gif:
Example of malformed output image (the 3rd frame in the gif):
The code I am using to split the gif is as follows:
public static void main(String[] args) throws Exception {
splitGif(new File("C:\\test.gif"));
}
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next(); reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
for(int i = 0; i < reader.getNumImages(true); i++) {
BufferedImage image = reader.read(i);
ImageIO.write(image, "PNG", new File(i + ".png"));
}
}
Can anyone help me out?
So the problem was that when reading .gif files into java, then all pixels in a given frame that did not change color compared to their previous frame will be fully transparent. If you want to read a .gif and split it in an array of properly rendered BufferedImages, then you have to fill the transparent pixels of the current frame with the last non-transparent pixel of one of the previous frames.
Code:
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
BufferedImage lastImage = reader.read(0);
ImageIO.write(lastImage, "PNG", new File(0 + ".png"));
for (int i = 1; i < reader.getNumImages(true); i++) {
BufferedImage image = makeImageForIndex(reader, i, lastImage);
ImageIO.write(image, "PNG", new File(i + ".png"));
}
}
private static BufferedImage makeImageForIndex(ImageReader reader, int index, BufferedImage lastImage) throws IOException {
BufferedImage image = reader.read(index);
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
if(lastImage != null) {
newImage.getGraphics().drawImage(lastImage, 0, 0, null);
}
newImage.getGraphics().drawImage(image, 0, 0, null);
return newImage;
}
You solved it yourself, but for good order: every next frame is the accumulation of all prior frames filling up the transparent pixels in the current frame.
public static void splitGif(File file) throws IOException {
ImageReader reader = ImageIO.getImageReadersBySuffix("gif").next();
reader.setInput(ImageIO.createImageInputStream(new FileInputStream(file)), false);
BufferedImage outImage = null;
Graphics2D g = null;
for (int i = 0; i < reader.getNumImages(true); i++) {
BufferedImage image = reader.read(i);
if (g == null) {
BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
g = (Graphics2D) outImage.getGraphics();
}
g.drawImage(lastImage, 0, 0, null);
ImageIO.write(outImage, "PNG", new File(i + ".png"));
}
if (g != null) {
g.dispose();
}
}
getGraphics==createGraphics should be balanced be a dispose as documented.

Categories

Resources