Example usage for com.itextpdf.text.pdf PdfCopy PdfCopy

List of usage examples for com.itextpdf.text.pdf PdfCopy PdfCopy

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfCopy PdfCopy.

Prototype

public PdfCopy(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Constructor

Usage

From source file:com.photon.phresco.framework.impl.DocumentGeneratorImpl.java

License:Apache License

@Override
public void generate(ApplicationInfo info, File filePath, List<ArtifactGroup> artifacts,
        ServiceManager serviceManager) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method DocumentGeneratorImpl.generate(ProjectInfo info, File filePath)");
    }//from w  w w .  j  av a  2 s  .  c  o  m
    OutputStream os = null, fos = null;
    try {
        if (isDebugEnabled) {
            S_LOGGER.debug("generate() Filepath=" + filePath.getPath());
        }
        String folderPath = filePath.toString() + File.separator + "docs";
        File docsFolder = new File(folderPath);
        if (!docsFolder.exists()) {
            docsFolder.mkdirs();
        }
        if (isDebugEnabled) {
            S_LOGGER.debug("generate() ProjectCode=" + info.getCode());
        }
        String path = folderPath + File.separator + info.getAppDirName() + "_doc.pdf";
        os = new FileOutputStream(new File(path));

        com.itextpdf.text.Document docu = new com.itextpdf.text.Document();

        PdfCopy pdfCopy = new PdfCopy(docu, os);
        docu.open();
        InputStream titleSection = DocumentUtil.getTitleSection(info);
        DocumentUtil.addPages(titleSection, pdfCopy);
        String techId = info.getTechInfo().getId();
        Technology technology = serviceManager.getTechnology(techId);
        if (StringUtils.isNotEmpty(technology.getDescription())) {
            InputStream stringAsPDF = DocumentUtil.getStringAsPDF(technology.getDescription());
            DocumentUtil.addPages(stringAsPDF, pdfCopy);
        }

        //         if (StringUtils.isNotEmpty(technology.getDescription())) {
        //            PdfInput convertToPdf = DocConvertor.convertToPdf(technology
        //                  .getDescription());
        //            if (convertToPdf != null) {
        //               DocumentUtil.addPages(convertToPdf.getInputStream(),
        //                     pdfCopy);
        //            }
        //         } else {
        //         }

        if (CollectionUtils.isNotEmpty(artifacts)) {
            for (ArtifactGroup artifactGroup : artifacts) {
                ArtifactElement artifactDescription = serviceManager
                        .getArtifactDescription(artifactGroup.getId());
                if (artifactDescription != null) {
                    artifactGroup.setDescription(artifactDescription.getDescription());
                }
            }
            DocumentUtil.addPages(artifacts, pdfCopy);
        }

        docu.close();

        //generate index.html
        String indexHtml = DocumentUtil.getIndexHtml(docsFolder);
        File indexPath = new File(docsFolder, "index.html");
        fos = new FileOutputStream(indexPath);
        fos.write(indexHtml.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
        if (isDebugEnabled) {
            S_LOGGER.debug("(The process cannot access the file because it is being used by another process");
        }
        throw new PhrescoException(e);
    } catch (com.itextpdf.text.DocumentException e) {
        e.printStackTrace();
        if (isDebugEnabled) {
            S_LOGGER.debug("(The process cannot access the file because it is being used by another process");
        }
        throw new PhrescoException(e);
    } finally {
        Utility.closeStream(os);
        Utility.closeStream(fos);
    }
}

From source file:com.photon.phresco.service.impl.DocumentGeneratorImpl.java

License:Apache License

@Override
public void generate(ProjectInfo info, File filePath) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method DocumentGeneratorImpl.generate(ProjectInfo info, File filePath)");
    }//from  w w w. ja v  a 2s  .c om
    OutputStream os = null, fos = null;

    try {
        if (isDebugEnabled) {
            S_LOGGER.debug("generate() Filepath=" + filePath.getPath());
        }
        String folderPath = filePath.toString() + File.separator + "docs";
        File docsFolder = new File(folderPath);
        if (!docsFolder.exists()) {
            docsFolder.mkdirs();
        }
        if (isDebugEnabled) {
            S_LOGGER.debug("generate() ProjectCode=" + info.getCode());
        }
        String path = folderPath + File.separator + info.getName() + "_doc.pdf";
        os = new FileOutputStream(new File(path));

        com.itextpdf.text.Document docu = new com.itextpdf.text.Document();

        PdfCopy pdfCopy = new PdfCopy(docu, os);
        docu.open();
        InputStream titleSection = DocumentUtil.getTitleSection(info);
        DocumentUtil.addPages(titleSection, pdfCopy);

        Technology technology = PhrescoServerFactory.getDbManager()
                .getTechnologyDoc(info.getTechnology().getId());
        List<Documentation> technologyDoc = technology.getDocs();
        if (technologyDoc != null) {
            for (Documentation documentation : technologyDoc) {
                if (!StringUtils.isEmpty(documentation.getUrl())) {
                    PdfInput convertToPdf = DocConvertor.convertToPdf(documentation.getUrl());
                    if (convertToPdf != null) {
                        DocumentUtil.addPages(convertToPdf.getInputStream(), pdfCopy);
                    }
                } else {
                    InputStream stringAsPDF = DocumentUtil.getStringAsPDF(documentation.getContent());
                    DocumentUtil.addPages(stringAsPDF, pdfCopy);
                }
            }
        }

        //            Documents documentInfo = repoManager.getDocument(technology.getId(), EntityType.TECHNOLOGY);
        //            if(documentInfo!= null){
        //                List<Document> docs = documentInfo.getDocument();
        //                for (Document document : docs) {
        //                    if(!StringUtils.isEmpty(document.getUrl())){
        //                        PdfInput convertToPdf = DocConvertor.convertToPdf(document.getUrl());
        //                        if(convertToPdf != null) {
        //                            DocumentUtil.addPages(convertToPdf.getInputStream(), pdfCopy);
        //                        }
        //                    } else {
        //                        InputStream stringAsPDF = DocumentUtil.getStringAsPDF(document.getContent());
        //                        DocumentUtil.addPages(stringAsPDF, pdfCopy);
        //                    }
        //                }
        //            }

        List<ModuleGroup> tuples = technology.getModules();
        DocumentUtil.addPages(tuples, pdfCopy, MODULES);

        List<ModuleGroup> libraries = technology.getJsLibraries();
        DocumentUtil.addPages(libraries, pdfCopy, LIB);
        //TODO: need to do for App servers, databases if required.

        docu.close();

        //generate index.html
        String indexHtml = DocumentUtil.getIndexHtml(docsFolder);
        File indexPath = new File(docsFolder, "index.html");
        fos = new FileOutputStream(indexPath);
        fos.write(indexHtml.getBytes());
    } catch (IOException e) {
        if (isDebugEnabled) {
            S_LOGGER.debug("(The process cannot access the file because it is being used by another process");
        }
        throw new PhrescoException(e);
    } catch (com.itextpdf.text.DocumentException e) {
        if (isDebugEnabled) {
            S_LOGGER.debug("(The process cannot access the file because it is being used by another process");
        }
        throw new PhrescoException(e);
    } finally {
        Utility.closeStream(os);
        Utility.closeStream(fos);
    }
}

From source file:com.tommontom.pdfsplitter.PdfCombine.java

public List<File> combine(File folder) throws IOException, DocumentException {
    if (!folder.isDirectory()) {
        throw new IllegalArgumentException("Provided folder is not a directory: " + folder);
    }/*from   w  w w .  ja  v  a2 s .c om*/
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter);

    /*
     * Stores the listing of the files
     */
    List<File> newFileList = new ArrayList<>();
    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }

        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));

        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("\\s");
        if (fileNames.length != 2) {
            throw new RuntimeException("File name format is not in right format");
        }

        String fileNameFirst = fileNames[0];
        String fileNameSecond = fileNames[1];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        String[] fileNameFirstParts = fileNameFirst.split("-");

        // Project num is always the 1st part
        String projectNum = fileNameFirstParts[0];
        if (!projectNum.equals(fileNameFirstParts[0])) {
            throw new RuntimeException("Filename needs to be renamed to the correct format");
        }
        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNameFirstParts[1]);
        secondLotNum = Integer.parseInt(fileNameFirstParts[2]);

        // Determine number of pages by difference of lot numbers

        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf,
        // 16034-212235.pdf, 16034-212236.pdf
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        int mod = pdfFileReader.getNumberOfPages() % 2;
        if (pdfFileReader.equals(mod)) {
            throw new RuntimeException("File is not an even number of pages");
        }
        Document document = new Document();

        /*
         * instantiates a new document to be made
         */
        int numPages = pdfFileReader.getNumberOfPages();
        int p = 0;
        int j = 0;
        // Create a copy of the orignal source file. We will pick specific pages
        // out below
        document.open();
        while (j < numPages) {
            if (p == numPages) {
                break;
            }
            if (j % 2 == 2) {
                j += 1;
            }
            j += 1;
            firstLotNum++;

            // Dynamic filename
            String dynamicFileName = projectNum + "-" + (firstLotNum - 1) + ".pdf";
            document = new Document();
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(folder.getPath() + "\\" + dynamicFileName));
            document.open();
            p += 2;

            // Import pages from original doc
            copy.addPage(copy.getImportedPage(pdfFileReader, j));
            copy.addPage(copy.getImportedPage(pdfFileReader, p));
            document.close();

            // Add to the list of compled file names
            newFileList.add(new File(dynamicFileName));
        }
        System.out.println("Number of Documents Created:" + numPages);
        System.out.println("Number of Documents Created:" + listOfFiles[i]);
    }

    return newFileList;
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplit(String path) throws IOException, DocumentException, InterruptedException {
    // TODO Instead of hard code path, pass in as argument
    File folder = new File(path);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }/*  w  w w .  j a  va 2 s  . co  m*/
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int k = 0;
        int numPages = pdfFileReader.getNumberOfPages();
        // Split on a space '\s'
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = (fileNameWithoutExt); /* Dynamic file name */

            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf"));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            deleteFile[k] = path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf";
            k++;
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();

        }

        System.out.println("Number of Documents Created:" + numPages);
        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitCopy(String path) throws IOException, DocumentException {
    // TODO Instead of hard code path, pass in as argument
    File folder = new File(path);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }//from   www .ja  v a 2  s .c o m
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        String[] fileNameNum = fileNameWithoutExt.split("-");
        int fileNameNumOne = Integer.getInteger(fileNameNum[0]);
        int fileNameNumTwo = Integer.getInteger(fileNameNum[1]);
        int constant = 1;
        int k = 0;
        int numPages = fileNameNumTwo - fileNameNumOne;
        // Split on a space '\s'
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        for (int j = 0; j < numPages + 1; j++) {
            String FileName = (fileNameWithoutExt); /* Dynamic file name */
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf"));
            deleteFile[k] = (path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf");
            k++;
            document.open();
            copy.addPage(
                    copy.getImportedPage(pdfFileReader, constant)); /* Import pages from original document */

            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();
            copy.close();
        }

        System.out.println("Number of Documents Created:" + numPages);
        pdfFileReader.close();
    }

}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitSupplierDoc(String path) throws IOException, DocumentException {
    // TODO Instead of hard code path, pass in as argument
    File folder = new File(path);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }/*from   ww  w  .jav  a2 s .  com*/
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        String[] fileNames = fileNameWithoutExt.split("-");
        /*
         * if (fileNames.length != 2) { throw new RuntimeException("File name format is not in right format"); }
         */

        String fileNameFirst = fileNames[1];
        String fileNameSecond = fileNames[2];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        // Project num is always the 1st part
        String projectNum = fileNames[0];
        if (!projectNum.equals(fileNames[0])) {
            throw new RuntimeException("Filename needs to have a project number");
        }

        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNames[1]);
        secondLotNum = Integer.parseInt(fileNames[2].substring(0, fileNames[2].lastIndexOf(".")));
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        int numPages = secondLotNum - firstLotNum;
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = projectNum + "-" + (firstLotNum) + ".pdf"; /* Dynamic file name */

            firstLotNum++;
            document = new Document(PageSize.LETTER, 0, 0, 0, 0);
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            document.close();
            copy.close();
        }
        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitDrop(File[] files) throws IOException, DocumentException, InterruptedException {
    // TODO Instead of hard code path, pass in as argument
    String path;//  w  w  w.  ja va 2  s .c o m
    if (directoryField.getText().isEmpty() || directoryField.getText().equals(example)) {
        path = files[0].getParent();
    } else {
        path = directoryField.getText();
    }
    File[] listOfFiles = files; /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int numPages = pdfFileReader.getNumberOfPages();
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        int k = 0;
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = fileNameWithoutExt; /* Dynamic file name */

            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf"));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */
            deleteFile[k] += path + "\\" + FileName + "(" + j + ")" + ".pdf";
            k++;
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();
            copy.close();
        }

        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitDropCopy(File[] files) throws IOException, DocumentException {
    // TODO Instead of hard code path, pass in as argument
    String path;//from   w  w  w  . j  a  v a 2s . co  m
    path = files[0].getParent();
    File[] listOfFiles = files; /* Stores the listing of the files */
    System.out.println(directoryField);
    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        String[] fileNameNum = fileNameWithoutExt.split("-");
        int fileNameNumOne = Integer.parseInt(fileNameNum[0]);
        int fileNameNumTwo = Integer.parseInt(fileNameNum[1]);
        int constant = 1;
        int numPages = fileNameNumTwo - fileNameNumOne;
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
        ; /* instantiates a new document to be made */

        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        for (int j = 0; j < numPages + 1; j++) {
            String FileName = fileNameWithoutExt; /* Dynamic file name */
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf"));
            document.open();
            copy.addPage(
                    copy.getImportedPage(pdfFileReader, constant)); /* Import pages from original document */
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();
        }
        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitDropSupplierDoc(File[] files) throws IOException, DocumentException {
    // TODO Instead of hard code path, pass in as argument

    String path;/*from  ww  w  .  ja  va2s  . co m*/
    if (directoryField.getText().isEmpty() || directoryField.getText().equals(example)) {
        path = files[0].getParent();
    } else {
        path = directoryField.getText();
    }
    File[] listOfFiles = files; /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        System.out.println(fileNameWithoutExt);
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("-");

        String fileNameFirst = fileNames[1];
        String fileNameSecond = fileNames[2];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        // Project num is always the 1st part
        String projectNum = fileNames[0];
        if (!projectNum.equals(fileNames[0])) {
            throw new RuntimeException("Filename needs to be renamed to the correct format");
        }

        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNameFirst);
        secondLotNum = Integer.parseInt(fileNameSecond);
        int numPages = secondLotNum - firstLotNum;
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = projectNum + "-" + (firstLotNum) + ".pdf"; /* Dynamic file name */
            firstLotNum++;
            document = new Document(PageSize.LETTER, 0, 0, 0, 0);
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();
        }
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfEven(String path) throws IOException, DocumentException {

    String DEFAULT_PATH = path; // TODO Instead of hard code path, pass in as argument
    File folder = new File(DEFAULT_PATH);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }/*from   ww w.j a va 2 s  . co m*/

        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));

        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("\\s");
        if (fileNames.length != 2) {
            throw new RuntimeException("File name format is not in right format");
        }

        String fileNameFirst = fileNames[0];
        String fileNameSecond = fileNames[1];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        String[] fileNameFirstParts = fileNameFirst.split("-");
        String[] fileNameSecondParts = fileNameSecond.split("-");

        // Project num is always the 1st part
        String projectNum = fileNameFirstParts[0];
        if (!projectNum.equals(fileNameSecondParts[0])) {
            throw new RuntimeException("Filename needs to be renamed to the correct format");
        }
        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNameFirstParts[1]);
        secondLotNum = Integer.parseInt(fileNameSecondParts[1]);

        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        int mod = pdfFileReader.getNumberOfPages() % 2;
        if (pdfFileReader.equals(mod)) {
            throw new RuntimeException("File is not an even number of pages");
        }
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int numPages = secondLotNum - firstLotNum + 1;
        int p = 0;
        int j = 1;
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        while (j < numPages) {
            j++;
            if (j % 2 == 1) {
                j += 1;
            }
            firstLotNum++;
            String FileName = projectNum + "-" + (firstLotNum - 1) + ".pdf"; /* Dynamic file name */

            document = new Document(PageSize.LETTER, 0, 0, 0, 0);
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(DEFAULT_PATH + "//" + FileName));
            if (j == 1) {
                newFileListing = ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n");
            }
            document.open();
            p += 2;
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            copy.addPage(copy.getImportedPage(pdfFileReader, p));
            document.close();

        }
        System.out.println("Number of Documents Created:" + numPages);
        System.out.println("Number of Documents Created:" + listOfFiles[i]);
    }
}