pdfbox-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From til...@apache.org
Subject svn commit: r1792647 [2/2] - in /pdfbox/trunk/examples/src: main/java/org/apache/pdfbox/examples/interactive/form/ main/java/org/apache/pdfbox/examples/pdmodel/ main/java/org/apache/pdfbox/examples/printing/ main/java/org/apache/pdfbox/examples/renderi...
Date Tue, 25 Apr 2017 19:55:48 GMT
Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldType1.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldType1.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldType1.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/HelloWorldType1.java
Tue Apr 25 19:55:48 2017
@@ -48,8 +48,7 @@ public final class HelloWorldType1
         String message = args[1];
         String pfbPath = args[2];
         
-        PDDocument doc = new PDDocument();
-        try
+        try (PDDocument doc = new PDDocument())
         {
             PDPage page = new PDPage();
             doc.addPage(page);
@@ -67,9 +66,5 @@ public final class HelloWorldType1
             doc.save(file);
             System.out.println(file + " created!");    
         }
-        finally
-        {
-            doc.close();
-        }
     }
 }

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ImageToPDF.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ImageToPDF.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ImageToPDF.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ImageToPDF.java
Tue Apr 25 19:55:48 2017
@@ -50,8 +50,7 @@ public final class ImageToPDF
             System.exit(1);
         }
 
-        PDDocument doc = new PDDocument();
-        try
+        try (PDDocument doc = new PDDocument())
         {
             PDPage page = new PDPage();
             doc.addPage(page);
@@ -72,9 +71,5 @@ public final class ImageToPDF
             contents.close();
             doc.save(pdfPath);
         }
-        finally
-        {
-            doc.close();
-        }
     }
 }

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintBookmarks.java
Tue Apr 25 19:55:48 2017
@@ -47,10 +47,8 @@ public class PrintBookmarks
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]) );
                 PrintBookmarks meta = new PrintBookmarks();
                 PDDocumentOutline outline =  document.getDocumentCatalog().getDocumentOutline();
                 if( outline != null )
@@ -62,13 +60,6 @@ public class PrintBookmarks
                     System.out.println( "This document does not contain any bookmarks" );
                 }
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/PrintDocumentMetaData.java
Tue Apr 25 19:55:48 2017
@@ -49,20 +49,11 @@ public class PrintDocumentMetaData
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]));
                 PrintDocumentMetaData meta = new PrintDocumentMetaData();
                 meta.printMetadata( document );
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RemoveFirstPage.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RemoveFirstPage.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RemoveFirstPage.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RemoveFirstPage.java
Tue Apr 25 19:55:48 2017
@@ -48,10 +48,8 @@ public final class RemoveFirstPage
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]) );
                 if( document.isEncrypted() )
                 {
                     throw new IOException( "Encrypted documents are not supported for this
example" );
@@ -64,13 +62,6 @@ public final class RemoveFirstPage
                 document.removePage( 0 );
                 document.save( args[1] );
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStamp.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStamp.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStamp.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStamp.java
Tue Apr 25 19:55:48 2017
@@ -53,10 +53,8 @@ public final class RubberStamp
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]) );
                 if( document.isEncrypted() )
                 {
                     throw new IOException( "Encrypted documents are not supported for this
example" );
@@ -75,13 +73,6 @@ public final class RubberStamp
 
                 document.save( args[1] );
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStampWithImage.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStampWithImage.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStampWithImage.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/RubberStampWithImage.java
Tue Apr 25 19:55:48 2017
@@ -62,10 +62,8 @@ public class RubberStampWithImage
         }
         else 
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]) );
                 if( document.isEncrypted() )
                 {
                     throw new IOException( "Encrypted documents are not supported for this
example" );
@@ -106,9 +104,10 @@ public class RubberStampWithImage
                     form.setFormType(1);
 
                     // adjust the image to the target rectangle and add it to the stream
-                    OutputStream os = form.getStream().createOutputStream();
-                    drawXObject(ximage, form.getResources(), os, lowerLeftX, lowerLeftY,
imgWidth, imgHeight);
-                    os.close();
+                    try (OutputStream os = form.getStream().createOutputStream())
+                    {
+                        drawXObject(ximage, form.getResources(), os, lowerLeftX, lowerLeftY,
imgWidth, imgHeight);
+                    }
 
                     PDAppearanceStream myDic = new PDAppearanceStream(form.getCOSObject());
                     PDAppearanceDictionary appearance = new PDAppearanceDictionary(new COSDictionary());
@@ -122,13 +121,6 @@ public class RubberStampWithImage
                 }
                 document.save( args[1] );
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
     

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowColorBoxes.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowColorBoxes.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowColorBoxes.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/ShowColorBoxes.java
Tue Apr 25 19:55:48 2017
@@ -42,8 +42,7 @@ public final class ShowColorBoxes
         
         String filename = args[0];
 
-        PDDocument doc = new PDDocument();
-        try
+        try (PDDocument doc = new PDDocument())
         {
             PDPage page = new PDPage();
             doc.addPage(page);
@@ -63,9 +62,5 @@ public final class ShowColorBoxes
             contents.close();
             doc.save(filename);
         }
-        finally
-        {
-            doc.close();
-        }
     }
 }

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/SuperimposePage.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/SuperimposePage.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/SuperimposePage.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/SuperimposePage.java
Tue Apr 25 19:55:48 2017
@@ -48,13 +48,10 @@ public final class SuperimposePage
         String sourcePath = args[0];
         String destPath = args[1];
         
-        PDDocument sourceDoc = null;
-        try
+        try (PDDocument sourceDoc = PDDocument.load(new File(sourcePath)))
         {
-            // load the source PDF
-            sourceDoc = PDDocument.load(new File(sourcePath));
             int sourcePage = 1;
-            
+
             // create a new PDF and add a blank page
             PDDocument doc = new PDDocument();
             PDPage page = new PDPage();
@@ -93,12 +90,5 @@ public final class SuperimposePage
             doc.save(destPath);
             doc.close();
         }
-        finally
-        {
-            if (sourceDoc != null)
-            {
-                sourceDoc.close();
-            }
-        }
     }
 }

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/UsingTextMatrix.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/UsingTextMatrix.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/UsingTextMatrix.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/pdmodel/UsingTextMatrix.java
Tue Apr 25 19:55:48 2017
@@ -51,11 +51,8 @@ public class UsingTextMatrix
     public void doIt( String message, String  outfile ) throws IOException
     {
         // the document
-        PDDocument doc = null;
-        try
+        try (PDDocument doc = new PDDocument())
         {
-            doc = new PDDocument();
-
             // Page 1
             PDFont font = PDType1Font.HELVETICA;
             PDPage page = new PDPage(PDRectangle.A4);
@@ -134,13 +131,6 @@ public class UsingTextMatrix
 
             doc.save( outfile );
         }
-        finally
-        {
-            if( doc != null )
-            {
-                doc.close();
-            }
-        }
     }
 
     /**

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/printing/Printing.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/printing/Printing.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/printing/Printing.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/printing/Printing.java
Tue Apr 25 19:55:48 2017
@@ -52,15 +52,15 @@ public final class Printing
         }
 
         String filename = args[0];
-        PDDocument document = PDDocument.load(new File(filename));
-        
-        // choose your printing method:
-        print(document); 
-        //printWithAttributes(document);
-        //printWithDialog(document);
-        //printWithDialogAndAttributes(document);
-        //printWithPaper(document);
-        document.close();
+        try (PDDocument document = PDDocument.load(new File(filename)))
+        {
+            // choose your printing method:
+            print(document);
+            //printWithAttributes(document);
+            //printWithDialog(document);
+            //printWithDialogAndAttributes(document);
+            //printWithPaper(document);
+        }
     }
 
     /**

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomGraphicsStreamEngine.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomGraphicsStreamEngine.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomGraphicsStreamEngine.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomGraphicsStreamEngine.java
Tue Apr 25 19:55:48 2017
@@ -47,11 +47,12 @@ public class CustomGraphicsStreamEngine
         File file = new File("src/main/resources/org/apache/pdfbox/examples/rendering/",
                              "custom-render-demo.pdf");
 
-        PDDocument doc = PDDocument.load(file);
-        PDPage page = doc.getPage(0);
-        CustomGraphicsStreamEngine engine = new CustomGraphicsStreamEngine(page);
-        engine.run();
-        doc.close();
+        try (PDDocument doc = PDDocument.load(file))
+        {
+            PDPage page = doc.getPage(0);
+            CustomGraphicsStreamEngine engine = new CustomGraphicsStreamEngine(page);
+            engine.run();
+        }
     }
     
     /**

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomPageDrawer.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomPageDrawer.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomPageDrawer.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/rendering/CustomPageDrawer.java
Tue Apr 25 19:55:48 2017
@@ -56,11 +56,12 @@ public class CustomPageDrawer
         File file = new File("src/main/resources/org/apache/pdfbox/examples/rendering/",
                              "custom-render-demo.pdf");
         
-        PDDocument doc = PDDocument.load(file);
-        PDFRenderer renderer = new MyPDFRenderer(doc);
-        BufferedImage image = renderer.renderImage(0);
-        ImageIO.write(image, "PNG", new File("custom-render.png"));
-        doc.close();
+        try (PDDocument doc = PDDocument.load(file))
+        {
+            PDFRenderer renderer = new MyPDFRenderer(doc);
+            BufferedImage image = renderer.renderImage(0);
+            ImageIO.write(image, "PNG", new File("custom-render.png"));
+        }
     }
 
     /**

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmptySignatureForm.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmptySignatureForm.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmptySignatureForm.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateEmptySignatureForm.java
Tue Apr 25 19:55:48 2017
@@ -44,41 +44,41 @@ public final class CreateEmptySignatureF
     public static void main(String[] args) throws IOException
     {
         // Create a new document with an empty page.
-        PDDocument document = new PDDocument();
-        PDPage page = new PDPage(PDRectangle.A4);
-        document.addPage(page);
-        
-        // Adobe Acrobat uses Helvetica as a default font and 
-        // stores that under the name '/Helv' in the resources dictionary
-        PDFont font = PDType1Font.HELVETICA;
-        PDResources resources = new PDResources();
-        resources.put(COSName.getPDFName("Helv"), font);
-        
-        // Add a new AcroForm and add that to the document
-        PDAcroForm acroForm = new PDAcroForm(document);
-        document.getDocumentCatalog().setAcroForm(acroForm);
-        
-        // Add and set the resources and default appearance at the form level
-        acroForm.setDefaultResources(resources);
-        
-        // Acrobat sets the font size on the form level to be
-        // auto sized as default. This is done by setting the font size to '0'
-        String defaultAppearanceString = "/Helv 0 Tf 0 g";
-        acroForm.setDefaultAppearance(defaultAppearanceString);
-        
-        // --- end of general AcroForm stuff ---
-        
-        // Create empty signature field, it will get the name "Signature1"
-        PDSignatureField signatureField = new PDSignatureField(acroForm);
-        PDAnnotationWidget widget = signatureField.getWidgets().get(0);
-        PDRectangle rect = new PDRectangle(50, 650, 200, 50);
-        widget.setRectangle(rect);
-        widget.setPage(page);
-        page.getAnnotations().add(widget);
-        
-        acroForm.getFields().add(signatureField);        
+        try (PDDocument document = new PDDocument())
+        {
+            PDPage page = new PDPage(PDRectangle.A4);
+            document.addPage(page);
 
-        document.save("target/EmptySignatureForm.pdf");
-        document.close();
+            // Adobe Acrobat uses Helvetica as a default font and
+            // stores that under the name '/Helv' in the resources dictionary
+            PDFont font = PDType1Font.HELVETICA;
+            PDResources resources = new PDResources();
+            resources.put(COSName.getPDFName("Helv"), font);
+
+            // Add a new AcroForm and add that to the document
+            PDAcroForm acroForm = new PDAcroForm(document);
+            document.getDocumentCatalog().setAcroForm(acroForm);
+
+            // Add and set the resources and default appearance at the form level
+            acroForm.setDefaultResources(resources);
+
+            // Acrobat sets the font size on the form level to be
+            // auto sized as default. This is done by setting the font size to '0'
+            String defaultAppearanceString = "/Helv 0 Tf 0 g";
+            acroForm.setDefaultAppearance(defaultAppearanceString);
+            // --- end of general AcroForm stuff ---
+
+            // Create empty signature field, it will get the name "Signature1"
+            PDSignatureField signatureField = new PDSignatureField(acroForm);
+            PDAnnotationWidget widget = signatureField.getWidgets().get(0);
+            PDRectangle rect = new PDRectangle(50, 650, 200, 50);
+            widget.setRectangle(rect);
+            widget.setPage(page);
+            page.getAnnotations().add(widget);
+
+            acroForm.getFields().add(signatureField);
+
+            document.save("target/EmptySignatureForm.pdf");
+        }
     }
 }

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java
Tue Apr 25 19:55:48 2017
@@ -105,9 +105,10 @@ public class CreateSignature extends Cre
         FileOutputStream fos = new FileOutputStream(outFile);
 
         // sign
-        PDDocument doc = PDDocument.load(inFile);
-        signDetached(doc, fos, tsaClient);
-        doc.close();
+        try (PDDocument doc = PDDocument.load(inFile))
+        {
+            signDetached(doc, fos, tsaClient);
+        }
     }
 
     public void signDetached(PDDocument document, OutputStream output, TSAClient tsaClient)

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateVisibleSignature.java
Tue Apr 25 19:55:48 2017
@@ -141,112 +141,112 @@ public class CreateVisibleSignature exte
         // creating output document and prepare the IO streams.
         FileOutputStream fos = new FileOutputStream(signedFile);
 
-        // load document
-        PDDocument doc = PDDocument.load(inputFile);
-
-        int accessPermissions = getMDPPermission(doc);
-        if (accessPermissions == 1)
+        try (PDDocument doc = PDDocument.load(inputFile))
         {
-            throw new IllegalStateException("No changes to the document are permitted due
to DocMDP transform parameters dictionary");
-        }
-        // Note that PDFBox has a bug that visual signing on certified files with permission
2
-        // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you may
want to 
-        // be careful with such files.        
+            int accessPermissions = getMDPPermission(doc);
+            if (accessPermissions == 1)
+            {
+                throw new IllegalStateException("No changes to the document are permitted
due to DocMDP transform parameters dictionary");
+            }
+            // Note that PDFBox has a bug that visual signing on certified files with permission
2
+            // doesn't work properly, see PDFBOX-3699. As long as this issue is open, you
may want to
+            // be careful with such files.
 
-        PDSignature signature;
+            PDSignature signature;
 
-        // sign a PDF with an existing empty signature, as created by the CreateEmptySignatureForm
example. 
-        signature = findExistingSignature(doc, signatureFieldName);
+            // sign a PDF with an existing empty signature, as created by the CreateEmptySignatureForm
example.
+            signature = findExistingSignature(doc, signatureFieldName);
 
-        if (signature == null)
-        {
-            // create signature dictionary
-            signature = new PDSignature();
-        }
+            if (signature == null)
+            {
+                // create signature dictionary
+                signature = new PDSignature();
+            }
 
-        // Optional: certify 
-        if (accessPermissions == 0)
-        {
-            setMDPPermission(doc, signature, 2);
-        }      
+            // Optional: certify
+            if (accessPermissions == 0)
+            {
+                setMDPPermission(doc, signature, 2);
+            }
 
-        // default filter
-        signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
-        
-        // subfilter for basic and PAdES Part 2 signatures
-        signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
-        
-        if (visibleSignatureProperties != null)
-        {
-            // this builds the signature structures in a separate document
-            visibleSignatureProperties.buildSignature();
+            // default filter
+            signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
 
-            signature.setName(visibleSignatureProperties.getSignerName());
-            signature.setLocation(visibleSignatureProperties.getSignerLocation());
-            signature.setReason(visibleSignatureProperties.getSignatureReason());
-        }
+            // subfilter for basic and PAdES Part 2 signatures
+            signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
 
-        // the signing date, needed for valid signature
-        signature.setSignDate(Calendar.getInstance());
+            if (visibleSignatureProperties != null)
+            {
+                // this builds the signature structures in a separate document
+                visibleSignatureProperties.buildSignature();
 
-        // do not set SignatureInterface instance, if external signing used
-        SignatureInterface signatureInterface = isExternalSigning() ? null : this;
+                signature.setName(visibleSignatureProperties.getSignerName());
+                signature.setLocation(visibleSignatureProperties.getSignerLocation());
+                signature.setReason(visibleSignatureProperties.getSignatureReason());
+            }
+            
+            // the signing date, needed for valid signature
+            signature.setSignDate(Calendar.getInstance());
 
-        // register signature dictionary and sign interface
-        if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled())
-        {
-            signatureOptions = new SignatureOptions();
-            signatureOptions.setVisualSignature(visibleSignatureProperties.getVisibleSignature());
-            signatureOptions.setPage(visibleSignatureProperties.getPage() - 1);
-            doc.addSignature(signature, signatureInterface, signatureOptions);
-        }
-        else
-        {
-            doc.addSignature(signature, signatureInterface);
-        }
+            // do not set SignatureInterface instance, if external signing used
+            SignatureInterface signatureInterface = isExternalSigning() ? null : this;
 
-        if (isExternalSigning())
-        {
-            System.out.println("Signing externally " + signedFile.getName());
-            ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(fos);
-            // invoke external signature service
-            byte[] cmsSignature = sign(externalSigning.getContent());
+            // register signature dictionary and sign interface
+            if (visibleSignatureProperties != null && visibleSignatureProperties.isVisualSignEnabled())
+            {
+                signatureOptions = new SignatureOptions();
+                signatureOptions.setVisualSignature(visibleSignatureProperties.getVisibleSignature());
+                signatureOptions.setPage(visibleSignatureProperties.getPage() - 1);
+                doc.addSignature(signature, signatureInterface, signatureOptions);
+            }
+            else
+            {
+                doc.addSignature(signature, signatureInterface);
+            }
 
-            // Explanation of late external signing (off by default):
-            // If you want to add the signature in a separate step, then set an empty byte
array
-            // and call signature.getByteRange() and remember the offset signature.getByteRange()[1]+1.
-            // you can write the ascii hex signature at a later time even if you don't have
this
-            // PDDocument object anymore, with classic java file random access methods.
-            // If you can't remember the offset value from ByteRange because your context
has changed, 
-            // then open the file with PDFBox, find the field with findExistingSignature()
or
-            // PODDocument.getLastSignatureDictionary() and get the ByteRange from there.
-            // Close the file and then write the signature as explained earlier in this comment.
-            if (isLateExternalSigning())
+            if (isExternalSigning())
             {
-                // this saves the file with a 0 signature
-                externalSigning.setSignature(new byte[0]);
-                
-                // remember the offset (add 1 because of "<")
-                int offset = signature.getByteRange()[1] + 1;
+                System.out.println("Signing externally " + signedFile.getName());
+                ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(fos);
+                // invoke external signature service
+                byte[] cmsSignature = sign(externalSigning.getContent());
+
+                // Explanation of late external signing (off by default):
+                // If you want to add the signature in a separate step, then set an empty
byte array
+                // and call signature.getByteRange() and remember the offset signature.getByteRange()[1]+1.
+                // you can write the ascii hex signature at a later time even if you don't
have this
+                // PDDocument object anymore, with classic java file random access methods.
+                // If you can't remember the offset value from ByteRange because your context
has changed,
+                // then open the file with PDFBox, find the field with findExistingSignature()
or
+                // PODDocument.getLastSignatureDictionary() and get the ByteRange from there.
+                // Close the file and then write the signature as explained earlier in this
comment.
+                if (isLateExternalSigning())
+                {
+                    // this saves the file with a 0 signature
+                    externalSigning.setSignature(new byte[0]);
 
-                // now write the signature at the correct offset without any PDFBox methods
-                RandomAccessFile raf = new RandomAccessFile(signedFile, "rw");
-                raf.seek(offset);
-                raf.write(Hex.getBytes(cmsSignature));
-                raf.close();
+                    // remember the offset (add 1 because of "<")
+                    int offset = signature.getByteRange()[1] + 1;
+
+                    // now write the signature at the correct offset without any PDFBox methods
+                    try (RandomAccessFile raf = new RandomAccessFile(signedFile, "rw"))
+                    {
+                        raf.seek(offset);
+                        raf.write(Hex.getBytes(cmsSignature));
+                    }
+                }
+                else
+                {
+                    // set signature bytes received from the service and save the file
+                    externalSigning.setSignature(cmsSignature);
+                }
             }
             else
             {
-                // set signature bytes received from the service and save the file
-                externalSigning.setSignature(cmsSignature);
+                // write incremental (only for signing purpose)
+                doc.saveIncremental(fos);
             }
         }
-        else
-        {
-            // write incremental (only for signing purpose)
-            doc.saveIncremental(fos);
-        }
-        doc.close();
         
         // Do not close signatureOptions before saving, because some COSStream objects within
         // are transferred to the signed document.
@@ -350,16 +350,17 @@ public class CreateVisibleSignature exte
 
         CreateVisibleSignature signing = new CreateVisibleSignature(keystore, pin.clone());
 
-        FileInputStream imageStream = new FileInputStream(args[3]);
-
-        String name = documentFile.getName();
-        String substring = name.substring(0, name.lastIndexOf('.'));
-        File signedDocumentFile = new File(documentFile.getParent(), substring + "_signed.pdf");
-
-        // page is 1-based here
-        int page = 1;
-        signing.setVisibleSignDesigner(args[2], 0, 0, -50, imageStream, page);
-        imageStream.close();
+        File signedDocumentFile;
+        int page;
+        try (FileInputStream imageStream = new FileInputStream(args[3]))
+        {
+            String name = documentFile.getName();
+            String substring = name.substring(0, name.lastIndexOf('.'));
+            signedDocumentFile = new File(documentFile.getParent(), substring + "_signed.pdf");
+            // page is 1-based here
+            page = 1;
+            signing.setVisibleSignDesigner(args[2], 0, 0, -50, imageStream, page);
+        }
         signing.setVisibleSignatureProperties("name", "location", "Security", 0, page, true);
         signing.setExternalSigning(externalSig);
         signing.signPDF(documentFile, signedDocumentFile, tsaClient);

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/DrawPrintTextLocations.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/DrawPrintTextLocations.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/DrawPrintTextLocations.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/DrawPrintTextLocations.java
Tue Apr 25 19:55:48 2017
@@ -96,11 +96,8 @@ public class DrawPrintTextLocations exte
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load(new File(args[0]));
-
                 DrawPrintTextLocations stripper = new DrawPrintTextLocations(document, args[0]);
                 stripper.setSortByPosition(true);
 
@@ -109,13 +106,6 @@ public class DrawPrintTextLocations exte
                     stripper.stripPage(page);
                 }
             }
-            finally
-            {
-                if (document != null)
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextLocations.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextLocations.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextLocations.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/PrintTextLocations.java
Tue Apr 25 19:55:48 2017
@@ -57,11 +57,8 @@ public class PrintTextLocations extends
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load( new File(args[0]) );
-
                 PDFTextStripper stripper = new PrintTextLocations();
                 stripper.setSortByPosition( true );
                 stripper.setStartPage( 0 );
@@ -70,13 +67,6 @@ public class PrintTextLocations extends
                 Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
                 stripper.writeText(document, dummy);
             }
-            finally
-            {
-                if( document != null )
-                {
-                    document.close();
-                }
-            }
         }
     }
 

Modified: pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java
(original)
+++ pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/util/RemoveAllText.java
Tue Apr 25 19:55:48 2017
@@ -63,10 +63,8 @@ public final class RemoveAllText
         }
         else
         {
-            PDDocument document = null;
-            try
+            try (PDDocument document = PDDocument.load(new File(args[0])))
             {
-                document = PDDocument.load(new File(args[0]));
                 if (document.isEncrypted())
                 {
                     System.err.println(
@@ -79,13 +77,6 @@ public final class RemoveAllText
                 }
                 document.save(args[1]);
             }
-            finally
-            {
-                if (document != null)
-                {
-                    document.close();
-                }
-            }
         }
     }
 
@@ -123,10 +114,11 @@ public final class RemoveAllText
             newTokens.add(token);
         }
         PDStream newContents = new PDStream(document);
-        OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE);
-        ContentStreamWriter writer = new ContentStreamWriter(out);
-        writer.writeTokens(newTokens);
-        out.close();
+        try (OutputStream out = newContents.createOutputStream(COSName.FLATE_DECODE))
+        {
+            ContentStreamWriter writer = new ContentStreamWriter(out);
+            writer.writeTokens(newTokens);
+        }
         page.setContents(newContents);
         processResources(page.getResources());
     }
@@ -153,10 +145,11 @@ public final class RemoveAllText
             }
             newTokens.add(token);
         }
-        OutputStream out = stream.createOutputStream(COSName.FLATE_DECODE);
-        ContentStreamWriter writer = new ContentStreamWriter(out);
-        writer.writeTokens(newTokens);
-        out.close();
+        try (OutputStream out = stream.createOutputStream(COSName.FLATE_DECODE))
+        {
+            ContentStreamWriter writer = new ContentStreamWriter(out);
+            writer.writeTokens(newTokens);
+        }
         processResources(xobject.getResources());
     }
 

Modified: pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdfa/CreatePDFATest.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdfa/CreatePDFATest.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdfa/CreatePDFATest.java
(original)
+++ pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdfa/CreatePDFATest.java
Tue Apr 25 19:55:48 2017
@@ -59,15 +59,16 @@ public class CreatePDFATest extends Test
         
         PreflightParser preflightParser = new PreflightParser(new File(pdfaFilename));
         preflightParser.parse();
-        PreflightDocument preflightDocument = preflightParser.getPreflightDocument();
-        preflightDocument.validate();
-        ValidationResult result = preflightDocument.getResult();
-        for (ValidationError ve : result.getErrorsList())
+        try (PreflightDocument preflightDocument = preflightParser.getPreflightDocument())
         {
-            System.err.println(ve.getErrorCode() + ": " + ve.getDetails());
+            preflightDocument.validate();
+            ValidationResult result = preflightDocument.getResult();
+            for (ValidationError ve : result.getErrorsList())
+            {
+                System.err.println(ve.getErrorCode() + ": " + ve.getDetails());
+            }
+            assertTrue("PDF file created with CreatePDFA is not valid PDF/A-1b", result.isValid());
         }
-        assertTrue("PDF file created with CreatePDFA is not valid PDF/A-1b", result.isValid());
-        preflightDocument.close();
         
         // check the XMP metadata
         PDDocument document = PDDocument.load(new File(pdfaFilename));

Modified: pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdmodel/TestCreateSignature.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdmodel/TestCreateSignature.java?rev=1792647&r1=1792646&r2=1792647&view=diff
==============================================================================
--- pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdmodel/TestCreateSignature.java
(original)
+++ pdfbox/trunk/examples/src/test/java/org/apache/pdfbox/examples/pdmodel/TestCreateSignature.java
Tue Apr 25 19:55:48 2017
@@ -137,10 +137,12 @@ public class TestCreateSignature
     public void testDetachedSHA256WithTSA()
             throws IOException, CMSException, OperatorCreationException, GeneralSecurityException
     {
+        byte[] content;
         // mock TSA response content
-        InputStream input = new FileInputStream(inDir + "tsa_response.asn1");
-        byte[] content = IOUtils.toByteArray(input);
-        input.close();
+        try (InputStream input = new FileInputStream(inDir + "tsa_response.asn1"))
+        {
+            content = IOUtils.toByteArray(input);
+        }
 
         // mock TSA server (RFC 3161)
         MockHttpServer mockServer = new MockHttpServer(15371);
@@ -196,15 +198,16 @@ public class TestCreateSignature
 
         // sign PDF
         String inPath = inDir + "sign_me.pdf";
-        FileInputStream fis = new FileInputStream(jpegPath);
-        CreateVisibleSignature signing = new CreateVisibleSignature(keystore, password.toCharArray());
-        signing.setVisibleSignDesigner(inPath, 0, 0, -50, fis, 1);
-        signing.setVisibleSignatureProperties("name", "location", "Security", 0, 1, true);
-        signing.setExternalSigning(externallySign);
-
-        File destFile = new File(outDir + getOutputFileName("signed{0}_visible.pdf"));
-        signing.signPDF(new File(inPath), destFile, null);
-        fis.close();
+        File destFile;
+        try (FileInputStream fis = new FileInputStream(jpegPath))
+        {
+            CreateVisibleSignature signing = new CreateVisibleSignature(keystore, password.toCharArray());
+            signing.setVisibleSignDesigner(inPath, 0, 0, -50, fis, 1);
+            signing.setVisibleSignatureProperties("name", "location", "Security", 0, 1, true);
+            signing.setExternalSigning(externallySign);
+            destFile = new File(outDir + getOutputFileName("signed{0}_visible.pdf"));
+            signing.signPDF(new File(inPath), destFile, null);
+        }
 
         checkSignature(destFile);
     }
@@ -218,40 +221,39 @@ public class TestCreateSignature
     private void checkSignature(File file)
             throws IOException, CMSException, OperatorCreationException, GeneralSecurityException
     {
-        PDDocument document = PDDocument.load(file);
-        List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
-        if (signatureDictionaries.isEmpty())
+        try (PDDocument document = PDDocument.load(file))
         {
-            Assert.fail("no signature found");
-        }
-        for (PDSignature sig : document.getSignatureDictionaries())
-        {
-            COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);
-            
-            FileInputStream fis = new FileInputStream(file);
-            byte[] buf = sig.getSignedContent(fis);
-            fis.close();
-
-            // inspiration:
-            // http://stackoverflow.com/a/26702631/535646
-            // http://stackoverflow.com/a/9261365/535646
-            CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf),
contents.getBytes());
-            Store certificatesStore = signedData.getCertificates();
-            Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
-            SignerInformation signerInformation = signers.iterator().next();
-            Collection matches = certificatesStore.getMatches(signerInformation.getSID());
-            X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
-            X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
-
-            Assert.assertEquals(certificate, certFromSignedData);
-
-            // CMSVerifierCertificateNotValidException means that the keystore wasn't valid
at signing time
-            if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData)))
+            List<PDSignature> signatureDictionaries = document.getSignatureDictionaries();
+            if (signatureDictionaries.isEmpty())
+            {
+                Assert.fail("no signature found");
+            }
+            for (PDSignature sig : document.getSignatureDictionaries())
             {
-                Assert.fail("Signature verification failed");
+                COSString contents = (COSString) sig.getCOSObject().getDictionaryObject(COSName.CONTENTS);
+                byte[] buf;
+                try (FileInputStream fis = new FileInputStream(file))
+                {
+                    buf = sig.getSignedContent(fis);
+                }
+                // inspiration:
+                // http://stackoverflow.com/a/26702631/535646
+                // http://stackoverflow.com/a/9261365/535646
+                CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(buf),
contents.getBytes());
+                Store certificatesStore = signedData.getCertificates();
+                Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
+                SignerInformation signerInformation = signers.iterator().next();
+                Collection matches = certificatesStore.getMatches(signerInformation.getSID());
+                X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
+                X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
+                Assert.assertEquals(certificate, certFromSignedData);
+                // CMSVerifierCertificateNotValidException means that the keystore wasn't
valid at signing time
+                if (!signerInformation.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certFromSignedData)))
+                {
+                    Assert.fail("Signature verification failed");
+                }
+                break;
             }
-            break;
         }
-        document.close();
     }
 }



Mime
View raw message