Example usage for com.lowagie.text.pdf PdfReader consolidateNamedDestinations

List of usage examples for com.lowagie.text.pdf PdfReader consolidateNamedDestinations

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfReader consolidateNamedDestinations.

Prototype

boolean consolidateNamedDestinations

To view the source code for com.lowagie.text.pdf PdfReader consolidateNamedDestinations.

Click Source Link

Usage

From source file:br.com.nordestefomento.jrimum.utilix.PDFUtil.java

License:Apache License

/**
 * <p>/*  w ww  .  j a  v a  2  s .com*/
 * 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:br.gov.jfrj.itextpdf.Documento.java

License:Open Source License

public static byte[] getDocumento(ExMobil mob, ExMovimentacao mov, boolean completo, boolean estampar,
        String hash, byte[] certificado) throws Exception {
    final ByteArrayOutputStream bo2 = new ByteArrayOutputStream();
    PdfReader reader;
    int n;/*  www.ja  va 2s .  c  o m*/
    int pageOffset = 0;
    ArrayList master = new ArrayList();
    int f = 0;
    Document document = null;
    PdfCopy writer = null;
    int nivelInicial = 0;

    // if (request.getRequestURI().indexOf("/completo/") == -1) {
    // return getPdf(docvia, mov != null ? mov : docvia.getExDocumento(),
    // mov != null ? mov.getNumVia() : docvia.getNumVia(), null,
    // null, request);
    // }

    List<ExArquivoNumerado> ans = mob.filtrarArquivosNumerados(mov, completo);

    if (!completo && !estampar && ans.size() == 1) {
        if (certificado != null) {
            CdService cdService = Service.getCdService();
            return cdService.produzPacoteAssinavel(certificado, null, ans.get(0).getArquivo().getPdf(), true,
                    ExDao.getInstance().getServerDateTime());
        } else if (hash != null) {
            // Calcula o hash do documento
            String alg = hash;
            MessageDigest md = MessageDigest.getInstance(alg);
            md.update(ans.get(0).getArquivo().getPdf());
            return md.digest();
        } else {
            return ans.get(0).getArquivo().getPdf();
        }
    }

    try {
        for (ExArquivoNumerado an : ans) {

            // byte[] ab = getPdf(docvia, an.getArquivo(), an.getNumVia(),
            // an
            // .getPaginaInicial(), an.getPaginaFinal(), request);

            String sigla = mob.getSigla();
            if (an.getArquivo() instanceof ExMovimentacao) {
                ExMovimentacao m = (ExMovimentacao) an.getArquivo();
                if (m.getExTipoMovimentacao().getId() == ExTipoMovimentacao.TIPO_MOVIMENTACAO_JUNTADA)
                    sigla = m.getExMobil().getSigla();
            } else {
                sigla = an.getMobil().getSigla();
            }

            byte[] ab = !estampar ? an.getArquivo().getPdf()
                    : stamp(an.getArquivo().getPdf(), sigla, an.getArquivo().isRascunho(),
                            an.getArquivo().isCancelado(), an.getArquivo().isSemEfeito(),
                            an.getArquivo().isInternoProduzido(), an.getArquivo().getQRCode(),
                            an.getArquivo().getMensagem(), an.getPaginaInicial(), an.getPaginaFinal(),
                            an.getOmitirNumeracao(), SigaExProperties.getTextoSuperiorCarimbo(),
                            mob.getExDocumento().getOrgaoUsuario().getDescricao());

            // we create a reader for a certain document

            reader = new PdfReader(ab);
            reader.consolidateNamedDestinations();
            // we retrieve the total number of pages
            n = reader.getNumberOfPages();
            // List bookmarks = SimpleBookmark.getBookmark(reader);
            // master.add(new Bookmark)
            // if (bookmarks != null) {
            // if (pageOffset != 0)
            // SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset,
            // null);
            // master.addAll(bookmarks);
            // }

            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, bo2);
                writer.setFullCompression();

                // writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);

                // step 3: we open the document
                document.open();

                nivelInicial = an.getNivel();
            }

            // PdfOutline root = writer.getDirectContent().getRootOutline();
            // PdfContentByte cb = writer.getDirectContent();
            // PdfDestination destination = new
            // PdfDestination(PdfDestination.FITH, position);
            // step 4: we add content
            PdfImportedPage page;
            for (int j = 0; j < n;) {
                ++j;
                page = writer.getImportedPage(reader, j);
                writer.addPage(page);
                if (j == 1) {
                    // PdfContentByte cb = writer.getDirectContent();
                    // PdfOutline root = cb.getRootOutline();
                    // PdfOutline oline1 = new PdfOutline(root,
                    // PdfAction.gotoLocalPage("1", false),"Chapter 1");

                    HashMap map = new HashMap();
                    map.put("Title", an.getNome());
                    map.put("Action", "GoTo");
                    map.put("Page", j + pageOffset + "");
                    map.put("Kids", new ArrayList());

                    ArrayList mapPai = master;
                    for (int i = 0; i < an.getNivel() - nivelInicial; i++) {
                        mapPai = ((ArrayList) ((HashMap) mapPai.get(mapPai.size() - 1)).get("Kids"));
                    }
                    mapPai.add(map);
                }

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

            pageOffset += n;
            f++;
        }
        if (!master.isEmpty())
            writer.setOutlines(master);

        // PdfDictionary info = writer.getInfo();
        // info.put(PdfName.MODDATE, null);
        // info.put(PdfName.CREATIONDATE, null);
        // info.put(PdfName.ID, null);

        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return bo2.toByteArray();
}

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/* ww  w  .j a va  2 s .c om*/
 * @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//from ww w. ja  v  a  2  s .  c o  m
 * @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//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/*  w w  w  . java 2s  .c  o 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 = 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:it.pdfsam.console.tools.pdf.PdfAlternateMix.java

License:Open Source License

/**
  * Execute the mix command. On error an exception is thrown.
  * @throws AlternateMixException/*ww w  .  ja  v a 2s  .  c o  m*/
  */
public void execute() throws AlternateMixException {
    try {
        workingIndeterminate();
        out_message = "";
        Document pdf_document = null;
        PdfCopy pdf_writer = null;
        File tmp_o_file = TmpFileNameGenerator.generateTmpFile(o_file.getParent());
        PdfReader pdf_reader1;
        PdfReader pdf_reader2;

        pdf_reader1 = new PdfReader(new RandomAccessFileOrArray(input_file1.getAbsolutePath()), null);
        pdf_reader1.consolidateNamedDestinations();
        limits1[1] = pdf_reader1.getNumberOfPages();

        pdf_reader2 = new PdfReader(new RandomAccessFileOrArray(input_file2.getAbsolutePath()), null);
        pdf_reader2.consolidateNamedDestinations();
        limits2[1] = pdf_reader2.getNumberOfPages();

        pdf_document = new Document(pdf_reader1.getPageSizeWithRotation(1));
        pdf_writer = new PdfCopy(pdf_document, new FileOutputStream(tmp_o_file));
        if (compressed_boolean) {
            pdf_writer.setFullCompression();
        }
        out_message += LogFormatter.formatMessage("Temporary file created-\n");
        MainConsole.setDocumentCreator(pdf_document);
        pdf_document.open();

        PdfImportedPage page;
        //importo
        boolean finished1 = false;
        boolean finished2 = false;
        int current1 = (reverseFirst) ? limits1[1] : limits1[0];
        int current2 = (reverseSecond) ? limits2[1] : limits2[0];
        while (!finished1 || !finished2) {
            if (!finished1) {
                if (current1 >= limits1[0] && current1 <= limits1[1]) {
                    page = pdf_writer.getImportedPage(pdf_reader1, current1);
                    pdf_writer.addPage(page);
                    current1 = (reverseFirst) ? (current1 - 1) : (current1 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("First file processed-\n");
                    finished1 = true;
                }
            }
            if (!finished2) {
                if (current2 >= limits2[0] && current2 <= limits2[1] && !finished2) {
                    page = pdf_writer.getImportedPage(pdf_reader2, current2);
                    pdf_writer.addPage(page);
                    current2 = (reverseSecond) ? (current2 - 1) : (current2 + 1);
                } else {
                    out_message += LogFormatter.formatMessage("Second file processed-\n");
                    finished2 = true;
                }
            }

        }

        pdf_reader1.close();
        pdf_writer.freeReader(pdf_reader1);
        pdf_reader2.close();
        pdf_writer.freeReader(pdf_reader2);

        pdf_document.close();
        // step 6: temporary buffer moved to output file
        renameTemporaryFile(tmp_o_file, o_file, overwrite_boolean);
        out_message += LogFormatter.formatMessage("Alternate mix completed-\n");

    } catch (Exception e) {
        throw new AlternateMixException(e);
    } finally {
        workCompleted();
    }
}

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  ww  . j a  va  2 s  . c  om*/
 */
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:lucee.runtime.tag.PDF.java

License:Open Source License

private void doActionAddWatermark() throws PageException, IOException, DocumentException {
    required("pdf", "addWatermark", "source", source);
    if (copyFrom == null && image == null)
        throw new ApplicationException(
                "at least one of the following attributes must be defined " + "[copyFrom,image]");

    if (destination != null && destination.exists() && !overwrite)
        throw new ApplicationException("destination file [" + destination + "] already exists");

    // image/*from  w  ww . j av a  2s  . com*/
    Image img = null;
    if (image != null) {
        lucee.runtime.img.Image ri = lucee.runtime.img.Image.createImage(pageContext, image, false, false, true,
                null);
        img = Image.getInstance(ri.getBufferedImage(), null, false);
    }
    // copy From
    else {
        byte[] barr;
        try {
            Resource res = Caster.toResource(pageContext, copyFrom, true);
            barr = IOUtil.toBytes(res);
        } catch (ExpressionException ee) {
            barr = Caster.toBinary(copyFrom);
        }
        img = Image.getInstance(PDFUtil.toImage(barr, 1).getBufferedImage(), null, false);

    }

    // position
    float x = UNDEFINED, y = UNDEFINED;
    if (!StringUtil.isEmpty(position)) {
        int index = position.indexOf(',');
        if (index == -1)
            throw new ApplicationException("attribute [position] has an invalid value [" + position + "],"
                    + "value should follow one of the following pattern [40,50], [40,] or [,50]");
        String strX = position.substring(0, index).trim();
        String strY = position.substring(index + 1).trim();
        if (!StringUtil.isEmpty(strX))
            x = Caster.toIntValue(strX);
        if (!StringUtil.isEmpty(strY))
            y = Caster.toIntValue(strY);

    }

    PDFDocument doc = toPDFDocument(source, password, null);
    doc.setPages(pages);
    PdfReader reader = doc.getPdfReader();
    reader.consolidateNamedDestinations();
    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 (!StringUtil.isEmpty(name) || destIsSource) {
        os = new ByteArrayOutputStream();
    } else if (destination != null) {
        os = destination.getOutputStream();
    }

    try {

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

        if (len > 0) {
            if (x == UNDEFINED || y == UNDEFINED) {
                PdfImportedPage first = stamp.getImportedPage(reader, 1);
                if (y == UNDEFINED)
                    y = (first.getHeight() - img.getHeight()) / 2;
                if (x == UNDEFINED)
                    x = (first.getWidth() - img.getWidth()) / 2;
            }
            img.setAbsolutePosition(x, y);
            //img.setAlignment(Image.ALIGN_JUSTIFIED); ration geht nicht anhand mitte

        }

        // rotation
        if (rotation != 0) {
            img.setRotationDegrees(rotation);
        }

        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();
            //print.out("op:"+opacity);
            gs1.setFillOpacity(opacity);
            //gs1.setStrokeOpacity(opacity);
            cb.setGState(gs1);
            cb.addImage(img);
        }
        if (bookmarks != null)
            stamp.setOutlines(master);
        stamp.close();
    } finally {
        IOUtil.closeEL(os);
        if (os instanceof ByteArrayOutputStream) {
            if (destination != null)
                IOUtil.copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination,
                        true);// MUST overwrite
            if (!StringUtil.isEmpty(name)) {
                pageContext.setVariable(name,
                        new PDFDocument(((ByteArrayOutputStream) os).toByteArray(), password));
            }
        }
    }
}

From source file:lucee.runtime.text.pdf.PDFUtil.java

License:Open Source License

/**
 * @param docs/*  w w w  . j  a  v a  2 s  .c o  m*/
 * @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(PDFDocument[] 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 (!stopOnError)
                    continue;
                throw Caster.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 {
        IOUtil.closeEL(document);
    }
}