Example usage for com.lowagie.text.pdf SimpleBookmark eliminatePages

List of usage examples for com.lowagie.text.pdf SimpleBookmark eliminatePages

Introduction

In this page you can find the example usage for com.lowagie.text.pdf SimpleBookmark eliminatePages.

Prototype

public static void eliminatePages(List list, int pageRange[]) 

Source Link

Document

Removes the bookmark entries for a number of page ranges.

Usage

From source file:it.pdfsam.console.tools.pdf.PdfConcat.java

License:Open Source License

/**
 * Execute the concat command. On error an exception is thrown.
 * @throws ConcatException/*from w  w  w  .  j a v  a 2  s  .  co  m*/
 */
public void execute() throws ConcatException {
    try {
        percentageChanged(0, 0);
        out_message = "";
        String file_name;
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document pdf_document = null;
        PdfConcatenator pdf_writer = null;
        int total_processed_pages = 0;
        String[] page_selection = u_string.split(":");
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader;
        for (Iterator f_list_itr = f_list.iterator(); f_list_itr.hasNext();) {
            String current_p_selection;
            //get page selection. If arrayoutofbounds default behaviour is "all" 
            try {
                current_p_selection = page_selection[f].toLowerCase();
                if (current_p_selection.equals(""))
                    current_p_selection = "all";
            } catch (Exception e) {
                current_p_selection = "all";
            }
            //validation
            if (!(Pattern.compile("([0-9]+[-][0-9]+)|(all)", Pattern.CASE_INSENSITIVE)
                    .matcher(current_p_selection).matches())) {
                String errorMsg = "";
                try {
                    tmp_o_file.delete();
                } catch (Exception e) {
                    errorMsg = " Unable to delete temporary file.";
                }
                throw new ConcatException(
                        "ValidationError: Syntax error on " + current_p_selection + "." + errorMsg);
            }
            file_name = f_list_itr.next().toString();
            //reader creation
            pdf_reader = new PdfReader(new RandomAccessFileOrArray(file_name), null);
            pdf_reader.consolidateNamedDestinations();
            int pdf_number_of_pages = pdf_reader.getNumberOfPages();
            //default behaviour
            int start = 0;
            int end_page = pdf_number_of_pages;
            if (!(current_p_selection.equals("all"))) {
                boolean valid = true;
                String exceptionMsg = "";
                String[] limits = current_p_selection.split("-");
                try {
                    start = Integer.parseInt(limits[0]);
                    end_page = Integer.parseInt(limits[1]);
                } catch (Exception ex) {
                    valid = false;
                    exceptionMsg += "ValidationError: Syntax error on " + current_p_selection + ".";
                    try {
                        tmp_o_file.delete();
                    } catch (Exception e) {
                        exceptionMsg += " Unable to delete temporary file.";
                    }
                }
                if (valid) {
                    //validation
                    if (start < 0) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " must be positive in "
                                + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (end_page > pdf_number_of_pages) {
                        valid = false;
                        exceptionMsg = "ValidationError: Cannot merge at page " + end_page + ". No such page.";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    } else if (start > end_page) {
                        valid = false;
                        exceptionMsg = "ValidationError: Syntax error. " + (start) + " is bigger than "
                                + end_page + " in " + current_p_selection + ".";
                        try {
                            tmp_o_file.delete();
                        } catch (Exception e) {
                            exceptionMsg += " Unable to delete temporary file.";
                        }
                    }
                }
                if (!valid) {
                    throw new ConcatException(exceptionMsg);
                }
            }
            List bookmarks = SimpleBookmark.getBookmark(pdf_reader);
            if (bookmarks != null) {
                //if the end page is not the end of the doc, delete bookmarks after it
                if (end_page < pdf_number_of_pages) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { end_page + 1, pdf_number_of_pages });
                }
                // if start page isn't the first page of the document, delete bookmarks before it
                if (start > 0) {
                    SimpleBookmark.eliminatePages(bookmarks, new int[] { 1, start });
                    //bookmarks references must be taken back
                    SimpleBookmark.shiftPageNumbers(bookmarks, -start, null);
                }
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += (end_page - start);
            out_message += LogFormatter.formatMessage(file_name + ": " + end_page + " pages-\n");
            if (f == 0) {
                if (copyfields_boolean) {
                    // step 1: we create a writer 
                    pdf_writer = new PdfCopyFieldsConcatenator(new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    HashMap meta = pdf_reader.getInfo();
                    meta.put("Creator", MainConsole.CREATOR);
                } else {
                    // step 1: creation of a document-object
                    pdf_document = new Document(pdf_reader.getPageSizeWithRotation(1));
                    // step 2: we create a writer that listens to the document
                    pdf_writer = new PdfSimpleConcatenator(pdf_document, new FileOutputStream(tmp_o_file),
                            compressed_boolean);
                    // step 3: we open the document
                    MainConsole.setDocumentCreator(pdf_document);
                    pdf_document.open();
                }
                out_message += LogFormatter.formatMessage("Temporary file created-\n");
            }
            // step 4: we add content
            pdf_reader.selectPages(start + "-" + end_page);
            pdf_writer.addDocument(pdf_reader);
            //fix 03/07
            //pdf_reader = null;
            pdf_reader.close();
            pdf_writer.freeReader(pdf_reader);
            total_processed_pages += end_page - start + 1;
            out_message += LogFormatter.formatMessage((end_page - start) + " pages processed correctly-\n");
            f++;
            try {
                percentageChanged((f * 100) / f_list.size(), (end_page - start));
            } catch (RuntimeException re) {
                out_message += LogFormatter.formatMessage("RuntimeException: " + re.getMessage() + "\n");
            }
        }
        if (master.size() > 0) {
            pdf_writer.setOutlines(master);
        }
        out_message += LogFormatter.formatMessage("Total processed pages: " + total_processed_pages + "-\n");
        // step 5: we close the document
        if (pdf_document != null) {
            pdf_document.close();
        }
        pdf_writer.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
    } catch (Exception e) {
        throw new ConcatException(e);
    } finally {
        workCompleted();
    }
}

From source file:it.pdfsam.console.tools.pdf.PdfSplit.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_SPLIT
 * /* w  w w.j a v  a  2s .  co m*/
 * @param pdf_reader
 *                pdfreader of the original pdf document
 * @param out_files_name
 *                output file name
 * @throws Exception
 */
private void doSplitSplit(PdfReader pdf_reader) throws Exception {
    String[] limits = snumber_page.split("-");
    Arrays.sort(limits, new StrNumComparator());
    // limits list validation end clean
    LinkedList limits_list = validateSplitLimits(limits, n);
    if (limits_list == null) {
        throw new SplitException("PageNumberError: Cannot find page limits, please check input value.");
    }
    if (limits_list.isEmpty()) {
        throw new SplitException("PageNumberError: Cannot find page limits, please check input value.");
    }
    // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START
    // BOOKMARKS
    Iterator itr = limits_list.iterator();
    int current_page;
    int relative_current_page = 0;
    int end_page = n;
    int start_page = 1;
    Document current_document = new Document(pdf_reader.getPageSizeWithRotation(1));
    PdfCopy pdf_writer = null;
    PdfImportedPage imported_page;
    File tmp_o_file = null;
    File o_file = null;
    if (itr.hasNext()) {
        end_page = Integer.parseInt((String) itr.next());
    }
    for (current_page = 1; current_page <= n; current_page++) {
        relative_current_page++;
        //check if i've to read one more page or to open a new doc
        if (relative_current_page == 1) {
            tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_dir);
            o_file = new File(o_dir, prefixParser.generateFileName(file_number_formatter.format(current_page)));
            start_page = current_page;
            // step 1: creation of a document-object
            current_document = new Document(pdf_reader.getPageSizeWithRotation(current_page));
            // step 2: we create a writer that listens to the document
            pdf_writer = new PdfCopy(current_document, new FileOutputStream(tmp_o_file));
            if (compressed_boolean) {
                pdf_writer.setFullCompression();
            }
            MainConsole.setDocumentCreator(current_document);
            // step 3: we open the document
            current_document.open();
        }
        imported_page = pdf_writer.getImportedPage(pdf_reader, current_page);
        pdf_writer.addPage(imported_page);
        // if it's time to close the document
        if (current_page == end_page) {
            out_message += LogFormatter.formatMessage(
                    "Temporary document " + tmp_o_file.getName() + " done, now adding bookmarks...\n");
            //manage bookmarks
            ArrayList master = new ArrayList();
            List this_book = SimpleBookmark.getBookmark(pdf_reader);
            if (this_book != null) {
                //ArrayList this_book = new ArrayList(bookmarks);
                SimpleBookmark.eliminatePages(this_book, new int[] { end_page + 1, n });
                if (start_page > 1) {
                    SimpleBookmark.eliminatePages(this_book, new int[] { 1, start_page - 1 });
                    SimpleBookmark.shiftPageNumbers(this_book, -(start_page - 1), null);
                }
                master.addAll(this_book);
                pdf_writer.setOutlines(master);
            }
            relative_current_page = 0;
            current_document.close();
            renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
            end_page = (itr.hasNext()) ? Integer.parseInt((String) itr.next()) : n;
        }
        percentageChanged((current_page * 100) / n);
    }
    out_message += LogFormatter.formatMessage("Split " + split_type + " done.\n");
}

From source file:org.pdfsam.console.business.pdf.bookmarks.BookmarksProcessor.java

License:Open Source License

/**
 * Process the bookmarks returning a view of the whole list that contains only pages comprehended among the two limits (included) with page number shifted if necessary.
 * //w w w.j  a  v  a2s.c  om
 * @param startPage
 *            start page number
 * @param endPage
 *            end page number
 * @param pageOffset
 *            if not 0 pages are shifted of the given amount
 * @return
 */
public List processBookmarks(int startPage, int endPage, int pageOffset) {
    List books = null;
    if (bookmarks != null) {
        books = getCopyBookmarks(bookmarks);
        if (endPage < numberOfPages) {
            SimpleBookmark.eliminatePages(books, new int[] { endPage + 1, numberOfPages });
        }
        if (startPage > 1) {
            SimpleBookmark.eliminatePages(books, new int[] { 1, startPage - 1 });
            SimpleBookmark.shiftPageNumbers(books, -(startPage - 1), null);
        }
        if (pageOffset != 0) {
            SimpleBookmark.shiftPageNumbers(books, pageOffset, null);
        }
    }
    return books;
}

From source file:org.sejda.impl.itext.component.ITextOutlineSubsetProvider.java

License:Apache License

public List<Map<String, Object>> getOutlineUntillPageWithOffset(int endPage, int offset) throws TaskException {
    if (startPage < 0 || startPage > endPage) {
        throw new TaskException(
                "Unable to process document bookmarks: start page is negative or higher then end page.");
    }/*from  w  w w  .  j a  v a 2s.co  m*/
    if (bookmarks.isEmpty()) {
        return Collections.emptyList();
    }
    List<Map<String, Object>> books = getDeepCopyBookmarks(bookmarks);
    if (endPage < totalNumberOfPages) {
        SimpleBookmark.eliminatePages(books, new int[] { endPage + 1, totalNumberOfPages });
    }
    if (startPage > 1) {
        SimpleBookmark.eliminatePages(books, new int[] { 1, startPage - 1 });
        SimpleBookmark.shiftPageNumbers(books, -(startPage - 1), null);
    }
    if (offset != 0) {
        SimpleBookmark.shiftPageNumbers(books, offset, null);
    }
    return books;
}