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:br.com.nordestefomento.jrimum.utilix.PDFUtil.java

License:Apache License

/**
 * <p>/*  www .  jav  a 2s  .c  om*/
 * Junta varios arquivos pdf em um soh.
 * </p>
 * 
 * @param pdfFiles
 *            Lista de array de bytes
 * 
 * @return Arquivo PDF em forma de byte
 * @since 0.2
 */
@SuppressWarnings("unchecked")
public static byte[] mergeFiles(List<byte[]> pdfFiles) {

    // retorno
    byte[] bytes = null;

    if (isNotNull(pdfFiles) && !pdfFiles.isEmpty()) {

        int pageOffset = 0;
        boolean first = true;

        ArrayList master = null;
        Document document = null;
        PdfCopy writer = null;
        ByteArrayOutputStream byteOS = null;

        try {

            byteOS = new ByteArrayOutputStream();
            master = new ArrayList();

            for (byte[] doc : pdfFiles) {

                if (isNotNull(doc)) {

                    // cria-se um reader para cada documento

                    PdfReader reader = new PdfReader(doc);

                    if (reader.isEncrypted()) {
                        reader = new PdfReader(doc, "".getBytes());
                    }

                    reader.consolidateNamedDestinations();

                    // pega-se o numero total de paginas
                    int n = reader.getNumberOfPages();
                    List bookmarks = SimpleBookmark.getBookmark(reader);

                    if (isNotNull(bookmarks)) {
                        if (pageOffset != 0) {
                            SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                        }
                        master.addAll(bookmarks);
                    }

                    pageOffset += n;

                    if (first) {

                        // passo 1: criar um document-object
                        document = new Document(reader.getPageSizeWithRotation(1));

                        // passo 2: criar um writer que observa o documento
                        writer = new PdfCopy(document, byteOS);
                        document.addAuthor("JRimum Group");
                        document.addSubject("JRimum Merged Document");
                        document.addCreator("JRimum Utilix");

                        // passo 3: abre-se o documento
                        document.open();
                        first = false;
                    }

                    // passo 4: adciona-se o conteudo
                    PdfImportedPage page;
                    for (int i = 0; i < n;) {
                        ++i;
                        page = writer.getImportedPage(reader, i);

                        writer.addPage(page);
                    }
                }
            }

            if (master.size() > 0) {
                writer.setOutlines(master);
            }

            // passo 5: fecha-se o documento
            if (isNotNull(document)) {
                document.close();
            }

            bytes = byteOS.toByteArray();

        } catch (Exception e) {
            LOG.error("", e);
        }
    }

    return bytes;
}

From source file:classroom.filmfestival_c.Movies21.java

@SuppressWarnings("unchecked")
public static void main(String args[]) {
    Movies18.main(args);//from w  w  w  . j  a  v a 2 s  . c o  m
    Movies20.main(args);
    try {
        PdfReader reader1 = new PdfReader(Movies18.RESULT);
        List<Map> list1 = SimpleBookmark.getBookmark(reader1);
        int[] offsets1 = new int[list1.size() + 1];
        int count = 0;
        for (Map<String, String> mark : list1) {
            offsets1[count++] = getPageNumber(mark.get("Page"));
        }
        offsets1[count] = reader1.getNumberOfPages() + 1;
        PdfReader reader2 = new PdfReader(Movies20.RESULT);
        List<Map> list2 = SimpleBookmark.getBookmark(reader2);
        if (list2.size() != list1.size()) {
            throw new DocumentException("The documents don't have the same number of bookmark entries.");
        }
        int[] offsets2 = new int[list2.size() + 1];
        count = 0;
        for (Map<String, String> mark : list2) {
            offsets2[count++] = getPageNumber(mark.get("Page"));
        }
        offsets2[count] = reader2.getNumberOfPages() + 1;
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        document.open();
        for (int i = 0; i < list1.size(); i++) {
            for (int j = offsets1[i]; j < offsets1[i + 1]; j++) {
                copy.addPage(copy.getImportedPage(reader1, j));
            }
            for (int j = offsets2[i]; j < offsets2[i + 1]; j++) {
                copy.addPage(copy.getImportedPage(reader2, j));
            }
        }
        document.close();
    } catch (IOException e) {
        LOGGER.warn("IOException: " + e);
    } catch (DocumentException e) {
        LOGGER.warn("IOException: " + e);
    }
}

From source file:com.benfante.minimark.blo.AssessmentPdfBuilder.java

License:Apache License

/**
 * Build the contatenated PDF for a list of assessments.
 *
 * @param assessments The assessments// www  .j  a  va  2  s.com
 * @param baseUrl The base URL for retrieving images and resource. If null it will not be set.
 * @param locale The locale for producing the document. Id null, the default locale will be used.
 * @return The PDF document.
 */
public byte[] buildPdf(List<AssessmentFilling> assessments, String baseUrl, Locale locale) throws Exception {
    ByteArrayOutputStream pdfos = new ByteArrayOutputStream();
    List master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    PdfOutline rootOutline = null;
    try {
        int f = 0;
        int pageOffset = 0;
        for (AssessmentFilling assessment : assessments) {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(buildPdf(assessment, baseUrl, locale));
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;
            if (f == 0) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, pdfos);
                writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
                // step 3: we open the document
                document.open();
                // initialize rootOutline for assessment bookmarks creation
                PdfContentByte cb = writer.getDirectContent();
                rootOutline = cb.getRootOutline();
            }
            // step 4: we add content
            new PdfOutline(rootOutline, new PdfDestination(PdfDestination.FIT),
                    assessment.getLastName() + " " + assessment.getFirstName());
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null) {
                writer.copyAcroForm(reader);
            }
            f++;
        }
    } finally {
        if (pdfos != null) {
            try {
                pdfos.close();
            } catch (IOException ioe) {
            }
        }
        if (!master.isEmpty()) {
            writer.setOutlines(master);
        }
        // step 5: we close the document
        if (document != null && document.isOpen()) {
            document.close();
        }
    }
    return pdfos.toByteArray();
}

From source file:com.sapienter.jbilling.server.invoice.PaperInvoiceBatchBL.java

License:Open Source License

/**
 * Takes a list of invoices and replaces the individual PDF files for one
 * single PDF in the destination directory.
 * @param destination//w ww  . j  a v a2s.  com
 * @param prefix
 * @param entityId
 * @param invoices
 * @throws PdfFormatException
 * @throws IOException
 */
public void compileInvoiceFiles(String destination, String prefix, Integer entityId, Integer[] invoices)
        throws DocumentException, IOException {

    String filePrefix = Util.getSysProp("base_dir") + "invoices/" + entityId + "-";
    String outFile = destination + prefix + "-batch.pdf";

    int pageOffset = 0;
    ArrayList master = new ArrayList();
    Document document = null;
    PdfCopy writer = null;
    for (int f = 0; f < invoices.length; f++) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(filePrefix + invoices[f] + "-invoice.pdf");
        reader.consolidateNamedDestinations();
        // we retrieve the total number of pages
        int numberOfPages = reader.getNumberOfPages();
        List bookmarks = SimpleBookmark.getBookmark(reader);
        if (bookmarks != null) {
            if (pageOffset != 0)
                SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
            master.addAll(bookmarks);
        }
        pageOffset += numberOfPages;

        if (f == 0) {
            // step 1: creation of a document-object
            document = new Document(reader.getPageSizeWithRotation(1));
            // step 2: we create a writer that listens to the document
            writer = new PdfCopy(document, new FileOutputStream(outFile));
            // step 3: we open the document
            document.open();
        }
        // step 4: we add content
        PdfImportedPage page;
        for (int i = 0; i < numberOfPages;) {
            ++i;
            page = writer.getImportedPage(reader, i);
            writer.addPage(page);
        }
        PRAcroForm form = reader.getAcroForm();
        if (form != null)
            writer.copyAcroForm(reader);

        //release and delete 
        writer.freeReader(reader);
        reader.close();
        File file = new File(filePrefix + invoices[f] + "-invoice.pdf");
        file.delete();
    }
    if (!master.isEmpty())
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null) {
        document.close();
    } else {
        LOG.warn("document == null");
    }

    LOG.debug("PDF batch file is ready " + outFile);
}

From source file:com.servoy.extensions.plugins.pdf_output.PDFProvider.java

License:Open Source License

/**
 * Combine multiple protected PDF docs into one.
 * Note: this function may fail when creating large PDF files due to lack of available heap memory. To compensate, please configure the application server with more heap memory via -Xmx parameter.
 *
 * @sample//from   ww  w. j  a  v  a  2  s  . c  o m
 * pdf_blob_column = combineProtectedPDFDocuments(new Array(pdf_blob1,pdf_blob2,pdf_blob3), new Array(pdf_blob1_pass,pdf_blob2_pass,pdf_blob3_pass));
 *
 * @param pdf_docs_bytearrays  the array of documents to combine
 * @param pdf_docs_passwords an array of passwords to use
 */
public byte[] js_combineProtectedPDFDocuments(Object[] pdf_docs_bytearrays, Object[] pdf_docs_passwords) {
    if (pdf_docs_bytearrays == null || pdf_docs_bytearrays.length == 0)
        return null;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        int pageOffset = 0;
        List master = new ArrayList();
        Document document = null;
        PdfCopy writer = null;
        for (int f = 0; f < pdf_docs_bytearrays.length; f++) {
            if (!(pdf_docs_bytearrays[f] instanceof byte[]))
                continue;
            byte[] pdf_file = (byte[]) pdf_docs_bytearrays[f];

            // we create a reader for a certain document
            byte[] password = null;
            if (pdf_docs_passwords != null && pdf_docs_passwords.length > f && pdf_docs_passwords[f] != null) {
                if (pdf_docs_passwords[f] instanceof String)
                    password = pdf_docs_passwords[f].toString().getBytes();
            }
            PdfReader reader = new PdfReader(pdf_file, password);
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            int n = reader.getNumberOfPages();
            List bookmarks = SimpleBookmark.getBookmark(reader);
            if (bookmarks != null) {
                if (pageOffset != 0) {
                    SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
                }
                master.addAll(bookmarks);
            }
            pageOffset += n;

            if (writer == null) {
                // step 1: creation of a document-object
                document = new Document(reader.getPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, baos);
                // step 3: we open the document
                document.open();
            }

            // step 4: we add content
            PdfImportedPage page;
            for (int i = 0; i < n;) {
                ++i;
                page = writer.getImportedPage(reader, i);
                writer.addPage(page);
            }
            PRAcroForm form = reader.getAcroForm();
            if (form != null)
                writer.copyAcroForm(reader);
        }
        if (writer != null && document != null) {
            if (master.size() > 0)
                writer.setOutlines(master);
            // step 5: we close the document
            document.close();
        }
        return baos.toByteArray();
    } catch (Throwable e) {
        Debug.error(e);
        throw new RuntimeException("Error combinding pdf documents: " + e.getMessage(), e); //$NON-NLS-1$
    }
}

From source file:com.silverpeas.importExport.control.ImportExport.java

License:Open Source License

/**
 * @param userDetail//from w  ww. jav  a2s  .c om
 * @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 = new PublicationsTypeManager();

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

    File fileExportDir = new File(tempDir + fileExportName);
    if (!fileExportDir.exists()) {
        try {
            FileFolderManager.createFolder(fileExportDir);
        } catch (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
                        SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF",
                                "CANT_FIND_PDF_FILE",
                                "PDF file '" + attDetail.getLogicalName() + "' is not present on disk", 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
                                SilverTrace.error("importExport", "PublicationTypeManager.processExportPDF",
                                        "CANT_MERGE_PDF_FILE", "PDF file is " + 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 (BadPdfFormatException e) {
            // Erreur lors de la copie
            throw new ImportExportException("ImportExport", "root.EX_CANT_WRITE_FILE", e);
        } 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;
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFCreator.java

License:Apache License

private List<PDFBookmark> extractBookmarksFromPDF(PdfReader pdfreader, List<PDFBookmark> pDFBookmarks,
        int documentpartnumber) {
    // add Bookmarks
    List<?> list = SimpleBookmark.getBookmark(pdfreader);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (list != null) {
        try {//  w  w w . j  a  v a  2s  . c  o  m
            // TODO: GDZ: Do we really need this XML step here?
            SimpleBookmark.exportToXML(list, baos, "UTF8", false);
            String bms = baos.toString();
            LOGGER.debug(bms);
            // parse the xml, find Title elements
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(bms)));

            Element e = doc.getDocumentElement();
            NodeList nl = e.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                if ((n.getNodeType() == Node.ELEMENT_NODE) && (n.getNodeName().equals("Title"))) {
                    // found the right node, get title and pagenumber
                    PDFBookmark bm = parseTitleNode(n, documentpartnumber);
                    // this is the uppermost bookmark, add it to rootbookmark list
                    pDFBookmarks.add(bm);
                }
            }
        } catch (IOException e) {
            LOGGER.error("IOExeption occured", e);
        } catch (ParserConfigurationException e) {
            LOGGER.error("ParserConfigurationException occured", e);
        } catch (SAXException e) {
            LOGGER.error("SAXException occured", e);
        }
    }
    return pDFBookmarks;
}

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//w ww  . j  a  v a  2 s . com
 */
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
 * //from   w  w w. ja  va  2  s .c  o 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:lucee.runtime.tag.Document.java

License:Open Source License

private void render(OutputStream os, boolean doBookmarks, boolean doHtmlBookmarks)
        throws IOException, PageException, DocumentException {
    byte[] pdf = null;
    // merge multiple docs to 1
    if (documents.size() > 1) {
        PDFDocument[] pdfDocs = new PDFDocument[documents.size()];
        PdfReader[] pdfReaders = new PdfReader[pdfDocs.length];
        Iterator<PDFDocument> it = documents.iterator();
        int index = 0;
        // generate pdf with pd4ml
        while (it.hasNext()) {
            pdfDocs[index] = it.next();/*w  ww  . ja  v a2s .  c om*/
            pdfReaders[index] = new PdfReader(
                    pdfDocs[index].render(getDimension(), unitFactor, pageContext, doHtmlBookmarks));
            index++;
        }

        // collect together
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        com.lowagie.text.Document document = new com.lowagie.text.Document(
                pdfReaders[0].getPageSizeWithRotation(1));
        PdfCopy copy = new PdfCopy(document, baos);
        document.open();
        String name;
        ArrayList bookmarks = doBookmarks ? new ArrayList() : null;
        try {
            int size, totalPage = 0;
            Map parent;
            for (int doc = 0; doc < pdfReaders.length; doc++) {
                size = pdfReaders[doc].getNumberOfPages();

                PdfImportedPage ip;

                // bookmarks
                if (doBookmarks) {
                    name = pdfDocs[doc].getName();
                    if (!StringUtil.isEmpty(name)) {
                        bookmarks.add(parent = PDFUtil.generateGoToBookMark(name, totalPage + 1));
                    } else
                        parent = null;

                    if (doHtmlBookmarks) {
                        java.util.List pageBM = SimpleBookmark.getBookmark(pdfReaders[doc]);
                        if (pageBM != null) {
                            if (totalPage > 0)
                                SimpleBookmark.shiftPageNumbers(pageBM, totalPage, null);
                            if (parent != null)
                                PDFUtil.setChildBookmarks(parent, pageBM);
                            else
                                bookmarks.addAll(pageBM);
                        }
                    }
                }

                totalPage++;
                for (int page = 1; page <= size; page++) {
                    if (page > 1)
                        totalPage++;
                    ip = copy.getImportedPage(pdfReaders[doc], page);

                    //ip.getPdfDocument().setHeader(arg0);
                    //ip.getPdfDocument().setFooter(arg0);
                    copy.addPage(ip);
                }
            }
            if (doBookmarks && !bookmarks.isEmpty())
                copy.setOutlines(bookmarks);
        } finally {
            document.close();
        }
        pdf = baos.toByteArray();
    } else if (documents.size() == 1) {
        pdf = (documents.get(0)).render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    } else {
        pdf = getDocument().render(getDimension(), unitFactor, pageContext, doHtmlBookmarks);
    }

    // permission/encryption
    if (PDFDocument.ENC_NONE != encryption) {
        PdfReader reader = new PdfReader(pdf);
        com.lowagie.text.Document document = new com.lowagie.text.Document(reader.getPageSize(1));
        document.addCreator("Lucee " + Info.getVersionAsString() + " " + Info.getStateAsString());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, baos);
        //PdfWriter writer = PdfWriter.getInstance(document, pdfOut);
        copy.setEncryption(PDFDocument.ENC_128BIT == encryption, userpassword, ownerpassword, permissions);
        document.open();
        int size = reader.getNumberOfPages();
        for (int page = 1; page <= size; page++) {
            copy.addPage(copy.getImportedPage(reader, page));
        }
        document.close();
        pdf = baos.toByteArray();
    }

    // write out
    if (os != null)
        IOUtil.copy(new ByteArrayInputStream(pdf), os, true, false);
    if (!StringUtil.isEmpty(name)) {
        pageContext.setVariable(name, pdf);
    }
}