pdfbox-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From le...@apache.org
Subject svn commit: r1198363 - in /pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox: PDFReader.java util/ImageIOUtil.java util/PDFImageWriter.java
Date Sun, 06 Nov 2011 13:39:52 GMT
Author: lehmi
Date: Sun Nov  6 13:39:52 2011
New Revision: 1198363

URL: http://svn.apache.org/viewvc?rev=1198363&view=rev
Log:
PDFBOX-1160: added "Save as image" to PDFReader

Added:
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/ImageIOUtil.java
Modified:
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/PDFReader.java
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/PDFReader.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/PDFReader.java?rev=1198363&r1=1198362&r2=1198363&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/PDFReader.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/PDFReader.java Sun Nov  6 13:39:52
2011
@@ -22,12 +22,14 @@ import org.apache.pdfbox.pdfviewer.Reade
 import org.apache.pdfbox.pdmodel.PDDocument;
 import org.apache.pdfbox.pdmodel.PDPage;
 import org.apache.pdfbox.util.ExtensionFileFilter;
+import org.apache.pdfbox.util.ImageIOUtil;
 
 import javax.swing.JFileChooser;
 import javax.swing.JScrollPane;
 import javax.swing.JPanel;
 import javax.swing.KeyStroke;
 
+import java.awt.image.BufferedImage;
 import java.awt.print.PrinterException;
 import java.io.File;
 import java.io.FileInputStream;
@@ -45,11 +47,9 @@ import java.util.List;
 public class PDFReader extends javax.swing.JFrame
 {
     private File currentDir=new File(".");
-    private javax.swing.JMenuItem aboutMenuItem;
-    private javax.swing.JMenuItem contentsMenuItem;
+    private javax.swing.JMenuItem saveAsImageMenuItem;
     private javax.swing.JMenuItem exitMenuItem;
     private javax.swing.JMenu fileMenu;
-    private javax.swing.JMenu helpMenu;
     private javax.swing.JMenuBar menuBar;
     private javax.swing.JMenuItem openMenuItem;
     private javax.swing.JMenuItem printMenuItem;
@@ -85,10 +85,8 @@ public class PDFReader extends javax.swi
         menuBar = new javax.swing.JMenuBar();
         fileMenu = new javax.swing.JMenu();
         openMenuItem = new javax.swing.JMenuItem();
+        saveAsImageMenuItem = new javax.swing.JMenuItem();
         exitMenuItem = new javax.swing.JMenuItem();
-        helpMenu = new javax.swing.JMenu();
-        contentsMenuItem = new javax.swing.JMenuItem();
-        aboutMenuItem = new javax.swing.JMenuItem();
         printMenuItem = new javax.swing.JMenuItem();
         viewMenu = new javax.swing.JMenu();
         nextPageItem = new javax.swing.JMenuItem();
@@ -145,6 +143,19 @@ public class PDFReader extends javax.swi
         });
         fileMenu.add( printMenuItem );
 
+        saveAsImageMenuItem.setText( "Save as image" );
+        saveAsImageMenuItem.addActionListener(new java.awt.event.ActionListener()
+        {
+            public void actionPerformed(java.awt.event.ActionEvent evt)
+            {
+                if (document != null) 
+                {
+                    saveImage();
+                }
+            }
+        });
+        fileMenu.add( saveAsImageMenuItem );
+
         exitMenuItem.setText("Exit");
         exitMenuItem.addActionListener(new java.awt.event.ActionListener()
         {
@@ -158,15 +169,6 @@ public class PDFReader extends javax.swi
 
         menuBar.add(fileMenu);
 
-        helpMenu.setText("Help");
-        contentsMenuItem.setText("Contents");
-        helpMenu.add(contentsMenuItem);
-
-        aboutMenuItem.setText("About");
-        helpMenu.add(aboutMenuItem);
-
-        //menuBar.add(helpMenu);
-
         viewMenu.setText("View");
         nextPageItem.setText("Next page");
         nextPageItem.setAccelerator(KeyStroke.getKeyStroke('+'));
@@ -200,7 +202,8 @@ public class PDFReader extends javax.swi
     }
 
 
-    private void updateTitle() {
+    private void updateTitle() 
+    {
         setTitle( "PDFBox - " + currentFilename + " ("+(currentPage+1)+"/"+numberOfPages+")");
     }
     
@@ -316,6 +319,26 @@ public class PDFReader extends javax.swi
             exception.printStackTrace();
         }
     }
+
+    private void saveImage()
+    {
+        try 
+        {
+            PDPage pageToSave = (PDPage)pages.get(currentPage);
+            BufferedImage pageAsImage = pageToSave.convertToImage();
+            String imageFilename = currentFilename;
+            if (imageFilename.toLowerCase().endsWith(".pdf"))
+            {
+                imageFilename = imageFilename.substring(0, imageFilename.length()-4);
+            }
+            imageFilename += "_" + (currentPage + 1); 
+            ImageIOUtil.writeImage(pageAsImage, "png", imageFilename,  BufferedImage.TYPE_USHORT_565_RGB,
300);
+        }
+        catch (IOException exception)
+        {
+            exception.printStackTrace();
+        }
+    }
     /**
      * This will parse a document.
      *

Added: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/ImageIOUtil.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/ImageIOUtil.java?rev=1198363&view=auto
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/ImageIOUtil.java (added)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/ImageIOUtil.java Sun Nov  6 13:39:52
2011
@@ -0,0 +1,190 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.pdfbox.util;
+
+import java.awt.image.BufferedImage;
+import java.awt.image.RenderedImage;
+import java.io.File;
+import java.io.IOException;
+import java.util.Iterator;
+
+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.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+
+/**
+ * This class handles some ImageIO operations.
+ *
+ * @version $Revision$
+ * 
+ */
+public class ImageIOUtil
+{   
+    private ImageIOUtil()
+    {
+        // Default constructor
+    }
+
+    /**
+     * Converts a given page range of a PDF document to bitmap images.
+     * @param image the image to be written
+     * @param imageFormat the target format (ex. "png")
+     * @param filename 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 static boolean writeImage(BufferedImage image, String imageFormat, String filename,

+            int imageType, int resolution)
+    throws IOException
+    {
+        boolean bSuccess = true;
+        ImageOutputStream output = null;
+        ImageWriter imageWriter = null;
+        try
+        {
+            String fileName = filename + "." + imageFormat;
+            output = ImageIO.createImageOutputStream( new File( fileName ) );
+    
+            boolean foundWriter = false;
+            Iterator<ImageWriter> writerIter = ImageIO.getImageWritersByFormatName(
imageFormat );
+            while( writerIter.hasNext() && !foundWriter )
+            {
+                try
+                {
+                    imageWriter = (ImageWriter)writerIter.next();
+                    ImageWriteParam writerParams = imageWriter.getDefaultWriteParam();
+                    if( writerParams.canWriteCompressed() )
+                    {
+                        writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
+                        writerParams.setCompressionQuality(1.0f);
+                    }
+                    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 )
+                    {
+                        imageWriter.dispose();
+                    }
+                }
+            }
+            if( !foundWriter )
+            {
+                bSuccess = false;
+            }
+        }
+        finally
+        {
+            if( output != null )
+            {
+                output.flush();
+                output.close();
+            }
+        }
+        return bSuccess;
+    }
+
+    private static 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 static 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: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java?rev=1198363&r1=1198362&r2=1198363&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/util/PDFImageWriter.java Sun Nov 
6 13:39:52 2011
@@ -19,29 +19,13 @@ package org.apache.pdfbox.util;
 import java.awt.HeadlessException;
 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;
 
-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.pdmodel.PDDocument;
 import org.apache.pdfbox.pdmodel.PDPage;
 
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
 
 /**
  * This class will take a PDF document and strip out all of the text and ignore the
@@ -127,130 +111,13 @@ public class PDFImageWriter extends PDFS
         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 )
-                {
-                    try
-                    {
-                        imageWriter = (ImageWriter)writerIter.next();
-                        ImageWriteParam writerParams = imageWriter.getDefaultWriteParam();
-                        if( writerParams.canWriteCompressed() )
-                        {
-                            writerParams.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
-                            writerParams.setCompressionQuality(1.0f);
-                        }
-                        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 )
-                        {
-                            imageWriter.dispose();
-                        }
-                    }
-                }
-                if( !foundWriter )
-                {
-                    bSuccess = false;
-                }
-            }
-            finally
-            {
-                if( output != null )
-                {
-                    output.flush();
-                    output.close();
-                }
-            }
+            PDPage page = (PDPage)pages.get( i );
+            BufferedImage image = page.convertToImage(imageType, resolution);
+            String fileName = outputPrefix + (i + 1);
+            System.out.println( "Writing: " + fileName + "." +imageFormat);
+            bSuccess &= ImageIOUtil.writeImage(image, imageFormat, fileName, imageType,
resolution);
         }
         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;
-    }
-
 }



Mime
View raw message