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

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

Introduction

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

Prototype

public PdfReader(PdfReader reader) 

Source Link

Document

Creates an independent duplicate.

Usage

From source file:org.jrimum.bopepo.pdf.PdfDocReader.java

License:Apache License

/**
 * Ler e analisa o documento./*  www .  jav  a2s.c o m*/
 * 
 * @param pdfIn
 *            Byte array contendo o documento
 */
@SuppressWarnings("unchecked")
public PdfDocReader(byte[] pdfIn) {
    PdfReader r = null;
    try {
        r = new PdfReader(pdfIn);
    } catch (Exception e) {
        Exceptions.throwIllegalStateException(e);
    }
    this.reader = r;
    this.form = reader.getAcroFields();
    this.docInfo = PdfDocInfo.create(this.reader.getInfo());
}

From source file:org.jrimum.bopepo.pdf.PdfDocReader.java

License:Apache License

/**
 * Ler e analisa o documento.// w ww  .  j a  v a2s.c o m
 * 
 * @param is
 *            Stream contendo o documento
 */
@SuppressWarnings("unchecked")
public PdfDocReader(InputStream is) {
    PdfReader r = null;
    try {
        r = new PdfReader(is);
    } catch (Exception e) {
        Exceptions.throwIllegalStateException(e);
    }
    this.reader = r;
    this.form = reader.getAcroFields();
    this.docInfo = PdfDocInfo.create(this.reader.getInfo());
}

From source file:org.jrimum.bopepo.pdf.PdfDocReader.java

License:Apache License

/**
 * Ler e analisa o documento./*from  ww  w  . ja  va 2 s.  c  om*/
 * 
 * @param url
 *            URL do documento
 */
@SuppressWarnings("unchecked")
public PdfDocReader(URL url) {
    PdfReader r = null;
    try {
        r = new PdfReader(url);
    } catch (Exception e) {
        Exceptions.throwIllegalStateException(e);
    }
    this.reader = r;
    this.form = reader.getAcroFields();
    this.docInfo = PdfDocInfo.create(this.reader.getInfo());
}

From source file:org.jrimum.bopepo.pdf.PdfDocReader.java

License:Apache License

/**
 * Ler e analisa o documento.// w  ww. j  av  a 2s . c  o  m
 * 
 * @param file
 *            Arquivo contendo o documento
 */
@SuppressWarnings("unchecked")
public PdfDocReader(File file) {
    PdfReader r = null;
    try {
        r = new PdfReader(new FileInputStream(file));
    } catch (Exception e) {
        Exceptions.throwIllegalStateException(e);
    }
    this.reader = r;
    this.form = reader.getAcroFields();
    this.docInfo = PdfDocInfo.create(this.reader.getInfo());
}

From source file:org.jrimum.bopepo.pdf.PDFs.java

License:Apache License

/**
 * Junta varios arquivos pdf em um s./*www . j av  a 2s. co m*/
 * 
 * @param pdfFiles
 *            Coleo de array de bytes
 * @param info
 *            Usa somente as informaes
 *            (title,subject,keywords,author,creator)
 * 
 * @return Arquivo PDF em forma de byte
 * 
 * @since 0.2
 */
public static byte[] mergeFiles(Collection<byte[]> pdfFiles, PdfDocInfo info) {

    try {

        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();

        Document document = new Document();

        PdfCopy copy = new PdfCopy(document, byteOS);

        document.open();

        for (byte[] f : pdfFiles) {

            PdfReader reader = new PdfReader(f);

            for (int page = 1; page <= reader.getNumberOfPages(); page++) {

                copy.addPage(copy.getImportedPage(reader, page));
            }

            reader.close();
        }

        document.addCreationDate();

        if (info != null) {

            document.addAuthor(info.author());
            document.addCreator(info.creator());
            document.addTitle(info.title());
            document.addSubject(info.subject());
            document.addKeywords(info.keywords());
        }

        copy.close();
        document.close();
        byteOS.close();

        return byteOS.toByteArray();

    } catch (Exception e) {
        return Exceptions.throwIllegalStateException(e);
    }
}

From source file:org.jrimum.bopepo.pdf.PDFUtil.java

License:Apache License

/**
 * <p>//ww  w . j a  va2 s .c  o m
 * 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:org.kuali.coeus.common.committee.impl.web.struts.action.CommitteeActionsActionBase.java

License:Open Source License

/**
 * This method merged the pdf bytes without creating page numbers and dates.
 * //from www  . j  a  v  a  2s . c  om
 * (This is a slimed down version of MergePdfBytes() in PrintingServiceImpl.java)
 * 
 * @param pdfBytesList
 *            List containing the PDF data bytes
 * @param bookmarksList
 *            List of bookmarks corresponding to the PDF bytes.
 * @return
 * @throws PrintingException
 */
private byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    for (int count = 0; count < pdfBytesList.size(); count++) {
        PdfReader reader;
        try {
            reader = new PdfReader(pdfBytesList.get(count));
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
            break;
            //              throw new PrintingException(e.getMessage(), e);
        }
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF bytes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            document.open();
        }
        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }

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

    return null;
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

License:Open Source License

protected boolean isPdfGoodToMerge(byte[] pdfBytes) {
    try {//from   w w w  . ja v a  2s .  c o m
        new PdfReader(pdfBytes);
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.kuali.coeus.common.impl.print.PrintingServiceImpl.java

License:Open Source License

/**
 * @param pdfBytesList List containing the PDF data bytes
 * @param bookmarksList List of bookmarks corresponding to the PDF bytes.
 * @return//w w  w.  j  a  v  a2  s.  c  o m
 * @throws PrintingException
 */

protected byte[] mergePdfBytes(List<byte[]> pdfBytesList, List<String> bookmarksList,
        boolean headerFooterRequired) throws PrintingException {
    Document document = null;
    PdfWriter writer = null;
    ByteArrayOutputStream mergedPdfReport = new ByteArrayOutputStream();
    int totalNumOfPages = 0;
    PdfReader[] pdfReaderArr = new PdfReader[pdfBytesList.size()];
    int pdfReaderCount = 0;
    for (byte[] fileBytes : pdfBytesList) {
        LOG.debug("File Size " + fileBytes.length + " For " + bookmarksList.get(pdfReaderCount));
        PdfReader reader = null;
        try {
            reader = new PdfReader(fileBytes);
            pdfReaderArr[pdfReaderCount] = reader;
            pdfReaderCount = pdfReaderCount + 1;
            totalNumOfPages += reader.getNumberOfPages();
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
    HeaderFooter footer = null;
    if (headerFooterRequired) {
        Calendar calendar = dateTimeService.getCurrentCalendar();
        String dateString = formateCalendar(calendar);
        StringBuilder footerPhStr = new StringBuilder();
        footerPhStr.append(" of ");
        footerPhStr.append(totalNumOfPages);
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_76));
        footerPhStr.append(getWhitespaceString(WHITESPACE_LENGTH_60));
        footerPhStr.append(dateString);
        Font font = FontFactory.getFont(FontFactory.TIMES, 8, Font.NORMAL, Color.BLACK);
        Phrase beforePhrase = new Phrase("Page ", font);
        Phrase afterPhrase = new Phrase(footerPhStr.toString(), font);
        footer = new HeaderFooter(beforePhrase, afterPhrase);
        footer.setAlignment(Element.ALIGN_BASELINE);
        footer.setBorderWidth(0f);
    }
    for (int count = 0; count < pdfReaderArr.length; count++) {
        PdfReader reader = pdfReaderArr[count];
        int nop;
        if (reader == null) {
            LOG.debug("Empty PDF byetes found for " + bookmarksList.get(count));
            continue;
        } else {
            nop = reader.getNumberOfPages();
        }

        if (count == 0) {
            document = nop > 0 ? new com.lowagie.text.Document(reader.getPageSizeWithRotation(1))
                    : new com.lowagie.text.Document();
            try {
                writer = PdfWriter.getInstance(document, mergedPdfReport);
            } catch (DocumentException e) {
                LOG.error(e.getMessage(), e);
                throw new PrintingException(e.getMessage(), e);
            }
            if (footer != null) {
                document.setFooter(footer);
            }
            // writer.setPageEvent(new Watermark()); // add watermark object here
            document.open();
        }

        PdfContentByte cb = writer.getDirectContent();
        int pageCount = 0;
        while (pageCount < nop) {
            document.setPageSize(reader.getPageSize(++pageCount));
            document.newPage();
            if (footer != null) {
                document.setFooter(footer);
            }
            PdfImportedPage page = writer.getImportedPage(reader, pageCount);

            cb.addTemplate(page, 1, 0, 0, 1, 0, 0);

            PdfOutline root = cb.getRootOutline();
            if (pageCount == 1) {
                String pageName = bookmarksList.get(count);
                cb.addOutline(new PdfOutline(root, new PdfDestination(PdfDestination.FITH), pageName),
                        pageName);
            }
        }
    }
    if (document != null) {
        try {
            document.close();
            return mergedPdfReport.toByteArray();
        } catch (Exception e) {
            LOG.error("Exception occured because the generated PDF document has no pages", e);
        }
    }
    return null;
}

From source file:org.kuali.coeus.common.impl.print.watermark.WatermarkServiceImpl.java

License:Open Source License

/**
 * This method for applying watermark to the pdf
 * /*from  w  w  w.jav a 2 s. c o  m*/
 * @return pdfFileData
 */
public byte[] applyWatermark(byte[] pdfBytes, WatermarkBean watermarkBean) throws Exception {

    byte[] pdfFileData = pdfBytes;

    try {
        if (watermarkBean != null) {
            // flatten original PDF before adding watermark. This prevents interactive form data from getting lost.
            PdfReader origFile = new PdfReader(pdfBytes);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            PdfStamper stamper = new PdfStamper(origFile, byteArrayOutputStream);
            stamper.setFormFlattening(true);
            stamper.close();
            byteArrayOutputStream = attachWatermarking(watermarkBean, byteArrayOutputStream.toByteArray());
            pdfFileData = byteArrayOutputStream.toByteArray();
        }
    } catch (Exception exception) {
        LOG.error("Exception occured in WatermarkServiceImpl. Water mark Exception: " + exception);
    }

    return pdfFileData;
}