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

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

Introduction

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

Prototype

public static List getBookmark(PdfReader reader) 

Source Link

Document

Gets a List with the bookmarks.

Usage

From source file:org.lucee.extension.pdf.tag.PDF.java

License:Open Source License

private void doActionRemoveWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "removeWatermark", "source", source);

    if (destination != null && destination.exists() && !overwrite)
        throw engine.getExceptionUtil()
                .createApplicationException("destination file [" + destination + "] already exists");

    BufferedImage bi = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics();
    g.setBackground(Color.BLACK);
    g.clearRect(0, 0, 1, 1);// ww w.j  av a2  s .com

    Image img = Image.getInstance(bi, null, false);
    img.setAbsolutePosition(1, 1);

    PDFStruct doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();

    boolean destIsSource = destination != null && doc.getResource() != null
            && destination.equals(doc.getResource());
    java.util.List bookmarks = SimpleBookmark.getBookmark(reader);
    ArrayList master = new ArrayList();
    if (bookmarks != null)
        master.addAll(bookmarks);

    // output
    OutputStream os = null;
    if (!Util.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {
        int len = reader.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(reader, os);

        Set _pages = doc.getPages();
        for (int i = 1; i <= len; i++) {
            if (_pages != null && !_pages.contains(Integer.valueOf(i)))
                continue;
            PdfContentByte cb = foreground ? stamp.getOverContent(i) : stamp.getUnderContent(i);
            PdfGState gs1 = new PdfGState();
            gs1.setFillOpacity(0);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        Util.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()),
                        destination, true);// MUST overwrite
            if (!Util.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:org.lucee.extension.pdf.util.PDFUtil.java

License:Open Source License

/**
 * @param docs/*from  ww  w. j  a va  2s  .  c  om*/
 * @param os
 * @param removePages
 *            if true, pages defined in PDFDocument will be removed, otherwise all other pages will be removed
 * @param version
 * @throws PageException
 * @throws IOException
 * @throws DocumentException
 */
public static void concat(PDFStruct[] docs, OutputStream os, boolean keepBookmark, boolean removePages,
        boolean stopOnError, char version) throws PageException, IOException, DocumentException {
    Document document = null;
    PdfCopy writer = null;
    PdfReader reader;
    Set pages;
    boolean isInit = false;
    PdfImportedPage page;
    try {
        int pageOffset = 0;
        ArrayList master = new ArrayList();

        for (int i = 0; i < docs.length; i++) {
            // we create a reader for a certain document
            pages = docs[i].getPages();
            try {
                reader = docs[i].getPdfReader();
            } catch (Throwable t) {
                if (t instanceof ThreadDeath)
                    throw (ThreadDeath) t;
                if (!stopOnError)
                    continue;
                throw CFMLEngineFactory.getInstance().getCastUtil().toPageException(t);
            }
            reader.consolidateNamedDestinations();

            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = keepBookmark ? SimpleBookmark.getBookmark(reader) : null;
            if (bookmarks != null) {
                removeBookmarks(bookmarks, pages, removePages);
                if (pageOffset != 0)
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                master.addAll(bookmarks);
            }

            if (!isInit) {
                isInit = true;
                document = new Document(reader.getPageSizeWithRotation(1));
                writer = new PdfCopy(document, os);

                if (version != 0)
                    writer.setPdfVersion(version);

                document.open();
            }

            for (int y = 1; y <= n; y++) {
                if (pages != null && removePages == pages.contains(Integer.valueOf(y))) {
                    continue;
                }
                pageOffset++;
                page = writer.getImportedPage(reader, y);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);
        }
        if (master.size() > 0)
            writer.setOutlines(master);

    } finally {
        CFMLEngineFactory.getInstance().getIOUtil().closeSilent(document);
    }
}

From source file:org.lucee.extension.pdf.util.PDFUtil.java

License:Open Source License

public static void encrypt(PDFStruct doc, OutputStream os, String newUserPassword, String newOwnerPassword,
        int permissions, int encryption) throws PageException, DocumentException, IOException {
    byte[] user = newUserPassword == null ? null : newUserPassword.getBytes();
    byte[] owner = newOwnerPassword == null ? null : newOwnerPassword.getBytes();

    PdfReader pr = doc.getPdfReader();// w  w  w  . j a va2s. c  om
    List bookmarks = SimpleBookmark.getBookmark(pr);
    int n = pr.getNumberOfPages();

    Document document = new Document(pr.getPageSizeWithRotation(1));
    PdfCopy writer = new PdfCopy(document, os);
    if (encryption != ENCRYPT_NONE)
        writer.setEncryption(user, owner, permissions, encryption);
    document.open();

    PdfImportedPage page;
    for (int i = 1; i <= n; i++) {
        page = writer.getImportedPage(pr, i);
        writer.addPage(page);
    }
    PRAcroForm form = pr.getAcroForm();
    if (form != null)
        writer.copyAcroForm(pr);
    if (bookmarks != null)
        writer.setOutlines(bookmarks);
    document.close();
}

From source file:org.pdfsam.console.business.pdf.handlers.ConcatCmdExecutor.java

License:Open Source License

public void execute(AbstractParsedCommand parsedCommand) throws ConsoleException {
    if ((parsedCommand != null) && (parsedCommand instanceof ConcatParsedCommand)) {
        ConcatParsedCommand inputCommand = (ConcatParsedCommand) parsedCommand;
        setPercentageOfWorkDone(0);//from   w w w  . j  a va2 s. c  o m
        // 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 = PdfUtility.readerFor(fileList[i]);
                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 {
            setWorkCompleted();
        }
    } else {
        throw new ConsoleException(ConsoleException.ERR_BAD_COMMAND);
    }

}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_BLEVEL
 * //from  w ww.j a  v  a 2  s . com
 * @param inputCommand
 * @param bookmarksTable
 *            bookmarks table. It's populated only when splitting by bookmarks. If null or empty it's ignored
 * @throws Exception
 */
private void executeSplit(SplitParsedCommand inputCommand, Hashtable bookmarksTable) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();

    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");

    Integer[] limits = inputCommand.getSplitPageNumbers();
    // limits list validation end clean
    TreeSet limitsList = validateSplitLimits(limits, n);
    if (limitsList.isEmpty()) {
        throw new SplitException(SplitException.ERR_NO_PAGE_LIMITS);
    }

    // HERE I'M SURE I'VE A LIMIT LIST WITH VALUES, I CAN START BOOKMARKS
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    int relativeCurrentPage = 0;
    int endPage = n;
    int startPage = 1;
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;

    Iterator itr = limitsList.iterator();
    if (itr.hasNext()) {
        endPage = ((Integer) itr.next()).intValue();
    }
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // check if i've to read one more page or to open a new doc
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            String bookmark = null;
            if (bookmarksTable != null && bookmarksTable.size() > 0) {
                bookmark = (String) bookmarksTable.get(new Integer(currentPage));
            }
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, bookmark);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            startPage = currentPage;
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));

            pdfWriter = new PdfSmartCopy(currentDocument, new FileOutputStream(tmpFile));

            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);

        // if it's time to close the document
        if (currentPage == endPage) {
            LOG.info("Temporary document " + tmpFile.getName() + " done, now adding bookmarks...");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, endPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
            endPage = (itr.hasNext()) ? ((Integer) itr.next()).intValue() : n;
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_BLEVEL
 * //from w w  w  . j  a  v a  2  s .  co  m
 * @param inputCommand
 * @throws Exception
 */
private void executeBookmarksSplit(SplitParsedCommand inputCommand) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    int bLevel = inputCommand.getBookmarksLevel().intValue();
    Hashtable bookmarksTable = new Hashtable();
    if (bLevel > 0) {
        pdfReader.removeUnusedObjects();
        pdfReader.consolidateNamedDestinations();
        List bookmarks = SimpleBookmark.getBookmark(pdfReader);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        SimpleBookmark.exportToXML(bookmarks, out, "UTF-8", false);
        ByteArrayInputStream input = new ByteArrayInputStream(out.toByteArray());
        int maxDepth = PdfUtility.getMaxBookmarksDepth(input);
        input.reset();
        if (bLevel <= maxDepth) {
            SAXReader reader = new SAXReader();
            org.dom4j.Document document = reader.read(input);
            // head node
            String headBookmarkXQuery = "/Bookmark/Title[@Action=\"GoTo\"]";
            Node headNode = document.selectSingleNode(headBookmarkXQuery);
            if (headNode != null && headNode.getText() != null && headNode.getText().trim().length() > 0) {
                bookmarksTable.put(new Integer(1), headNode.getText().trim());
            }
            // bLevel nodes
            StringBuffer buffer = new StringBuffer("/Bookmark");
            for (int i = 0; i < bLevel; i++) {
                buffer.append("/Title[@Action=\"GoTo\"]");
            }
            String xQuery = buffer.toString();
            List nodes = document.selectNodes(xQuery);
            input.close();
            input = null;
            if (nodes != null && nodes.size() > 0) {
                LinkedHashSet pageSet = new LinkedHashSet(nodes.size());
                for (Iterator nodeIter = nodes.iterator(); nodeIter.hasNext();) {
                    Node currentNode = (Node) nodeIter.next();
                    Node pageAttribute = currentNode.selectSingleNode("@Page");
                    if (pageAttribute != null && pageAttribute.getText().length() > 0) {
                        String attribute = pageAttribute.getText();
                        int blankIndex = attribute.indexOf(' ');
                        if (blankIndex > 0) {
                            Integer currentNumber = new Integer(attribute.substring(0, blankIndex));
                            String bookmarkText = currentNode.getText().trim();
                            // fix #2789963
                            if (currentNumber.intValue() > 0) {
                                // bookmarks regexp matching if any
                                if (StringUtils.isBlank(inputCommand.getBookmarkRegexp())
                                        || bookmarkText.matches(inputCommand.getBookmarkRegexp())) {
                                    // to split just before the given page
                                    if ((currentNumber.intValue()) > 1) {
                                        pageSet.add(new Integer(currentNumber.intValue() - 1));
                                    }
                                    if (StringUtils.isNotBlank(bookmarkText)) {
                                        bookmarksTable.put(currentNumber, bookmarkText.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (pageSet.size() > 0) {
                    if (StringUtils.isBlank(inputCommand.getBookmarkRegexp())) {
                        LOG.debug("Found " + pageSet.size() + " destination pages at level " + bLevel);
                    } else {
                        LOG.debug("Found " + pageSet.size() + " destination pages at level " + bLevel
                                + " matching '" + inputCommand.getBookmarkRegexp() + "'");
                    }
                    inputCommand.setSplitPageNumbers((Integer[]) pageSet.toArray(new Integer[pageSet.size()]));
                } else {
                    throw new SplitException(SplitException.ERR_BLEVEL_NO_DEST, new String[] { "" + bLevel });
                }
            } else {
                throw new SplitException(SplitException.ERR_BLEVEL, new String[] { "" + bLevel });
            }
        } else {
            input.close();
            pdfReader.close();
            throw new SplitException(SplitException.ERR_BLEVEL_OUTOFBOUNDS,
                    new String[] { "" + bLevel, "" + maxDepth });

        }
    } else {
        pdfReader.close();
        throw new SplitException(SplitException.ERR_NOT_VALID_BLEVEL, new String[] { "" + bLevel });
    }
    pdfReader.close();
    executeSplit(inputCommand, bookmarksTable);
}

From source file:org.pdfsam.console.business.pdf.handlers.SplitCmdExecutor.java

License:Open Source License

/**
 * Execute the split of a pdf document when split type is S_SIZE
 * //from  w w  w. j a  v  a2s.c om
 * @param inputCommand
 * @throws Exception
 */
private void executeSizeSplit(SplitParsedCommand inputCommand) throws Exception {
    pdfReader = PdfUtility.readerFor(inputCommand.getInputFile());
    pdfReader.removeUnusedObjects();
    pdfReader.consolidateNamedDestinations();
    int n = pdfReader.getNumberOfPages();
    BookmarksProcessor bookmarkProcessor = new BookmarksProcessor(SimpleBookmark.getBookmark(pdfReader), n);
    int fileNum = 0;
    LOG.info("Found " + n + " pages in input pdf document.");
    int currentPage;
    Document currentDocument = new Document(pdfReader.getPageSizeWithRotation(1));
    PdfImportedPage importedPage;
    File tmpFile = null;
    File outFile = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int startPage = 0;
    int relativeCurrentPage = 0;
    for (currentPage = 1; currentPage <= n; currentPage++) {
        relativeCurrentPage++;
        // time to open a new document?
        if (relativeCurrentPage == 1) {
            LOG.debug("Creating a new document.");
            startPage = currentPage;
            fileNum++;
            tmpFile = FileUtility.generateTmpFile(inputCommand.getOutputFile());
            FileNameRequest request = new FileNameRequest(currentPage, fileNum, null);
            outFile = new File(inputCommand.getOutputFile(), prefixParser.generateFileName(request));
            currentDocument = new Document(pdfReader.getPageSizeWithRotation(currentPage));
            baos = new ByteArrayOutputStream();
            pdfWriter = new PdfSmartCopy(currentDocument, baos);
            // set creator
            currentDocument.addCreator(ConsoleServicesFacade.CREATOR);

            setCompressionSettingOnWriter(inputCommand, pdfWriter);
            setPdfVersionSettingOnWriter(inputCommand, pdfWriter, Character.valueOf(pdfReader.getPdfVersion()));

            currentDocument.open();
        }

        importedPage = pdfWriter.getImportedPage(pdfReader, currentPage);
        pdfWriter.addPage(importedPage);
        // if it's time to close the document
        if ((currentPage == n) || ((relativeCurrentPage > 1) && ((baos.size() / relativeCurrentPage)
                * (1 + relativeCurrentPage) > inputCommand.getSplitSize().longValue()))) {
            LOG.debug("Current stream size: " + baos.size() + " bytes.");
            // manage bookmarks
            List bookmarks = bookmarkProcessor.processBookmarks(startPage, currentPage);
            if (bookmarks != null) {
                pdfWriter.setOutlines(bookmarks);
            }
            relativeCurrentPage = 0;
            currentDocument.close();
            FileOutputStream fos = new FileOutputStream(tmpFile);
            baos.writeTo(fos);
            fos.close();
            baos.close();
            LOG.info("Temporary document " + tmpFile.getName() + " done.");
            FileUtility.renameTemporaryFile(tmpFile, outFile, inputCommand.isOverwrite());
            LOG.debug("File " + outFile.getCanonicalPath() + " created.");
        }
        setPercentageOfWorkDone((currentPage * WorkDoneDataModel.MAX_PERGENTAGE) / n);
    }
    pdfReader.close();
    LOG.info("Split " + inputCommand.getSplitType() + " done.");
}

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

License:Apache License

@SuppressWarnings({ "cast", "unchecked" })
public ITextOutlineLevelsHandler(PdfReader reader, String matchingTitleRegEx) {
    reader.consolidateNamedDestinations();
    this.bookmarks = (List<Map<String, Object>>) SimpleBookmark.getBookmark(reader);
    if (isNotBlank(matchingTitleRegEx)) {
        titleMatchingPattern = Pattern.compile(matchingTitleRegEx);
    }//from   ww  w  .  j av  a2s  .  com
}

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

License:Apache License

private List<Object> getBookmarksOrEmpty(PdfReader reader) {
    @SuppressWarnings("unchecked")
    List<Object> documentBookmarks = SimpleBookmark.getBookmark(reader);
    if (documentBookmarks != null) {
        return Collections.unmodifiableList(documentBookmarks);
    }/*from  w w  w.  j a v  a  2  s.  c o m*/
    return Collections.emptyList();
}

From source file:org.silverpeas.core.importexport.control.ImportExport.java

License:Open Source License

/**
 * @param userDetail/*from   ww  w  .  ja  v a2s  .  co  m*/
 * @param itemsToExport
 * @return
 * @throws ImportExportException
 */
public ExportPDFReport processExportPDF(UserDetail userDetail, List<WAAttributeValuePair> itemsToExport,
        NodePK rootPK) throws ImportExportException {
    ExportPDFReport report = new ExportPDFReport();
    report.setDateDebut(new Date());

    PublicationsTypeManager pubTypeManager = getPublicationsTypeManager();

    String fileExportName = generateExportDirName(userDetail, "fusion");
    String tempDir = FileRepositoryManager.getTemporaryPath();

    File fileExportDir = new File(tempDir + fileExportName);
    if (!fileExportDir.exists()) {
        try {
            FileFolderManager.createFolder(fileExportDir);
        } catch (org.silverpeas.core.util.UtilException ex) {
            throw new ImportExportException("ImportExport", "importExport.EX_CANT_CREATE_FOLDER", ex);
        }
    }

    File pdfFileName = new File(tempDir + fileExportName + ".pdf");
    try {
        // cration des rpertoires avec le nom des thmes et des publications
        List<AttachmentDetail> pdfList = pubTypeManager.processPDFExport(report, userDetail, itemsToExport,
                fileExportDir.getPath(), true, rootPK);

        try {
            int pageOffset = 0;
            List master = new ArrayList();
            Document document = null;
            PdfCopy writer = null;

            if (!pdfList.isEmpty()) {
                boolean firstPage = true;
                for (AttachmentDetail attDetail : pdfList) {
                    PdfReader reader = null;
                    try {
                        reader = new PdfReader(
                                fileExportDir.getPath() + File.separatorChar + attDetail.getLogicalName());
                    } catch (IOException ioe) {
                        // Attached file is not physically present on disk, ignore it and log event
                        SilverLogger.getLogger(this).error("Cannot find PDF {0}",
                                new String[] { attDetail.getLogicalName() }, ioe);
                    }
                    if (reader != null) {
                        reader.consolidateNamedDestinations();
                        int nbPages = reader.getNumberOfPages();
                        List bookmarks = SimpleBookmark.getBookmark(reader);
                        if (bookmarks != null) {
                            if (pageOffset != 0) {
                                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                            }
                            master.addAll(bookmarks);
                        }
                        pageOffset += nbPages;

                        if (firstPage) {
                            document = new Document(reader.getPageSizeWithRotation(1));
                            writer = new PdfCopy(document, new FileOutputStream(pdfFileName));
                            document.open();
                            firstPage = false;
                        }

                        for (int i = 1; i <= nbPages; i++) {
                            try {
                                PdfImportedPage page = writer.getImportedPage(reader, i);
                                writer.addPage(page);
                            } catch (Exception e) {
                                // Can't import PDF file, ignore it and log event
                                SilverLogger.getLogger(this).error("Cannot merge PDF {0}",
                                        new String[] { attDetail.getLogicalName() }, e);
                            }
                        }

                        PRAcroForm form = reader.getAcroForm();
                        if (form != null) {
                            writer.copyAcroForm(reader);
                        }
                    }
                }

                if (!master.isEmpty()) {
                    writer.setOutlines(master);
                }
                writer.flush();
                document.close();
            } else {
                return null;
            }

        } catch (DocumentException e) {
            // Impossible de copier le document
            throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e);
        }

    } catch (IOException e) {
        // Pb avec le rpertoire de destination
        throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e);
    }

    report.setPdfFileName(pdfFileName.getName());
    report.setPdfFileSize(pdfFileName.length());
    report.setPdfFilePath(FileServerUtils.getUrlToTempDir(pdfFileName.getName()));

    report.setDateFin(new Date());

    return report;
}