Package org.pdfsam.console.business.dto.commands

Examples of org.pdfsam.console.business.dto.commands.ConcatParsedCommand


    private PdfStamper rotationStamper = null;
    private PdfReader rotationReader = null;

    public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
        if ((parsedCommand != null) && (parsedCommand instanceof ConcatParsedCommand)) {
            ConcatParsedCommand inputCommand = (ConcatParsedCommand) parsedCommand;
            setPercentageOfWorkDone(0);
            // xml or csv parsing
            PdfFile[] fileList = inputCommand.getInputFileList();
            if (fileList == null || !(fileList.length > 0)) {
                File listFile = inputCommand.getInputCvsOrXmlFile();
                if (listFile != null && listFile.exists()) {
                    fileList = parseListFile(listFile);
                } else if (inputCommand.getInputDirectory() != null) {
                    fileList = getPdfFiles(inputCommand.getInputDirectory());
                }
            }
            // no input file found
            if (fileList == null || !(fileList.length > 0)) {
                throw new ConcatException(ConcatException.CMD_NO_INPUT_FILE);
            }

            // init
            int pageOffset = 0;
            ArrayList master = new ArrayList();
            Document pdfDocument = null;
            int totalProcessedPages = 0;

            try {
                String[] pageSelections = inputCommand.getPageSelections();
                File tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
                int length = ArrayUtils.getLength(pageSelections);

                for (int i = 0; i < fileList.length; i++) {

                    String currentPageSelection = ValidationUtility.ALL_STRING;
                    int currentDocumentPages = 0;
                    if (!ArrayUtils.isEmpty(pageSelections) && i <= length) {
                        currentPageSelection = pageSelections[i].toLowerCase();
                    }

                    String[] selectionGroups = StringUtils.split(currentPageSelection, ",");

                    pdfReader = new PdfReader(new RandomAccessFileOrArray(fileList[i].getFile().getAbsolutePath()),
                            fileList[i].getPasswordBytes());
                    pdfReader.removeUnusedObjects();
                    pdfReader.consolidateNamedDestinations();
                    int pdfNumberOfPages = pdfReader.getNumberOfPages();
                    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), pdfNumberOfPages);

                    List boundsList = getBounds(pdfNumberOfPages, selectionGroups);
                    ValidationUtility.assertNotIntersectedBoundsList(boundsList);
                    String boundsString = "";

                    for (Iterator iter = boundsList.iterator(); iter.hasNext();) {
                        Bounds bounds = (Bounds) iter.next();
                        boundsString += (boundsString.length() > 0) ? "," + bounds.toString() : bounds.toString();

                        // bookmarks
                        List bookmarks = bookmarkProcessor.processBookmarks(bounds.getStart(), bounds.getEnd(),
                                pageOffset);
                        if (bookmarks != null) {
                            master.addAll(bookmarks);
                        }
                        int relativeOffset = (bounds.getEnd() - bounds.getStart()) + 1;
                        currentDocumentPages += relativeOffset;
                        pageOffset += relativeOffset;
                    }

                    // add pages
                    LOG.info(fileList[i].getFile().getAbsolutePath() + ": " + currentDocumentPages
                            + " pages to be added.");
                    if (pdfWriter == null) {
                        if (inputCommand.isCopyFields()) {
                            // step 1: we create a writer
                            pdfWriter = new PdfCopyFieldsConcatenator(new FileOutputStream(tmpFile), inputCommand
                                    .isCompress());
                            LOG.debug("PdfCopyFieldsConcatenator created.");
                            // output document version
                            if (inputCommand.getOutputPdfVersion() != null) {
                                pdfWriter.setPdfVersion(inputCommand.getOutputPdfVersion().charValue());
                            }
                            HashMap meta = pdfReader.getInfo();
                            meta.put("Creator", ConsoleServicesFacade.CREATOR);
                        } else {
                            // step 1: creation of a document-object
                            pdfDocument = new Document(pdfReader.getPageSizeWithRotation(1));
                            // step 2: we create a writer that listens to the document
                            pdfWriter = new PdfSimpleConcatenator(pdfDocument, new FileOutputStream(tmpFile),
                                    inputCommand.isCompress());
                            LOG.debug("PdfSimpleConcatenator created.");
                            // output document version
                            if (inputCommand.getOutputPdfVersion() != null) {
                                pdfWriter.setPdfVersion(inputCommand.getOutputPdfVersion().charValue());
                            }
                            // step 3: we open the document
                            pdfDocument.addCreator(ConsoleServicesFacade.CREATOR);
                            pdfDocument.open();
                        }
                    }
                    // step 4: we add content
                    pdfReader.selectPages(boundsString);
                    pdfWriter.addDocument(pdfReader);
                    // fix 03/07
                    // pdfReader = null;
                    pdfReader.close();
                    pdfWriter.freeReader(pdfReader);
                    totalProcessedPages += currentDocumentPages;
                    LOG.info(currentDocumentPages + " pages processed correctly.");
                    setPercentageOfWorkDone(((i + 1) * WorkDoneDataModel.MAX_PERGENTAGE) / fileList.length);
                }
                if (master.size() > 0) {
                    pdfWriter.setOutlines(master);
                }
                LOG.info("Total processed pages: " + totalProcessedPages + ".");
                if (pdfDocument != null) {
                    pdfDocument.close();
                }
                // rotations
                if (inputCommand.getRotations() != null && inputCommand.getRotations().length > 0) {
                    LOG.info("Applying pages rotation.");
                    File rotatedTmpFile = applyRotations(tmpFile, inputCommand);
                    FileUtility.deleteFile(tmpFile);
                    FileUtility.renameTemporaryFile(rotatedTmpFile, inputCommand.getOutputFile(), inputCommand
                            .isOverwrite());
                } else {
                    FileUtility.renameTemporaryFile(tmpFile, inputCommand.getOutputFile(), inputCommand.isOverwrite());
                }
                LOG.debug("File " + inputCommand.getOutputFile().getCanonicalPath() + " created.");
            } catch (ConsoleException consoleException) {
                throw consoleException;
            } catch (Exception e) {
                throw new ConcatException(e);
            } finally {
View Full Code Here


* @author Andrea Vacondio
*/
public class ConcatCmdValidator extends AbstractCmdValidator {
   
  public AbstractParsedCommand validateArguments(CmdLineHandler cmdLineHandler) throws ConsoleException {
    ConcatParsedCommand parsedCommandDTO = new ConcatParsedCommand();
   
    if(cmdLineHandler != null){
      //-o
      FileParam oOption = (FileParam) cmdLineHandler.getOption(ConcatParsedCommand.O_ARG);
      if ((oOption.isSet())){
              File outFile = oOption.getFile();
              //checking extension
              ValidationUtility.assertValidPdfExtension(outFile.getName());
              parsedCommandDTO.setOutputFile(outFile)
          }else{
            throw new ParseException(ParseException.ERR_NO_O);
          }
 
      //-f -l -d
      FileParam lOption = (FileParam) cmdLineHandler.getOption(ConcatParsedCommand.L_ARG);
      PdfFileParam fOption = (PdfFileParam) cmdLineHandler.getOption(ConcatParsedCommand.F_ARG);
      FileParam dOption = (FileParam) cmdLineHandler.getOption(ConcatParsedCommand.D_ARG);
      if(lOption.isSet() || fOption.isSet() || dOption.isSet()){
        if(lOption.isSet() ^ fOption.isSet() ^ dOption.isSet()){
          if(fOption.isSet()){
            //validate file extensions
            for(Iterator fIterator = fOption.getPdfFiles().iterator(); fIterator.hasNext();){
              PdfFile currentFile = (PdfFile) fIterator.next();
                  if (!((currentFile.getFile().getName().toLowerCase().endsWith(PDF_EXTENSION)) && (currentFile.getFile().getName().length()>PDF_EXTENSION.length()))){
                    throw new ParseException(ParseException.ERR_IN_NOT_PDF, new String[]{currentFile.getFile().getPath()});
                  }
                }
            parsedCommandDTO.setInputFileList(FileUtility.getPdfFiles(fOption.getPdfFiles()));
          }else if(lOption.isSet()){
            if(lOption.getFile().getPath().toLowerCase().endsWith(CSV_EXTENSION) || lOption.getFile().getPath().toLowerCase().endsWith(XML_EXTENSION)){
              parsedCommandDTO.setInputCvsOrXmlFile(lOption.getFile());
            }else{
              throw new ParseException(ParseException.ERR_NOT_CSV_OR_XML);
            }
          }else{
            if ((dOption.isSet())){
                    File inputDir = dOption.getFile();
                    ValidationUtility.assertValidDirectory(inputDir);
                    parsedCommandDTO.setInputDirectory(inputDir)
                }
          }
        }else{
          throw new ParseException(ParseException.ERR_BOTH_F_OR_L_OR_D);
        }         
      }else{
        throw new ParseException(ParseException.ERR_NO_F_OR_L_OR_D);
      }
 
      //-u
      StringParam uOption = (StringParam) cmdLineHandler.getOption(ConcatParsedCommand.U_ARG);           
          //if it's set we proceed with validation
          if (uOption.isSet()){
            String[] selections = StringUtils.split(uOption.getValue(), ":");
            String[] trimmedSelection = new String[selections.length];
            for(int i = 0; i<selections.length; i++){
              trimmedSelection[i] = selections[i].trim();
            }
              ValidationUtility.assertValidPageSelectionsArray(trimmedSelection);
              parsedCommandDTO.setPageSelections(trimmedSelection);
          }
 
          //-copyfields
          parsedCommandDTO.setCopyFields(((BooleanParam) cmdLineHandler.getOption(ConcatParsedCommand.COPYFIELDS_ARG)).isTrue());
         
          //-r
          StringParam rOption = (StringParam) cmdLineHandler.getOption(ConcatParsedCommand.R_ARG);
          if(rOption.isSet()){
            PageRotation[] rotations = ValidationUtility.getPagesRotation(rOption.getValue());
            parsedCommandDTO.setRotations(rotations);
          }
    }else{
      throw new ConsoleException(ConsoleException.CMD_LINE_HANDLER_NULL);
    }
    return parsedCommandDTO;
View Full Code Here

TOP

Related Classes of org.pdfsam.console.business.dto.commands.ConcatParsedCommand

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.