You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pdfbox.apache.org by ms...@apache.org on 2020/12/08 07:58:57 UTC

svn commit: r1884198 - in /pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools: PDFMerger.java PDFSplit.java

Author: msahyoun
Date: Tue Dec  8 07:58:57 2020
New Revision: 1884198

URL: http://svn.apache.org/viewvc?rev=1884198&view=rev
Log:
PDFBOX-2602: use picocli for command line parsing

Modified:
    pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java
    pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java

Modified: pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java?rev=1884198&r1=1884197&r2=1884198&view=diff
==============================================================================
--- pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java (original)
+++ pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFMerger.java Tue Dec  8 07:58:57 2020
@@ -16,72 +16,70 @@
  */
 package org.apache.pdfbox.tools;
 
+import java.io.File;
 import java.io.IOException;
+import java.io.PrintStream;
+import java.util.concurrent.Callable;
 
 import org.apache.pdfbox.io.MemoryUsageSetting;
 import org.apache.pdfbox.multipdf.PDFMergerUtility;
 
+import picocli.CommandLine;
+import picocli.CommandLine.Command;
+import picocli.CommandLine.Parameters;
+
 /**
  * This is the main program that will take a list of pdf documents and merge them,
  * saving the result in a new document.
  *
  * @author Ben Litchfield
  */
-public final class PDFMerger
+@Command(name = "PDFMerger", description = "Merge multiple PDFs into one.")
+public final class PDFMerger implements Callable<Integer>
 {
-    
-    private PDFMerger()
-    {
-    }
+    // Expected for CLI app to write to System.out/Sytem.err
+    @SuppressWarnings("squid:S106")
+    private static final PrintStream SYSERR = System.err;
+
+    @Parameters(paramLabel = "inputfile", arity = "2..*", description = "the PDF files to merge.")
+    private File[] infiles;
+
+    @Parameters(paramLabel = "outputfile", index="1", description = "the merged PDF file.")
+    private File outfile;
+
     /**
      * Infamous main method.
      *
      * @param args Command line arguments, should be at least 3.
-     *
-     * @throws IOException If there is an error parsing the document.
      */
-    public static void main( String[] args ) throws IOException
+    public static void main( String[] args )
     {
         // suppress the Dock icon on OS X
         System.setProperty("apple.awt.UIElement", "true");
 
-        PDFMerger merge = new PDFMerger();
-        merge.merge( args );
+        int exitCode = new CommandLine(new PDFMerger()).execute(args);
+        System.exit(exitCode);
     }
 
-    private void merge( String[] args ) throws IOException
+    public Integer call()
     {
-        int firstFileArgPos = 0;
+        PDFMergerUtility merger = new PDFMergerUtility();
 
-        if ( args.length - firstFileArgPos < 3 )
+        try
         {
-            usage();
-        }
+            for (File infile : infiles)
+            {
+                merger.addSource(infile);
+            }
 
-        PDFMergerUtility merger = new PDFMergerUtility();
-        for( int i=firstFileArgPos; i<args.length-1; i++ )
+            merger.setDestinationFileName(outfile.getAbsolutePath());
+            merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
+        }
+        catch (IOException ioe)
         {
-            String sourceFileName = args[i];
-            merger.addSource(sourceFileName);
+            SYSERR.println( "Error merging documents: " + ioe.getMessage());
+            return 4;
         }
-
-        String destinationFileName = args[args.length-1];
-        merger.setDestinationFileName(destinationFileName);
-        merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
-    }
-
-    /**
-     * This will print the usage requirements and exit.
-     */
-    private static void usage()
-    {
-        String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFMerger "
-                + "<inputfiles 2..n> <outputfile>\n"
-                + "\nOptions:\n"
-                + "  <inputfiles 2..n> : 2 or more source PDF documents to merge\n"
-                + "  <outputfile>      : The PDF document to save the merged documents to\n";
-        
-        System.err.println(message);
-        System.exit(1);
+        return 0;
     }
 }

Modified: pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java?rev=1884198&r1=1884197&r2=1884198&view=diff
==============================================================================
--- pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java (original)
+++ pdfbox/trunk/tools/src/main/java/org/apache/pdfbox/tools/PDFSplit.java Tue Dec  8 07:58:57 2020
@@ -18,194 +18,134 @@ package org.apache.pdfbox.tools;
 
 import java.io.File;
 import java.io.IOException;
-
+import java.io.PrintStream;
 import java.util.List;
+import java.util.concurrent.Callable;
 
+import org.apache.commons.io.FilenameUtils;
 import org.apache.pdfbox.Loader;
+import org.apache.pdfbox.io.IOUtils;
 import org.apache.pdfbox.multipdf.Splitter;
 import org.apache.pdfbox.pdmodel.PDDocument;
 
+import picocli.CommandLine;
+import picocli.CommandLine.Option;
+import picocli.CommandLine.Parameters;
+
 /**
  * This is the main program that will take a pdf document and split it into
  * a number of other documents.
  *
  * @author Ben Litchfield
  */
-public final class PDFSplit
+public final class PDFSplit implements Callable<Integer>
 {
-    @SuppressWarnings({"squid:S2068"})
-    private static final String PASSWORD = "-password";
-    private static final String SPLIT = "-split";
-    private static final String START_PAGE = "-startPage";
-    private static final String END_PAGE = "-endPage";
-    private static final String OUTPUT_PREFIX = "-outputPrefix";
+    // Expected for CLI app to write to System.out/Sytem.err
+    @SuppressWarnings("squid:S106")
+    private static final PrintStream SYSERR = System.err;
+
+    @Option(names = {"-h", "--help"}, usageHelp = true, description = "display this help message")
+    boolean usageHelpRequested;
+
+    @Option(names = "-password", description = "the password to decrypt the document.")    
+    private String password;
+
+    @Option(names = "-split", description = "split after this many pages (default 1, if startPage and endPage are unset).")    
+    private int split = -1;
+
+    @Option(names = "-startPage", description = "start page.")    
+    private int startPage = -1;
+
+    @Option(names = "-endPage", description = "end page.")    
+    private int endPage = -1;
+
+    @Option(names = "-outputPrefix", description = "the filename prefix for split files.")    
+    private String outputPrefix;
+
+    @Parameters(paramLabel = "inputfile", description = "the PDF file to split.")
+    private File infile;
 
-    private PDFSplit()
-    {
-    }
     /**
      * Infamous main method.
      *
      * @param args Command line arguments, should be one and a reference to a file.
-     *
-     * @throws IOException If there is an error parsing the document.
      */
-    public static void main( String[] args ) throws IOException
+    public static void main( String[] args )
     {
         // suppress the Dock icon on OS X
         System.setProperty("apple.awt.UIElement", "true");
 
-        PDFSplit split = new PDFSplit();
-        split.split( args );
+        int exitCode = new CommandLine(new PDFSplit()).execute(args);
+        System.exit(exitCode);
     }
 
-    private void split( String[] args ) throws IOException
+    public Integer call()
     {
-        @SuppressWarnings({"squid:S2068"})
-        String password = "";
-        String split = null;
-        String startPage = null;
-        String endPage = null;
         Splitter splitter = new Splitter();
-        String pdfFile = null;
-        String outputPrefix = null;
-        for( int i=0; i<args.length; i++ )
+
+        if (outputPrefix == null)
         {
-            switch (args[i])
-            {
-                case PASSWORD:
-                    i++;
-                    if (i >= args.length)
-                    {
-                        usage();
-                    }
-                    password = args[i];
-                    break;
-                case SPLIT:
-                    i++;
-                    if (i >= args.length)
-                    {
-                        usage();
-                    }
-                    split = args[i];
-                    break;
-                case START_PAGE:
-                    i++;
-                    if (i >= args.length)
-                    {
-                        usage();
-                    }
-                    startPage = args[i];
-                    break;
-                case END_PAGE:
-                    i++;
-                    if (i >= args.length)
-                    {
-                        usage();
-                    }
-                    endPage = args[i];
-                    break;
-                case OUTPUT_PREFIX:
-                    i++;
-                    outputPrefix = args[i];
-                    break;
-                default:
-                    if (pdfFile == null)
-                    {
-                        pdfFile = args[i];
-                    }
-                    break;
-            }
+            outputPrefix = FilenameUtils.getBaseName(infile.getAbsolutePath());
         }
 
-        if( pdfFile == null )
+        List<PDDocument> documents = null;
+
+        try (PDDocument document = Loader.loadPDF(infile, password))
         {
-            usage();
-        }
-        else
-        {          
-            if (outputPrefix == null)
+            int numberOfPages = document.getNumberOfPages();
+            boolean startEndPageSet = false;
+            if (startPage != -1)
             {
-                outputPrefix = pdfFile.substring(0, pdfFile.lastIndexOf('.'));
-            }
-            PDDocument document = null;
-            List<PDDocument> documents = null;
-            try
-            {
-                document = Loader.loadPDF(new File(pdfFile), password);
-
-                int numberOfPages = document.getNumberOfPages();
-                boolean startEndPageSet = false;
-                if (startPage != null)
-                {
-                    splitter.setStartPage(Integer.parseInt( startPage ));
-                    startEndPageSet = true;
-                    if (split == null)
-                    {
-                        splitter.setSplitAtPage(numberOfPages);
-                    }
-                }
-                if (endPage != null)
+                splitter.setStartPage(startPage);
+                startEndPageSet = true;
+                if (split == -1)
                 {
-                    splitter.setEndPage(Integer.parseInt( endPage ));
-                    startEndPageSet = true;
-                    if (split == null)
-                    {
-                        splitter.setSplitAtPage(Integer.parseInt( endPage ));
-                    }
+                    splitter.setSplitAtPage(numberOfPages);
                 }
-                if (split != null)
-                {
-                    splitter.setSplitAtPage( Integer.parseInt( split ) );
-                }
-                else 
-                {
-                    if (!startEndPageSet)
-                    {
-                        splitter.setSplitAtPage(1);
-                    }
-                }
-                    
-                documents = splitter.split( document );
-                for( int i=0; i<documents.size(); i++ )
+            }
+            if (endPage != -1)
+            {
+                splitter.setEndPage(endPage);
+                startEndPageSet = true;
+                if (split == -1)
                 {
-                    try (PDDocument doc = documents.get(i))
-                    {
-                        doc.save(outputPrefix + "-" + (i + 1) + ".pdf");
-                    }
+                    splitter.setSplitAtPage(endPage);
                 }
-
             }
-            finally
+            if (split != -1)
+            {
+                splitter.setSplitAtPage(split);
+            }
+            else 
             {
-                if( document != null )
+                if (!startEndPageSet)
                 {
-                    document.close();
+                    splitter.setSplitAtPage(1);
                 }
-                for( int i=0; documents != null && i<documents.size(); i++ )
+            }
+                
+            documents = splitter.split( document );
+            for( int i=0; i<documents.size(); i++ )
+            {
+                try (PDDocument doc = documents.get(i))
                 {
-                    PDDocument doc = documents.get(i);
-                    doc.close();
+                    doc.save(outputPrefix + "-" + (i + 1) + ".pdf");
                 }
             }
         }
-    }
-
-    /**
-     * This will print the usage requirements and exit.
-     */
-    private static void usage()
-    {
-        String message = "Usage: java -jar pdfbox-app-x.y.z.jar PDFSplit [options] <inputfile>\n"
-                + "\nOptions:\n"
-                + "  -password  <password>  : Password to decrypt document\n"
-                + "  -split     <integer>   : split after this many pages (default 1, if startPage and endPage are unset)\n"
-                + "  -startPage <integer>   : start page\n"
-                + "  -endPage   <integer>   : end page\n"
-                + "  -outputPrefix <prefix> : Filename prefix for split files\n"
-                + "  <inputfile>            : The PDF document to use\n";
-        
-        System.err.println(message);
-        System.exit( 1 );
+        catch (IOException ioe)
+        {
+            SYSERR.println( "Error splitting document: " + ioe.getMessage());
+            return 4;
+        }
+        finally
+        {
+            for( int i=0; documents != null && i<documents.size(); i++ )
+            {
+                PDDocument doc = documents.get(i);
+                IOUtils.closeQuietly(doc);
+            }
+        }
+        return 0;
     }
 }