You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pdfbox.apache.org by le...@apache.org on 2009/07/08 08:02:35 UTC
svn commit: r792043 - in /incubator/pdfbox/trunk/src:
main/java/org/apache/pdfbox/ main/java/org/apache/pdfbox/pdfviewer/
main/java/org/apache/pdfbox/pdmodel/ main/java/org/apache/pdfbox/util/
test/java/org/apache/pdfbox/util/
Author: lehmi
Date: Wed Jul 8 06:02:34 2009
New Revision: 792043
URL: http://svn.apache.org/viewvc?rev=792043&view=rev
Log:
PDFBOX-460: Improvements for bitmap production (resolution and color depth). Patch from Jeremias Maerki (jeremias at apache dot org)
Modified:
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/ (props changed)
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/PDFToImage.java
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdfviewer/PageDrawer.java
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java
incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java
incubator/pdfbox/trunk/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java
Propchange: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/
('svn:mergeinfo' removed)
Modified: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/PDFToImage.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/PDFToImage.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/PDFToImage.java (original)
+++ incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/PDFToImage.java Wed Jul 8 06:02:34 2009
@@ -16,22 +16,11 @@
*/
package org.apache.pdfbox;
+import java.awt.Toolkit;
import java.awt.image.BufferedImage;
-import java.io.File;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.imageio.IIOException;
-import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
-import javax.imageio.ImageWriteParam;
-import javax.imageio.ImageWriter;
-import javax.imageio.stream.ImageOutputStream;
-
import org.apache.pdfbox.exceptions.InvalidPasswordException;
-
import org.apache.pdfbox.pdmodel.PDDocument;
-//import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.util.PDFImageWriter;
/**
@@ -46,8 +35,10 @@
private static final String PASSWORD = "-password";
private static final String START_PAGE = "-startPage";
private static final String END_PAGE = "-endPage";
- private static final String IMAGE_TYPE = "-imageType";
+ private static final String IMAGE_FORMAT = "-imageType";
private static final String OUTPUT_PREFIX = "-outputPrefix";
+ private static final String COLOR = "-color";
+ private static final String RESOLUTION = "-resolution";
/**
* private constructor.
@@ -69,10 +60,12 @@
String password = "";
String pdfFile = null;
String outputPrefix = null;
- String imageType = "jpg";
+ String imageFormat = "jpg";
int startPage = 1;
int endPage = Integer.MAX_VALUE;
- for( int i=0; i<args.length; i++ )
+ String color = "rgb";
+ int resolution = Toolkit.getDefaultToolkit().getScreenResolution();
+ for( int i = 0; i < args.length; i++ )
{
if( args[i].equals( PASSWORD ) )
{
@@ -101,16 +94,26 @@
}
endPage = Integer.parseInt( args[i] );
}
- else if( args[i].equals( IMAGE_TYPE ) )
+ else if( args[i].equals( IMAGE_FORMAT ) )
{
i++;
- imageType = args[i];
+ imageFormat = args[i];
}
else if( args[i].equals( OUTPUT_PREFIX ) )
{
i++;
outputPrefix = args[i];
}
+ else if( args[i].equals( COLOR ) )
+ {
+ i++;
+ color = args[i];
+ }
+ else if( args[i].equals( RESOLUTION ) )
+ {
+ i++;
+ resolution = Integer.parseInt(args[i]);
+ }
else
{
if( pdfFile == null )
@@ -119,7 +122,6 @@
}
}
}
-
if( pdfFile == null )
{
usage();
@@ -153,27 +155,62 @@
}
else
{
- //they didn't suppply a password and the default of "" was wrong.
+ //they didn't supply a password and the default of "" was wrong.
System.err.println( "Error: The document is encrypted." );
usage();
}
}
}
-
- //Make the call
- PDFImageWriter W = new PDFImageWriter();
- W.WriteImage(document, imageType, password, startPage, endPage, outputPrefix);
- } catch(Exception e){
- System.err.println( e);
- }
- finally
- {
- if( document != null )
- {
- document.close();
- }
- }
- }
+ int imageType = 24;
+ if ("bilevel".equalsIgnoreCase(color))
+ {
+ imageType = BufferedImage.TYPE_BYTE_BINARY;
+ }
+ else if ("indexed".equalsIgnoreCase(color))
+ {
+ imageType = BufferedImage.TYPE_BYTE_INDEXED;
+ }
+ else if ("gray".equalsIgnoreCase(color))
+ {
+ imageType = BufferedImage.TYPE_BYTE_GRAY;
+ }
+ else if ("rgb".equalsIgnoreCase(color))
+ {
+ imageType = BufferedImage.TYPE_INT_RGB;
+ }
+ else if ("rgba".equalsIgnoreCase(color))
+ {
+ imageType = BufferedImage.TYPE_INT_ARGB;
+ }
+ else
+ {
+ System.err.println( "Error: the number of bits per pixel must be 1, 8 or 24." );
+ System.exit( 2 );
+ }
+
+ //Make the call
+ PDFImageWriter imageWriter = new PDFImageWriter();
+ boolean success = imageWriter.writeImage(document, imageFormat, password,
+ startPage, endPage, outputPrefix, imageType, resolution);
+ if (!success)
+ {
+ System.err.println( "Error: no writer found for image format '"
+ + imageFormat + "'" );
+ System.exit(1);
+ }
+ }
+ catch (Exception e)
+ {
+ System.err.println(e);
+ }
+ finally
+ {
+ if( document != null )
+ {
+ document.close();
+ }
+ }
+ }
}
/**
@@ -185,9 +222,11 @@
" -password <password> Password to decrypt document\n" +
" -imageType <image type> (" + getImageFormats() + ")\n" +
" -outputPrefix <output prefix> Filename prefix for image files\n" +
- " -startPage <number> The first page to start extraction(1 based)\n" +
- " -endPage <number> The last page to extract(inclusive)\n" +
- " <PDF file> The PDF document to use\n"
+ " -startPage <number> The first page to start extraction(1 based)\n" +
+ " -endPage <number> The last page to extract(inclusive)\n" +
+ " -color <string> The color depth (valid: bilevel, indexed, gray, rgb, rgba)\n" +
+ " -resolution <number> The bitmap resolution in dpi\n" +
+ " <PDF file> The PDF document to use\n"
);
System.exit( 1 );
}
@@ -196,10 +235,10 @@
{
StringBuffer retval = new StringBuffer();
String[] formats = ImageIO.getReaderFormatNames();
- for( int i=0; i<formats.length; i++ )
+ for( int i = 0; i < formats.length; i++ )
{
retval.append( formats[i] );
- if( i+1<formats.length )
+ if( i + 1 < formats.length )
{
retval.append( "," );
}
Modified: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdfviewer/PageDrawer.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdfviewer/PageDrawer.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdfviewer/PageDrawer.java (original)
+++ incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdfviewer/PageDrawer.java Wed Jul 8 06:02:34 2009
@@ -281,7 +281,11 @@
path.reset();
}
- //If you need to do anything when a color changes, do it here ... or in an override of this function
+ /**
+ * Called when the color changed.
+ * @param bStroking true for the stroking color, false for the non-stroking color
+ * @throws IOException if an I/O error occurs
+ */
public void colorChanged(boolean bStroking) throws IOException
{
//logger().info("changing " + (bStroking ? "" : "non") + "stroking color");
@@ -289,7 +293,7 @@
//This code generalizes the code Jim Lynch wrote for AppendRectangleToPath
/**
- * use the current transformatrion matrix to transform a single point.
+ * use the current transformation matrix to transform a single point.
* @param x x-coordinate of the point to be transform
* @param y y-coordinate of the point to be transform
* @return the transformed coordinates as Point2D.Double
@@ -297,7 +301,8 @@
public java.awt.geom.Point2D.Double transformedPoint(double x, double y)
{
double[] position = {x,y};
- getGraphicsState().getCurrentTransformationMatrix().createAffineTransform().transform(position, 0, position, 0, 1);
+ getGraphicsState().getCurrentTransformationMatrix().createAffineTransform().transform(
+ position, 0, position, 0, 1);
position[1] = fixY(position[1]);
return new Point2D.Double(position[0],position[1]);
}
Modified: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java (original)
+++ incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPage.java Wed Jul 8 06:02:34 2009
@@ -40,8 +40,6 @@
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
-import java.awt.geom.AffineTransform;
-import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.ImagingOpException;
import java.awt.print.PageFormat;
@@ -64,6 +62,8 @@
*/
public class PDPage extends LoggingObject implements COSObjectable, Printable
{
+ private static final int DEFAULT_USER_SPACE_UNIT_DPI = 72;
+
private COSDictionary page;
/**
@@ -642,7 +642,8 @@
}
/**
- * Convert this page to an output image.
+ * Convert this page to an output image with 8 bits per pixel and the double
+ * default screen resolution.
*
* @return A graphical representation of this page.
*
@@ -650,36 +651,59 @@
*/
public BufferedImage convertToImage() throws IOException
{
- int scaling = 2;
- PDRectangle mBox = findMediaBox();
- int width = (int)(mBox.getWidth());//*2);
- int height = (int)(mBox.getHeight());//*2);
- Dimension pageDimension = new Dimension( width, height );
-
//note we are doing twice as many pixels because
//the default size is not really good resolution,
//so create an image that is twice the size
//and let the client scale it down.
- BufferedImage retval = new BufferedImage( width*scaling, height*scaling, BufferedImage.TYPE_BYTE_INDEXED );
+ return convertToImage(8, 2 * DEFAULT_USER_SPACE_UNIT_DPI);
+ }
+
+ /**
+ * Convert this page to an output image.
+ *
+ * @param imageType the image type (see {@link BufferedImage}.TYPE_*)
+ * @param resolution the resolution in dpi (dots per inch)
+ * @return A graphical representation of this page.
+ *
+ * @throws IOException If there is an error drawing to the image.
+ */
+ public BufferedImage convertToImage(int imageType, int resolution) throws IOException
+ {
+ PDRectangle mBox = findMediaBox();
+ float widthPt = mBox.getWidth();
+ float heightPt = mBox.getHeight();
+ float scaling = resolution / (float)DEFAULT_USER_SPACE_UNIT_DPI;
+ int widthPx = Math.round(widthPt * scaling);
+ int heightPx = Math.round(heightPt * scaling);
+ //TODO The following reduces accuracy. It should really be a Dimension2D.Float.
+ Dimension pageDimension = new Dimension( (int)widthPt, (int)heightPt );
+
+ BufferedImage retval = new BufferedImage( widthPx, heightPx, imageType );
Graphics2D graphics = (Graphics2D)retval.getGraphics();
- graphics.setColor( Color.WHITE );
- graphics.fillRect(0,0,width*scaling, height*scaling);
+ graphics.setBackground( Color.WHITE );
+ graphics.clearRect( 0, 0, retval.getWidth(), retval.getHeight() );
graphics.scale( scaling, scaling );
PageDrawer drawer = new PageDrawer();
drawer.drawPage( graphics, this, pageDimension );
- try{
+ //TODO This could be done directly by manipulating the transformation matrix before painting.
+ //That could result in a better image quality.
+ try
+ {
int rotation = findRotation();
- if (rotation == 90 || rotation == 270) {
+ if (rotation == 90 || rotation == 270)
+ {
int w = retval.getWidth();
int h = retval.getHeight();
- BufferedImage rotated_img = new BufferedImage(w, h, retval.getType());
- Graphics2D g = rotated_img.createGraphics();
+ BufferedImage rotatedImg = new BufferedImage(w, h, retval.getType());
+ Graphics2D g = rotatedImg.createGraphics();
g.rotate(Math.toRadians(rotation), w/2, h/2);
g.drawImage(retval, null, 0, 0);
}
- } catch (ImagingOpException e){
- logger().log(Level.WARNING, "Unable to rotate page image", e);
+ }
+ catch (ImagingOpException e)
+ {
+ logger().log(Level.WARNING, "Unable to rotate page image", e);
}
return retval;
Modified: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java (original)
+++ incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java Wed Jul 8 06:02:34 2009
@@ -309,7 +309,7 @@
}
}
-/**
+ /**
* This will get the CropBox at this page and not look up the hierarchy.
* This attribute is inheritable, and findCropBox() should probably used.
* This will return null if no CropBox is available at this level.
Modified: incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java (original)
+++ incubator/pdfbox/trunk/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java Wed Jul 8 06:02:34 2009
@@ -16,9 +16,11 @@
*/
package org.apache.pdfbox.util;
-import java.io.IOException;
+import java.awt.Toolkit;
import java.awt.image.BufferedImage;
+import java.awt.image.RenderedImage;
import java.io.File;
+import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
@@ -26,22 +28,27 @@
import javax.imageio.IIOException;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
+import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
+import javax.imageio.metadata.IIOInvalidTreeException;
+import javax.imageio.metadata.IIOMetadata;
+import javax.imageio.metadata.IIOMetadataNode;
import javax.imageio.stream.ImageOutputStream;
-import org.apache.pdfbox.exceptions.InvalidPasswordException;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
/**
- * This class will take a pdf document and strip out all of the text and ignore the
+ * This class will take a PDF document and strip out all of the text and ignore the
* formatting and such. Please note; it is up to clients of this class to verify that
* a specific user has the correct permissions to extract text from the
* PDF document.
- *
- *Patterned after PDFTextStripper
+ * <p>
+ * Patterned after PDFTextStripper.
*
* @author <a href="mailto:DanielWilson@Users.SourceForge.net">Daniel Wilson</a>
* @version $Revision: 1.1 $
@@ -72,71 +79,170 @@
super( props );
}
-
- public boolean WriteImage(PDDocument document, String imageType, String password, int startPage, int endPage, String outputPrefix) throws IOException {
- boolean bSuccess = true;
- List pages = document.getDocumentCatalog().getAllPages();
- for( int i=startPage-1; i<endPage && i<pages.size(); i++ )
+ /**
+ * Converts a given page range of a PDF document to bitmap images.
+ * @param document the PDF document
+ * @param imageType the target format (ex. "png")
+ * @param password the password (needed if the PDF is encrypted)
+ * @param startPage the start page (1 is the first page)
+ * @param endPage the end page (set to Integer.MAX_VALUE for all pages)
+ * @param outputPrefix used to construct the filename for the individual images
+ * @return true if the images were produced, false if there was an error
+ * @throws IOException if an I/O error occurs
+ */
+ public boolean writeImage(PDDocument document, String imageType, String password,
+ int startPage, int endPage, String outputPrefix)
+ throws IOException
+ {
+ return writeImage(document, imageType, password, startPage, endPage, outputPrefix,
+ 8, Toolkit.getDefaultToolkit().getScreenResolution());
+ }
+
+ /**
+ * Converts a given page range of a PDF document to bitmap images.
+ * @param document the PDF document
+ * @param imageFormat the target format (ex. "png")
+ * @param password the password (needed if the PDF is encrypted)
+ * @param startPage the start page (1 is the first page)
+ * @param endPage the end page (set to Integer.MAX_VALUE for all pages)
+ * @param outputPrefix used to construct the filename for the individual images
+ * @param imageType the image type (see {@link BufferedImage}.TYPE_*)
+ * @param resolution the resolution in dpi (dots per inch)
+ * @return true if the images were produced, false if there was an error
+ * @throws IOException if an I/O error occurs
+ */
+ public boolean writeImage(PDDocument document, String imageFormat, String password,
+ int startPage, int endPage, String outputPrefix, int imageType, int resolution)
+ throws IOException
+ {
+ boolean bSuccess = true;
+ List pages = document.getDocumentCatalog().getAllPages();
+ for( int i = startPage - 1; i < endPage && i < pages.size(); i++ )
+ {
+ ImageOutputStream output = null;
+ ImageWriter imageWriter = null;
+ try
+ {
+ PDPage page = (PDPage)pages.get( i );
+ BufferedImage image = page.convertToImage(imageType, resolution);
+ String fileName = outputPrefix + (i + 1) + "." + imageFormat;
+ System.out.println( "Writing: " + fileName );
+ output = ImageIO.createImageOutputStream( new File( fileName ) );
+
+ boolean foundWriter = false;
+ Iterator writerIter = ImageIO.getImageWritersByFormatName( imageFormat );
+ while( writerIter.hasNext() && !foundWriter )
{
- ImageOutputStream output = null;
- ImageWriter imageWriter = null;
try
{
- PDPage page = (PDPage)pages.get( i );
- BufferedImage image = page.convertToImage();
- String fileName = outputPrefix + (i+1) + "." + imageType;
- System.out.println( "Writing:" + fileName );
- output = ImageIO.createImageOutputStream( new File( fileName ) );
-
- boolean foundWriter = false;
- Iterator writerIter = ImageIO.getImageWritersByFormatName( imageType );
- while( writerIter.hasNext() && !foundWriter )
+ imageWriter = (ImageWriter)writerIter.next();
+ ImageWriteParam writerParams = imageWriter.getDefaultWriteParam();
+ if( writerParams.canWriteCompressed() )
{
- try
- {
- imageWriter = (ImageWriter)writerIter.next();
- ImageWriteParam writerParams = imageWriter.getDefaultWriteParam();
- if(writerParams.canWriteCompressed() )
- {
- writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
- writerParams.setCompressionQuality(1.0f);
- }
-
-
- imageWriter.setOutput( output );
- imageWriter.write( null, new IIOImage( image, null, null), writerParams );
- foundWriter = true;
- }
- catch( IIOException io )
- {
- //ignore exception
- }
- finally
- {
- if( imageWriter != null )
- {
- imageWriter.dispose();
- }
- }
+ writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+ writerParams.setCompressionQuality(1.0f);
}
- if( !foundWriter )
+ IIOMetadata meta = createMetadata( image, imageWriter, writerParams, resolution);
+ imageWriter.setOutput( output );
+ imageWriter.write( null, new IIOImage( image, null, meta ), writerParams );
+ foundWriter = true;
+ }
+ catch( IIOException io )
+ {
+ throw new IOException( io.getMessage() );
+ }
+ finally
+ {
+ if( imageWriter != null )
{
- bSuccess=false;
- throw new RuntimeException( "Error: no writer found for image type '" + imageType + "'" );
-
+ imageWriter.dispose();
}
+ }
+ }
+ if( !foundWriter )
+ {
+ bSuccess = false;
}
- finally
- {
- if( output != null )
- {
- output.flush();
- output.close();
- }
- }
}
- //}
- return bSuccess;
-}
+ finally
+ {
+ if( output != null )
+ {
+ output.flush();
+ output.close();
+ }
+ }
+ }
+ return bSuccess;
+ }
+
+ private IIOMetadata createMetadata(RenderedImage image, ImageWriter imageWriter,
+ ImageWriteParam writerParams, int resolution)
+ {
+ ImageTypeSpecifier type;
+ if (writerParams.getDestinationType() != null)
+ {
+ type = writerParams.getDestinationType();
+ }
+ else
+ {
+ type = ImageTypeSpecifier.createFromRenderedImage( image );
+ }
+ IIOMetadata meta = imageWriter.getDefaultImageMetadata( type, writerParams );
+ return (addResolution(meta, resolution) ? meta : null);
+ }
+
+ private static final String STANDARD_METADATA_FORMAT = "javax_imageio_1.0";
+
+ private boolean addResolution(IIOMetadata meta, int resolution)
+ {
+ if (meta.isStandardMetadataFormatSupported())
+ {
+ IIOMetadataNode root = (IIOMetadataNode)meta.getAsTree(STANDARD_METADATA_FORMAT);
+ IIOMetadataNode dim = getChildNode(root, "Dimension");
+ IIOMetadataNode child;
+ child = getChildNode(dim, "HorizontalPixelSize");
+ if (child == null)
+ {
+ child = new IIOMetadataNode("HorizontalPixelSize");
+ dim.appendChild(child);
+ }
+ child.setAttribute("value",
+ Double.toString(resolution / 25.4));
+ child = getChildNode(dim, "VerticalPixelSize");
+ if (child == null)
+ {
+ child = new IIOMetadataNode("VerticalPixelSize");
+ dim.appendChild(child);
+ }
+ child.setAttribute("value",
+ Double.toString(resolution / 25.4));
+ try
+ {
+ meta.mergeTree(STANDARD_METADATA_FORMAT, root);
+ }
+ catch (IIOInvalidTreeException e)
+ {
+ throw new RuntimeException("Cannot update image metadata: "
+ + e.getMessage());
+ }
+ return true;
+ }
+ return false;
+ }
+
+ private static IIOMetadataNode getChildNode(Node n, String name)
+ {
+ NodeList nodes = n.getChildNodes();
+ for (int i = 0; i < nodes.getLength(); i++)
+ {
+ Node child = nodes.item(i);
+ if (name.equals(child.getNodeName()))
+ {
+ return (IIOMetadataNode)child;
+ }
+ }
+ return null;
+ }
}
Modified: incubator/pdfbox/trunk/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java
URL: http://svn.apache.org/viewvc/incubator/pdfbox/trunk/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java?rev=792043&r1=792042&r2=792043&view=diff
==============================================================================
--- incubator/pdfbox/trunk/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java (original)
+++ incubator/pdfbox/trunk/src/test/java/org/apache/pdfbox/util/TestPDFToImage.java Wed Jul 8 06:02:34 2009
@@ -16,27 +16,18 @@
*/
package org.apache.pdfbox.util;
-import java.io.*; //for BufferedReader
-/*import java.io.File;
+import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
-import java.io.FileOutputStream;
import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
import java.io.PrintWriter;
-import java.io.Writer;
-*/
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.pdfbox.pdmodel.PDDocument;
-import org.apache.pdfbox.util.PDFImageWriter;
/**
* Test suite for PDFTextStripper.
@@ -105,58 +96,58 @@
public void doTestFile(File file, boolean bLogResult)
throws Exception
{
- String sCmd;
PDDocument document = null;
log.println("\nPreparing to convert " + file.getName());
log.flush();
- try
- {
- document = PDDocument.load(file);
- writer.WriteImage(document,"png","",1,Integer.MAX_VALUE, "test/output/" + file.getName() + "-");
- }
- catch(Exception e)
- {
- this.bFail=true;
- System.err.println("Error converting file " + file.getName());
- e.printStackTrace();
-
- log.println("Error converting file " + file.getName() + "\n" + e);
-
- }
- finally{
- document.close();
- }
-
- //Now check the resulting files ... did we get identical PNG(s)?
- try
- {
- mcurFile = file;
+ try
+ {
+ document = PDDocument.load(file);
+ writer.writeImage(document, "png", "", 1, Integer.MAX_VALUE, "test/output/" + file.getName() + "-");
+ }
+ catch(Exception e)
+ {
+ this.bFail=true;
+ System.err.println("Error converting file " + file.getName());
+ e.printStackTrace();
+ log.println("Error converting file " + file.getName() + "\n" + e);
- File[] outFiles = testDir().listFiles(new FilenameFilter()
- {
+ }
+ finally
+ {
+ document.close();
+ }
+
+ //Now check the resulting files ... did we get identical PNG(s)?
+ try
+ {
+ mcurFile = file;
+
+ File[] outFiles = testDir().listFiles(new FilenameFilter()
+ {
public boolean accept(File dir, String name)
{
return (name.endsWith(".png") && name.startsWith(mcurFile.getName(),0));
}
- });
- for (int n = 0; n < outFiles.length; n++)
+ });
+ for (int n = 0; n < outFiles.length; n++)
{
File outFile = new File("test/output/" + outFiles[n].getName());
if (!outFile.exists() ||
- !filesAreIdentical(outFiles[n], outFile)){
- this.bFail=true;
- log.println("Input and output not identical for file: " + outFile.getName());
- }
+ !filesAreIdentical(outFiles[n], outFile))
+ {
+ this.bFail=true;
+ log.println("Input and output not identical for file: " + outFile.getName());
+ }
}
}
- catch(Exception e)
- {
- this.bFail=true;
- System.err.println("Error comparing file output for " + file.getName());
- e.printStackTrace();
- }
+ catch(Exception e)
+ {
+ this.bFail=true;
+ System.err.println("Error comparing file output for " + file.getName());
+ e.printStackTrace();
+ }
}
@@ -229,55 +220,64 @@
junit.textui.TestRunner.main( arg );
}
- public static boolean filesAreIdentical(File left, File right) throws IOException
+ private static boolean filesAreIdentical(File left, File right) throws IOException
{
- //http://forum.java.sun.com/thread.jspa?threadID=688105&messageID=4003259
+ //http://forum.java.sun.com/thread.jspa?threadID=688105&messageID=4003259
- /* -- I reworked ASSERT's into IF statement -- dwilson
+ /* -- I reworked ASSERT's into IF statement -- dwilson
assert left != null;
assert right != null;
assert left.exists();
assert right.exists();
*/
- if(left != null && right != null && left.exists() && right.exists()){
- if (left.length() != right.length())
- return false;
-
- FileInputStream lin = new FileInputStream(left);
- FileInputStream rin = new FileInputStream(right);
- try
- {
- byte[] lbuffer = new byte[4096];
- byte[] rbuffer = new byte[lbuffer.length];
- for (int lcount = 0; (lcount = lin.read(lbuffer)) > 0;)
- {
- int bytesRead = 0;
- for (int rcount = 0; (rcount = rin.read(rbuffer, bytesRead, lcount - bytesRead)) > 0;)
- {
- bytesRead += rcount;
- }
- for (int byteIndex = 0; byteIndex < lcount; byteIndex++)
- {
- if (lbuffer[byteIndex] != rbuffer[byteIndex])
- return false;
- }
- }
- }
- finally
- {
- lin.close();
- rin.close();
- }
- return true;
- }else{
- return false;
- }
+ if(left != null && right != null && left.exists() && right.exists())
+ {
+ if (left.length() != right.length())
+ {
+ return false;
+ }
+
+ FileInputStream lin = new FileInputStream(left);
+ FileInputStream rin = new FileInputStream(right);
+ try
+ {
+ byte[] lbuffer = new byte[4096];
+ byte[] rbuffer = new byte[lbuffer.length];
+ for (int lcount = 0; (lcount = lin.read(lbuffer)) > 0;)
+ {
+ int bytesRead = 0;
+ for (int rcount = 0; (rcount = rin.read(rbuffer, bytesRead, lcount - bytesRead)) > 0;)
+ {
+ bytesRead += rcount;
+ }
+ for (int byteIndex = 0; byteIndex < lcount; byteIndex++)
+ {
+ if (lbuffer[byteIndex] != rbuffer[byteIndex])
+ {
+ return false;
+ }
+ }
+ }
+ }
+ finally
+ {
+ lin.close();
+ rin.close();
+ }
+ return true;
+ }
+ else
+ {
+ return false;
+ }
}
- private File testDir(){
+ private File testDir()
+ {
if (null==mdirTest)
+ {
mdirTest = new File("test/input/rendering");
-
+ }
return mdirTest;
}
}