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

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

Introduction

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

Prototype

public void addPage(PdfImportedPage iPage) throws IOException, BadPdfFormatException 

Source Link

Document

Add an imported page to our output

Usage

From source file:eu.mrbussy.pdfsplitter.Splitter.java

License:Open Source License

/**
 * Split the given PDF file into multiple files using pages.
 * //from w w  w.ja  v a 2s  .  c  o m
 * @param filename
 *            - Name of the PDF to split
 * @param useSubFolder
 *            - Use a separate folder to place the files in.
 */
public static void Run(File file, boolean useSubFolder) {
    PdfReader reader = null;
    String format = null;

    if (useSubFolder) {
        format = "%1$s%2$s%4$s"; // Directory format
        try {
            FileUtils.forceMkdir(
                    new File(String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
                            FilenameUtils.getBaseName(file.getAbsolutePath()),
                            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR)));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        format = "%1$s%2$s%4$s%2$s_%%03d.%3$s"; // Directory format + filename
    } else
        format = "%1$s%2$s_%%03d.%3$s";

    String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
            FilenameUtils.getBaseName(file.getAbsolutePath()),
            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR);

    try {
        reader = new PdfReader(new FileInputStream(file));

        if (reader.getNumberOfPages() > 0) {
            for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) {
                System.out.println(String.format(splitFile, pageNum));
                String filename = String.format(splitFile, pageNum);
                Document document = new Document(reader.getPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename));
                document.open();
                // Copy the page from the original
                PdfImportedPage page = writer.getImportedPage(reader, pageNum);
                writer.addPage(page);
                document.close();
                writer.close();
            }
        }
    } catch (Exception ex) {
        // TODO Implement exception handling
        ex.printStackTrace(System.err);
    } finally {
        if (reader != null)
            // Always close the stream
            reader.close();
    }
}

From source file:fenix.planner.pdf.PDFGenerator.java

License:Open Source License

private void addPageNumbers(PdfReader reader, PdfCopy copy) {
    int pageCount = reader.getNumberOfPages();
    PdfImportedPage page;/*from w  ww  .  jav a  2 s.c  om*/
    PdfCopy.PageStamp stamp;

    for (int i = 1; i <= pageCount; ++i) {
        Rectangle rect = reader.getBoxSize(i, "art");
        page = copy.getImportedPage(reader, i);
        stamp = copy.createPageStamp(page);
        // add page numbers
        ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_RIGHT,
                new Phrase(String.format("%d / %d", i, pageCount), footerFont), rect.getRight(),
                rect.getBottom() + 5, 0);
        try {
            stamp.alterContents();
            copy.addPage(page);
        } catch (BadPdfFormatException | IOException ex) {
            throw new PDFGenerationException("Error adding page number to page " + i, ex);
        }
    }
}

From source file:itextblast.ITextBlast.java

public static void splitByPage(String[] args) throws IOException, DocumentException {

    // use one of the previous examples to create a PDF
    // new MovieTemplates().createPdf(MovieTemplates.RESULT);
    // Create a reader; from current existing file
    // Next time pass it from args ..
    PdfReader reader = new PdfReader("./source/imokman.pdf");
    // We'll create as many new PDFs as there are pages
    Document document;//www  . j av a 2 s  .c  om
    PdfCopy copy;
    // loop over all the pages in the original PDF
    int n = reader.getNumberOfPages();
    for (int i = 0; i < n;) {
        // step 1
        document = new Document();
        // step 2
        copy = new PdfCopy(document, new FileOutputStream(String.format(RESULT, ++i)));
        // step 3
        document.open();
        // step 4
        copy.addPage(copy.getImportedPage(reader, i));
        // step 5
        document.close();
    }
    reader.close();
}

From source file:itextblast.ITextBlast.java

private static void copySelectedQuestionPage(int start_page, int end_page, String question_number)
        throws FileNotFoundException, DocumentException, IOException {

    Document document;//w w w . j a  va  2  s . c  om
    PdfCopy copy;
    document = new Document();
    copy = new PdfCopy(document, new FileOutputStream(
            String.format(ITextBlast.working_dir + RESULT, ITextBlast.qa_filename, question_number)));
    document.open();
    for (int i = start_page; i <= end_page; i++) {
        copy.addPage(copy.getImportedPage(ITextBlast.my_reader, i));
    }
    document.close();
}

From source file:mergevoucher.MainJFrame.java

private void deletePages(File file, String str) throws IOException, DocumentException {
    //open the old pdf file and open a blank new one 
    String fullFileName = file.getPath();
    //System.out.println(fullFileName);
    PdfReader reader = new PdfReader(fullFileName);
    Document document = new Document(reader.getPageSizeWithRotation(1));
    String out = fullFileName.replaceFirst(".pdf", "(new).pdf");
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(out));
    document.open();//w  w w  .  jav a 2 s .  co m
    int pdfPageNumber = reader.getNumberOfPages(); //get pdf page number
    //change pageNumber string to int array
    Boolean[] preservePages = getPages(pdfPageNumber, str);
    //copy pages except need delete to new pdf file
    for (int i = 1; i <= pdfPageNumber; i++) {
        //filter not preserve pages 
        if (preservePages[i]) { //if preserve,copy;else bypass
            //String content = PdfTextExtractor.getTextFromPage(reader, i); //?i;
            copy.addPage(copy.getImportedPage(reader, i));
        }
    }
    System.out.println("New pdf file is:" + fullFileName.replaceFirst(".pdf", "(new).pdf"));
    //close files 
    reader.close();
    document.close();
    copy.close();
}

From source file:org.arc42.pdfutil.PdfConcatenizer.java

License:Open Source License

/**
 * concats all files given in sourceFile
 */// ww w .  j a  v a 2s.c o  m
public void concatFiles() {
    Document document = new Document();
    try {
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(targetFileName));
        document.open();
        PdfReader reader;
        int nrOfPagesInCurrentFile;
        for (int i = 0; i < sourceFiles.size(); i++) {
            reader = new PdfReader(sourceFiles.get(i));

            nrOfPagesInCurrentFile = reader.getNumberOfPages();
            for (int page = 0; page < nrOfPagesInCurrentFile;) {
                copy.addPage(copy.getImportedPage(reader, ++page));
            }

            if (evenify && (nrOfPagesInCurrentFile % 2 == 1)) {
                addBlankPage(copy);
            }

        }
        document.close();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Exception: wrong file you gave me, Yoda muttered...", e);
    } catch (BadPdfFormatException e) {
        LOGGER.log(Level.SEVERE, "Exception: Encountered bad pdf format", e);
    } catch (DocumentException e) {
        LOGGER.log(Level.SEVERE, "Exception: Something bad happened to the output document.", e);
    }

}

From source file:org.arc42.pdfutil.PdfConcatenizer.java

License:Open Source License

/**
 * addBlankPage adds an empty page (e.g. "deliberately left blank") to current PdfCopy instance
 * (usually at the end of odd-paged files to achieve "evenification" (even number of
 * pages in every processed file)/*from  w w w. j a v a  2 s.c o m*/
 *
 * @param copy where the blank page is added to
 */
private void addBlankPage(PdfCopy copy) throws DocumentException, IOException {
    copy.addPage(copy.getImportedPage(blankReader, 1));

    // the following lines would add an "EMPTY" page, with NO text on it
    // copy.newPage();
    // copy.addPage(PageSize.A4, 0);

}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

License:Open Source License

/**
 * @param mainFileUrl/* w w w  . ja  v  a 2s .  co  m*/
 *            : PDF file that has to be splitted
 * @param splittedPageSize
 *            : Page size of each splitted files
 */
private static String splitAndSaveChapter(String mainFileUrl, int pageBeginNum, int pageEndNum, String name) {
    try {
        PdfReader reader = new PdfReader(mainFileUrl);

        int splittedPageSize = pageEndNum - pageBeginNum + 1;
        int pageNum = pageBeginNum;

        String chapterUrl = mainFileUrl.substring(0, mainFileUrl.indexOf(DOT_PDF)) + "-" + name + DOT_PDF;

        Document document = new Document(reader.getPageSizeWithRotation(1));

        FileOutputStream fos = new FileOutputStream(chapterUrl);
        PdfCopy writer = new PdfCopy(document, fos);
        Map<String, String> info = reader.getInfo();

        document.open();
        if ((info != null) && (info.get(_AUTHOR) != null)) {
            document.addAuthor(info.get(_AUTHOR));
        }

        document.addTitle(name);

        for (int offset = 0; offset < splittedPageSize && (pageNum + offset) < pageEndNum; offset++) {
            PdfImportedPage page = writer.getImportedPage(reader, pageNum + offset);
            writer.addPage(page);
        }

        document.close();
        writer.close();
        return chapterUrl;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:oscar.dms.IncomingDocUtil.java

License:Open Source License

public static void deletePage(String queueId, String myPdfDir, String myPdfName, String PageNumberToDelete)
        throws Exception {
    long lastModified;
    String filePathName, tempFilePathName;

    tempFilePathName = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator + "T" + myPdfName;
    filePathName = getIncomingDocumentFilePathName(queueId, myPdfDir, myPdfName);

    File f = new File(filePathName);
    lastModified = f.lastModified();/*from   w w  w. j a  v a2s . c o  m*/
    f.setReadOnly();

    String deletePath = getIncomingDocumentDeletedFilePath(queueId, myPdfDir) + File.separator;
    String deletePathFileName = "";
    int index = myPdfName.indexOf(".pdf");

    String myPdfNameF = myPdfName.substring(0, index);
    String myPdfNameExt = myPdfName.substring(index, myPdfName.length());

    PdfReader reader = null;
    Document document = null;
    PdfCopy copy = null;
    PdfCopy deleteCopy = null;

    try {
        reader = new PdfReader(filePathName);
        deletePathFileName = deletePath + myPdfNameF + "d" + PageNumberToDelete + "of"
                + Integer.toString(reader.getNumberOfPages()) + myPdfNameExt;

        document = new Document(reader.getPageSizeWithRotation(1));
        copy = new PdfCopy(document, new FileOutputStream(tempFilePathName));
        deleteCopy = new PdfCopy(document, new FileOutputStream(deletePathFileName));
        document.open();

        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
            if (!(pageNumber == (Integer.parseInt(PageNumberToDelete)))) {
                copy.addPage(copy.getImportedPage(reader, pageNumber));
            } else {
                deleteCopy.addPage(copy.getImportedPage(reader, pageNumber));
            }
        }
    } catch (Exception e) {
        throw (e);
    } finally {
        try {
            if (copy != null) {
                copy.close();
            }
            if (deleteCopy != null) {
                deleteCopy.close();
            }

            if (document != null) {
                document.close();
            }

            if (reader != null) {
                reader.close();
            }

        } catch (Exception e) {
            throw (e);
        }
    }

    boolean success;
    if (!oscar.OscarProperties.getInstance().getBooleanProperty("INCOMINGDOCUMENT_RECYCLEBIN", "true")) {
        File f1 = new File(deletePathFileName);
        success = f1.delete();
        if (!success) {
            throw new Exception("Error in deleting file:" + deletePathFileName);
        }
    }

    success = f.delete();
    if (success) {
        File f1 = new File(tempFilePathName);
        f1.setLastModified(lastModified);
        success = f1.renameTo(new File(filePathName));
        if (!success) {
            throw new Exception("Error in renaming file from:" + tempFilePathName + "to " + filePathName);
        }
    } else {
        throw new Exception("Error in deleting file:" + filePathName);
    }
}

From source file:oscar.dms.IncomingDocUtil.java

License:Open Source License

public static void extractPage(String queueId, String myPdfDir, String myPdfName, String pageNumbersToExtract)
        throws Exception {
    long lastModified;
    String filePathName, tempFilePathName;

    tempFilePathName = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator + "T" + myPdfName;
    filePathName = getIncomingDocumentFilePathName(queueId, myPdfDir, myPdfName);

    File f = new File(filePathName);
    lastModified = f.lastModified();/*from  w  w w. j a v  a 2  s  .c  om*/
    f.setReadOnly();

    String extractPath = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator;
    int index = myPdfName.toLowerCase().indexOf(".pdf");
    String myPdfNameF = myPdfName.substring(0, index);
    String myPdfNameExt = myPdfName.substring(index, myPdfName.length());

    ArrayList<String> extractList = new ArrayList<String>();
    int startPage, endPage;
    boolean cancelExtract = false;

    PdfReader reader = null;
    Document document = null;
    PdfCopy copy = null;
    PdfCopy extractCopy = null;

    try {
        reader = new PdfReader(filePathName);
        extractPath = extractPath + myPdfNameF + "E" + Integer.toString(reader.getNumberOfPages())
                + myPdfNameExt;

        for (int pgIndex = 0; pgIndex <= reader.getNumberOfPages(); pgIndex++) {
            extractList.add(pgIndex, "0");
        }

        String tmpPageNumbersToExtract = pageNumbersToExtract;
        String[] pageList = tmpPageNumbersToExtract.split(",");
        for (int i = 0; i < pageList.length; i++) {
            if (!pageList[i].isEmpty()) {
                String[] rangeList = pageList[i].split("-");
                if (rangeList.length > 2) {
                    cancelExtract = true;
                }
                for (int j = 0; j < rangeList.length; j++) {
                    if (!rangeList[j].matches("^[0-9]+$")) {
                        cancelExtract = true;
                    }
                }
                if (!cancelExtract) {
                    if (rangeList.length == 1) {
                        startPage = Integer.parseInt(rangeList[0], 10);
                        if (startPage > extractList.size() || startPage == 0) {
                            cancelExtract = true;
                        } else {
                            extractList.set(startPage, "1");
                        }
                    } else if (rangeList.length == 2) {
                        startPage = Integer.parseInt(rangeList[0], 10);
                        endPage = Integer.parseInt(rangeList[1], 10);

                        for (int k = startPage; k <= endPage; k++) {

                            if (k > extractList.size() || k == 0) {
                                cancelExtract = true;
                            } else {
                                extractList.set(k, "1");
                            }
                        }
                    }
                }
            }
        }
        if (!cancelExtract) {
            cancelExtract = true;
            for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
                if (!(extractList.get(pageNumber).equals("1"))) {
                    cancelExtract = false;
                }
            }
        }
        if (cancelExtract == true) {
            reader.close();
            throw new Exception(myPdfName + " : Invalid Pages to Extract " + pageNumbersToExtract);
        }

        document = new Document(reader.getPageSizeWithRotation(1));
        copy = new PdfCopy(document, new FileOutputStream(tempFilePathName));
        extractCopy = new PdfCopy(document, new FileOutputStream(extractPath));
        document.open();
        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
            if (!(extractList.get(pageNumber).equals("1"))) {
                copy.addPage(copy.getImportedPage(reader, pageNumber));
            } else {
                extractCopy.addPage(copy.getImportedPage(reader, pageNumber));
            }
        }

    } catch (Exception e) {
        throw (e);
    } finally {
        try {
            if (copy != null) {
                copy.close();
            }
            if (extractCopy != null) {
                extractCopy.close();
            }

            if (document != null) {
                document.close();
            }

            if (reader != null) {
                reader.close();
            }

        } catch (Exception e) {
            throw (e);
        }
    }

    boolean success = f.delete();

    if (success) {
        File f1 = new File(tempFilePathName);
        f1.setLastModified(lastModified);
        success = f1.renameTo(new File(filePathName));
        if (!success) {
            throw new Exception("Error in renaming file from:" + tempFilePathName + "to " + filePathName);
        }

        File f2 = new File(extractPath);
        f2.setLastModified(lastModified);
    } else {
        throw new Exception("Error in deleting file:" + filePathName);
    }
}