Convert PDF to TIF Image
[Logo]
ICEsoft.org Forums: ICEfaces, ICEmobile, ICEpdf
[Search] Search   [Recent Topics] Recent Topics   [Groups] Home Page | www.icefaces.org  [Register] Register  [Login] Login 
Convert PDF to TIF Image  XML
Forum Index -> ICEpdf General Go to Page: Previous  1, 2, 3 Next 
Author Message
shahnawajakhtar

Joined: 11/03/2010 00:00:00
Messages: 2
Offline


Hi I am using this code. It is working good for conversion (PDF->tif). But I am facing a problem of moving these files (both PDf and tif) to another location. but I am getting error in moving files.

These are still coming locked. renameTo method of file is returning false to move these files.

Pls help me out of it.

Thanks,
Shahnawaj

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.FileImageOutputStream;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet;
import com.sun.media.imageio.plugins.tiff.TIFFDirectory;
import com.sun.media.imageio.plugins.tiff.TIFFField;
import com.sun.media.imageio.plugins.tiff.TIFFTag;


public class TiffHelper {
private static final char[] INCH_RESOLUTION_UNIT = new char[] {2};
private static final long[][] X_DPI_RESOLUTION = new long[][] {{150, 1}};
private static final long[][] Y_DPI_RESOLUTION = new long[][] {{150, 1}};
private static final char[] BITS_PER_SAMPLE = new char[] {1};
private static final char[] COMPRESSION = new char[] {BaselineTIFFTagSet.COMPRESSION_LZW};
private static final int HEIGHT = 1650;

/**
* ::Constructor()
*/
private TiffHelper() {

}

public static void main(String args[])
{
convertPDF("D:\\PROJECTS\\PDFExp\\exp\\Map.pdf","D:\\PROJECTS\\PDFExp\\exp\\Map.tif");
System.out.println(new File("D:\\PROJECTS\\PDFExp\\exp\\Map.pdf").renameTo(new File("D:\\PROJECTS\\PDFExp\\move\\Map.pdf")));
System.out.println(new File("D:\\PROJECTS\\PDFExp\\exp\\Map.tif").renameTo(new File("D:\\PROJECTS\\PDFExp\\move\\Map.tif")));
}

/**
* Convert a PDF document to a TIF file
*/
public static boolean convertPDF(String pdf, String tif) {
try {
convert(pdf, tif);
return true;
} catch (IOException e) {
return false;
}
}


/**
* Convert a PDF document to a TIF file
*/
protected static void convert(String pdf, String tif) throws IOException {

Document pdffile = new Document();
try {
pdffile.setFile(pdf);
} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);
} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);
} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);
} catch (IOException ex) {
System.out.println("Error handling PDF document " + ex);
}

int numPgs = pdffile.getNumberOfPages();
//float scale = 2.084f;
float scale = 1.600f;
float rotation = 0f;

BufferedImage image[] = new BufferedImage[numPgs];

for (int i = 0; i < numPgs; i++) {

/*
* Generate the image:
* Notes: 1275x1650 = 8.5 x 11 @ 150dpi ???
*/
image[i] = (BufferedImage)pdffile.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);

}
try
{
save(image, tif);
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pdffile.dispose();
System.out.println("pdffile getting free");
pdffile=null;
image=null;
}

}

/**
* Save tiff
*/
@SuppressWarnings("unchecked")
private static void save(BufferedImage[] b, String tif) throws IOException {

//Get a TIFF writer and set its output.
Iterator writers = ImageIO.getImageWritersByFormatName("TIFF");

if (writers == null || !writers.hasNext()) {
throw new RuntimeException("No writers for available.");
}
File temp =new File(tif);
ImageWriter writer = (ImageWriter) writers.next();
FileImageOutputStream fio=new FileImageOutputStream(temp);
writer.setOutput(fio);
writer.prepareWriteSequence(null);

for (int i = 0; i < b.length; i++)
{
ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(b[i]);
IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
imageMetadata = createImageMetadata(imageMetadata);
writer.writeToSequence(new IIOImage(b[i], null, imageMetadata), null);
}


writer.dispose();
writer = null;
//writers=null;
System.out.println("Clearing cacheing doc");
/*
temp=null;
fio.close();
System.out.println("Clearing cacheing doc 1");
fio=null;*/



}

/**
* Return the metadata for the new TIF image
*/
private static IIOMetadata createImageMetadata(IIOMetadata imageMetadata) throws IIOInvalidTreeException {

//Get the IFD (Image File Directory) which is the root of all the tags
//for this image. From here we can get all the tags in the image.
TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);

//Create the necessary TIFF tags that we want to add to the image metadata
BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();

//Resolution tags...
TIFFTag tagResUnit = base.getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT);
TIFFTag tagXRes = base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION);
TIFFTag tagYRes = base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION);

//BitsPerSample tag
TIFFTag tagBitSample = base.getTag(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);

//Row and Strip tags...
TIFFTag tagRowStrips = base.getTag(BaselineTIFFTagSet.TAG_ROWS_PER_STRIP);

//Compression tag
TIFFTag tagCompression = base.getTag(BaselineTIFFTagSet.TAG_COMPRESSION);

//Set the tag values
TIFFField fieldResUnit = new TIFFField(tagResUnit, TIFFTag.TIFF_SHORT, 1, INCH_RESOLUTION_UNIT);
TIFFField fieldXRes = new TIFFField(tagXRes, TIFFTag.TIFF_RATIONAL, 1, X_DPI_RESOLUTION);
TIFFField fieldYRes = new TIFFField(tagYRes, TIFFTag.TIFF_RATIONAL, 1, Y_DPI_RESOLUTION);
TIFFField fieldBitSample = new TIFFField(tagBitSample, TIFFTag.TIFF_SHORT, 1, BITS_PER_SAMPLE);
TIFFField fieldRowStrips = new TIFFField(tagRowStrips, TIFFTag.TIFF_LONG, 1, new long[] {HEIGHT});
TIFFField fieldCompression = new TIFFField(tagCompression, TIFFTag.TIFF_SHORT, 1, COMPRESSION);

//Cleanup the fields
//ifd.removeTIFFFields();

//Add the new tag/value sets to the image metadata
ifd.addTIFFField(fieldResUnit);
ifd.addTIFFField(fieldXRes);
ifd.addTIFFField(fieldYRes);
ifd.addTIFFField(fieldBitSample);
ifd.addTIFFField(fieldRowStrips);
ifd.addTIFFField(fieldCompression);

return ifd.getAsMetadata();

}

}

sam_roi19

Joined: 11/07/2010 20:51:54
Messages: 1
Offline


Hello,

I have able to use your code, but was having problem to set the height of the image it is created. I want to have the image dimension to be 1703 Width and 2203 as Height.

float scale = 2.784f; // this gives me the Width

but the height is always 2330.

Regards,
Sam
waltero

Joined: 27/07/2010 12:15:36
Messages: 1
Offline


I try this code, but when is converted the document to tif the resolutions is very bad and the file size is bigger than pdf

Why ?
pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


I moved this post to

http://www.icefaces.org/JForum/posts/list/17504.page

Thanks,

Pedro

pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


See http://www.icefaces.org/JForum/posts/list/17504.page

Pedro

sam_roi19 wrote:
Hello,

I have able to use your code, but was having problem to set the height of the image it is created. I want to have the image dimension to be 1703 Width and 2203 as Height.

float scale = 2.784f; // this gives me the Width

but the height is always 2330.

Regards,
Sam 

pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


see http://www.icefaces.org/JForum/posts/list/17504.page

Pedro

shahnawajakhtar wrote:
Hi I am using this code. It is working good for conversion (PDF->tif). But I am facing a problem of moving these files (both PDf and tif) to another location. but I am getting error in moving files.

These are still coming locked. renameTo method of file is returning false to move these files.

Pls help me out of it.

Thanks,
Shahnawaj

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOInvalidTreeException;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.FileImageOutputStream;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import com.sun.media.imageio.plugins.tiff.BaselineTIFFTagSet;
import com.sun.media.imageio.plugins.tiff.TIFFDirectory;
import com.sun.media.imageio.plugins.tiff.TIFFField;
import com.sun.media.imageio.plugins.tiff.TIFFTag;


public class TiffHelper {
private static final char[] INCH_RESOLUTION_UNIT = new char[] {2};
private static final long[][] X_DPI_RESOLUTION = new long[][] {{150, 1}};
private static final long[][] Y_DPI_RESOLUTION = new long[][] {{150, 1}};
private static final char[] BITS_PER_SAMPLE = new char[] {1};
private static final char[] COMPRESSION = new char[] {BaselineTIFFTagSet.COMPRESSION_LZW};
private static final int HEIGHT = 1650;

/**
* ::Constructor()
*/
private TiffHelper() {

}

public static void main(String args[])
{
convertPDF("D:\\PROJECTS\\PDFExp\\exp\\Map.pdf","D:\\PROJECTS\\PDFExp\\exp\\Map.tif");
System.out.println(new File("D:\\PROJECTS\\PDFExp\\exp\\Map.pdf").renameTo(new File("D:\\PROJECTS\\PDFExp\\move\\Map.pdf")));
System.out.println(new File("D:\\PROJECTS\\PDFExp\\exp\\Map.tif").renameTo(new File("D:\\PROJECTS\\PDFExp\\move\\Map.tif")));
}

/**
* Convert a PDF document to a TIF file
*/
public static boolean convertPDF(String pdf, String tif) {
try {
convert(pdf, tif);
return true;
} catch (IOException e) {
return false;
}
}


/**
* Convert a PDF document to a TIF file
*/
protected static void convert(String pdf, String tif) throws IOException {

Document pdffile = new Document();
try {
pdffile.setFile(pdf);
} catch (PDFException ex) {
System.out.println("Error parsing PDF document " + ex);
} catch (PDFSecurityException ex) {
System.out.println("Error encryption not supported " + ex);
} catch (FileNotFoundException ex) {
System.out.println("Error file not found " + ex);
} catch (IOException ex) {
System.out.println("Error handling PDF document " + ex);
}

int numPgs = pdffile.getNumberOfPages();
//float scale = 2.084f;
float scale = 1.600f;
float rotation = 0f;

BufferedImage image[] = new BufferedImage[numPgs];

for (int i = 0; i < numPgs; i++) {

/*
* Generate the image:
* Notes: 1275x1650 = 8.5 x 11 @ 150dpi ???
*/
image[i] = (BufferedImage)pdffile.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);

}
try
{
save(image, tif);
}
catch (Exception e)
{
// TODO: handle exception
}
finally
{
pdffile.dispose();
System.out.println("pdffile getting free");
pdffile=null;
image=null;
}

}

/**
* Save tiff
*/
@SuppressWarnings("unchecked")
private static void save(BufferedImage[] b, String tif) throws IOException {

//Get a TIFF writer and set its output.
Iterator writers = ImageIO.getImageWritersByFormatName("TIFF");

if (writers == null || !writers.hasNext()) {
throw new RuntimeException("No writers for available.");
}
File temp =new File(tif);
ImageWriter writer = (ImageWriter) writers.next();
FileImageOutputStream fio=new FileImageOutputStream(temp);
writer.setOutput(fio);
writer.prepareWriteSequence(null);

for (int i = 0; i < b.length; i++)
{
ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromRenderedImage(b[i]);
IIOMetadata imageMetadata = writer.getDefaultImageMetadata(imageType, null);
imageMetadata = createImageMetadata(imageMetadata);
writer.writeToSequence(new IIOImage(b[i], null, imageMetadata), null);
}


writer.dispose();
writer = null;
//writers=null;
System.out.println("Clearing cacheing doc");
/*
temp=null;
fio.close();
System.out.println("Clearing cacheing doc 1");
fio=null;*/



}

/**
* Return the metadata for the new TIF image
*/
private static IIOMetadata createImageMetadata(IIOMetadata imageMetadata) throws IIOInvalidTreeException {

//Get the IFD (Image File Directory) which is the root of all the tags
//for this image. From here we can get all the tags in the image.
TIFFDirectory ifd = TIFFDirectory.createFromMetadata(imageMetadata);

//Create the necessary TIFF tags that we want to add to the image metadata
BaselineTIFFTagSet base = BaselineTIFFTagSet.getInstance();

//Resolution tags...
TIFFTag tagResUnit = base.getTag(BaselineTIFFTagSet.TAG_RESOLUTION_UNIT);
TIFFTag tagXRes = base.getTag(BaselineTIFFTagSet.TAG_X_RESOLUTION);
TIFFTag tagYRes = base.getTag(BaselineTIFFTagSet.TAG_Y_RESOLUTION);

//BitsPerSample tag
TIFFTag tagBitSample = base.getTag(BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE);

//Row and Strip tags...
TIFFTag tagRowStrips = base.getTag(BaselineTIFFTagSet.TAG_ROWS_PER_STRIP);

//Compression tag
TIFFTag tagCompression = base.getTag(BaselineTIFFTagSet.TAG_COMPRESSION);

//Set the tag values
TIFFField fieldResUnit = new TIFFField(tagResUnit, TIFFTag.TIFF_SHORT, 1, INCH_RESOLUTION_UNIT);
TIFFField fieldXRes = new TIFFField(tagXRes, TIFFTag.TIFF_RATIONAL, 1, X_DPI_RESOLUTION);
TIFFField fieldYRes = new TIFFField(tagYRes, TIFFTag.TIFF_RATIONAL, 1, Y_DPI_RESOLUTION);
TIFFField fieldBitSample = new TIFFField(tagBitSample, TIFFTag.TIFF_SHORT, 1, BITS_PER_SAMPLE);
TIFFField fieldRowStrips = new TIFFField(tagRowStrips, TIFFTag.TIFF_LONG, 1, new long[] {HEIGHT});
TIFFField fieldCompression = new TIFFField(tagCompression, TIFFTag.TIFF_SHORT, 1, COMPRESSION);

//Cleanup the fields
//ifd.removeTIFFFields();

//Add the new tag/value sets to the image metadata
ifd.addTIFFField(fieldResUnit);
ifd.addTIFFField(fieldXRes);
ifd.addTIFFField(fieldYRes);
ifd.addTIFFField(fieldBitSample);
ifd.addTIFFField(fieldRowStrips);
ifd.addTIFFField(fieldCompression);

return ifd.getAsMetadata();

}

}

 

pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


see http://www.icefaces.org/JForum/posts/list/17504.page

Pedro

waltero wrote:
I try this code, but when is converted the document to tif the resolutions is very bad and the file size is bigger than pdf

Why ? 

pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


See http://www.icefaces.org/JForum/posts/list/17504.page

Pedro


javierburgos wrote:
Hello,

I'm using the example shown on the first post and I'm having some questions.

First of all, I would like to do a tiff with a 300 DPI resolution. What parameters should I change?

Second, I try to create a multitiff page after converting successfully from pdf to tiff and I get the following exception:

Code:
javax.imageio.IIOException: I/O error writing TIFF file!
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.write(TIFFImageWriter.java:2706)
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.insert(TIFFImageWriter.java:2903)
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.writeInsert(TIFFImageWriter.java:2862)
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.writeToSequence(TIFFImageWriter.java:2754)
 ..
 .
 .
 .
 .
 .
 [b]Caused by: javax.imageio.IIOException: Bits per sample must be 1 for T6 compression![/b]
         at com.sun.media.imageioimpl.plugins.tiff.TIFFT6Compressor.encode(TIFFT6Compressor.java:178)
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.writeTile(TIFFImageWriter.java:2309)
         at com.sun.media.imageioimpl.plugins.tiff.TIFFImageWriter.write(TIFFImageWriter.java:2686)


Could someone help me please? 

Admin

Joined: 27/05/2004 00:00:00
Messages: 199
Offline


Moved from ICEfaces General Help to ICEpdf General Help forum.

- Admin
pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


See update @ http://www.icefaces.org/JForum/posts/list/17504.page

Pedro

deanSiz wrote:

Hi All,
Have you tried using the BaselineTIFFTagSet.COMPRESSION_CCITT_T_4 ?
At first, I encounter error . Then I change the Document.java
BufferedImage image = new BufferedImage( pageWidth,
pageHeight,
BufferedImage.TYPE_BYTE_BINARY);
Now it turns out all the Tiff pages become Black in Background.
Any help? Thanks. 

hemantkap

Joined: 29/09/2010 06:39:27
Messages: 18
Offline


Hi,
I have used your code for converting pdf to tif and it is working successfully. thanks for it.

I have requirement of converting all type of files (jpg, jpeg, pdf) to TIF. So is it possible to use (after modifying) same code/class to achieve above requirement?

Thanks in Advance.
Hemant K.
pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


hemantkap,

You could add a new method in the class called convertImage().

Code:
public static boolean convertImage(BufferedImage[] image, String tif, long dpi, int color, int compression) {
 		try {
 			if (dpi < TiffConvert.DPI) {
 				return false;
 			}
 			IMAGE_DPI = dpi;
 			IMAGE_COLOR = color;
 			IMAGE_COMPRESSION = compression;
                         IMAGE_HEIGHT = image[0].getHeight();
 			save(image, tif);
 			return true;
 		} catch (IOException e) {
 			return false;
 		}
 }


The buffered image object can be a jpg, gif, etc.

You can open an image file as a buffered image, ex:

Code:
FileInputStream in = new FileInputStream("myimage.jpeg");
 JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
 BufferedImage image = decoder.decodeAsBufferedImage();


You can lookup java's docs for the different decoders you might need. The main thing is get it in a buffered image then you can convert it to a TIFF.

One thing you have to be sure of is the that your buffered image has to be compatible with the type of compression you want. For example, if you want COMPRESSION_CCITT_T_6 make sure the buffered image is of type TYPE_BYTE_BINARY, etc. Look at the convert(...) method to see how I do it.

Maybe if I get some time I might add a generic method to the class to process file types other than PDF.

This hasn't been an issue for us because what I have done in the past is to add the images as pages in a PDF and then convert the PDF to TIF. I use iText for that.

Pedro

hemantkap

Joined: 29/09/2010 06:39:27
Messages: 18
Offline


Thanks a lot Pedro.
Its working fine, the image (TIF) compression is also good.

So the problem is solved for PDF, JPG and GIF images. Now i am trying for PNG images to convert to TIF but its not working in this case. I am not getting the proper decoder for PNG images. I will try more on this and get back to you. Hope it will work :)

Thanks again for your immediate reply.

- Hemant.
pedrojrivera

Joined: 20/11/2008 00:00:00
Messages: 55
Offline


hemant,

Add this method to the class.

Code:
 	/**
 	 * Convert an image (png, gif, ico, jpg, bmp) to a TIF
 	 * @param img
 	 * @param tif
 	 * @param dpi
 	 * @param color
 	 * @param compression
 	 * @return
 	 */
 	public static boolean convertImg(String img, String tif, long dpi, int color, int compression) {
 		
 		try {
 			BufferedImage image = ImageIO.read(new File(img));
 			BufferedImage[] newImg = new BufferedImage[1];
 			
 			if (image == null) {
 				return false;
 			}
 			
 			IMAGE_DPI = dpi;
 			IMAGE_COLOR = color;
 			IMAGE_COMPRESSION = compression;
 			IMAGE_WIDTH = image.getWidth();
 			IMAGE_HEIGHT = image.getHeight();
 			
 			if (IMAGE_COMPRESSION == BaselineTIFFTagSet.COMPRESSION_CCITT_RLE ||
 			    IMAGE_COMPRESSION == BaselineTIFFTagSet.COMPRESSION_CCITT_T_4 ||
 			    IMAGE_COMPRESSION == BaselineTIFFTagSet.COMPRESSION_CCITT_T_6 ||
 			    IMAGE_COLOR == CLR_BLACK_WHITE ) {
 	            newImg[0] = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);
 			} else if (IMAGE_COLOR == CLR_GRAY_SCALE) {
 				newImg[0] = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_BYTE_GRAY);
 			} else {
 				newImg[0] = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
 			}
 			
 			Graphics2D g = (Graphics2D)newImg[0].getGraphics();
 			g.drawImage(image, 0, 0, null);
 			g.dispose();
 			
 			save(newImg, tif);
 			
 		} catch (IOException e) {
 			return false;
 		}
 		return true;
 	}


Let me know if this works.

I also updated the java source here:

http://www.icefaces.org/JForum/posts/list/17504.page#64470

Pedro

hemantkap

Joined: 29/09/2010 06:39:27
Messages: 18
Offline


Thanks Pedro,

Now it seems a generic method for all types of formats to convert into TIF.

Now i am moving to the next Target. Actually i want to convert the images/pdf files into TIFF and store the new image into DB as byte[].

So am wondering where to make changes to get byte[] of converted tiff file which i can store into DB.

Thanks,
- Hemant.
 
Forum Index -> ICEpdf General Go to Page: Previous  1, 2, 3 Next 
Go to:   
Powered by JForum 2.1.7ice © JForum Team