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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:org.egov.wtms.web.controller.reports.GenerateConnectionBillController.java

License:Open Source License

private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) {

    Document document = null;//from   ww  w  .jav  a  2  s . c o m
    try {
        final List<InputStream> pdfs = streamOfPDFFiles;
        final List<PdfReader> readers = new ArrayList<PdfReader>();
        final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            final InputStream pdf = iteratorPDFs.next();
            final PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            if (null == document)
                document = new Document(pdfReader.getPageSize(1));
        }
        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        final PdfContentByte cb = writer.getDirectContent(); // Holds the
        // PDF
        // data

        PdfImportedPage page;
        int pageOfCurrentReaderPDF = 0;
        final Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            final PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();

    } catch (final Exception e) {

        LOGGER.error("Exception in concat PDFs : ", e);
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (final IOException ioe) {
            LOGGER.error("Exception in concat PDFs : ", ioe);
        }
    }

    return outputStream.toByteArray();
}

From source file:org.egov.wtms.web.controller.reports.SearchNoticeController.java

License:Open Source License

private byte[] concatPDFs(final List<InputStream> streamOfPDFFiles, final ByteArrayOutputStream outputStream) {

    Document document = null;//w w  w.  ja v  a  2s. com
    try {
        final List<InputStream> pdfs = streamOfPDFFiles;
        final List<PdfReader> readers = new ArrayList<>();
        final Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            final InputStream pdf = iteratorPDFs.next();
            final PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            if (null == document)
                document = new Document(pdfReader.getPageSize(1));
        }
        // Create a writer for the outputstream
        final PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        final PdfContentByte cb = writer.getDirectContent(); // Holds the
        // PDF
        // data

        PdfImportedPage page;
        int pageOfCurrentReaderPDF = 0;
        final Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            final PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();

    } catch (final Exception e) {

        LOGGER.error("Exception in concat PDFs : ", e);
    } finally {
        if (document.isOpen())
            document.close();
        try {
            if (outputStream != null)
                outputStream.close();
        } catch (final IOException ioe) {
            LOGGER.error("Exception in concat PDFs : ", ioe);
        }
    }

    return outputStream != null ? outputStream.toByteArray() : null;
}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

public int getPageCount() throws DocumentException {

    int pageCount = 0;

    if (content == null) {
        return pageCount;
    }/*from  w  w w  . j  a va  2s .  co  m*/

    ByteArrayInputStream bais = null;
    PdfReader reader = null;

    try {

        bais = new ByteArrayInputStream(content);
        reader = new PdfReader(bais);
        pageCount = reader.getNumberOfPages();

    } catch (Exception e) {
        throw new DocumentException(e);
    } finally {
        if (reader != null)
            reader.close();
        IOUtils.closeQuietly(bais);
    }

    return pageCount;

}

From source file:org.ghost4j.document.PDFDocument.java

License:LGPL

@Override
public void append(Document document) throws DocumentException {

    super.append(document);

    ByteArrayOutputStream baos = null;
    com.lowagie.text.Document mergedDocument = new com.lowagie.text.Document();

    try {//w  w  w  .j  ava2 s  .  c o m

        baos = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(mergedDocument, baos);

        mergedDocument.open();

        // copy current document
        PdfReader reader = new PdfReader(content);
        int pageCount = reader.getNumberOfPages();
        for (int i = 0; i < pageCount;) {
            copy.addPage(copy.getImportedPage(reader, ++i));
        }

        // copy new document
        reader = new PdfReader(document.getContent());
        pageCount = reader.getNumberOfPages();
        for (int i = 0; i < pageCount;) {
            copy.addPage(copy.getImportedPage(reader, ++i));
        }

        mergedDocument.close();

        // replace content with new content
        content = baos.toByteArray();

    } catch (Exception e) {
        throw new DocumentException(e);
    } finally {
        if (mergedDocument.isOpen())
            mergedDocument.close();
        IOUtils.closeQuietly(baos);
    }

}

From source file:org.jaffa.modules.printing.services.MultiFormPrintEngine.java

License:Open Source License

/**
 * Merge a list of generated Pdf Documents together
 * @param documents //from  ww  w .j a v a 2s.c  om
 * @throws java.io.IOException 
 * @throws com.lowagie.text.DocumentException 
 * @return byte[]
 */
public static byte[] mergePdf(List<byte[]> documents) throws IOException, DocumentException {
    int pageOffset = 0;
    ArrayList master = new ArrayList();
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    Document document = null;
    PdfCopy writer = null;
    boolean first = true;
    for (Iterator<byte[]> it = documents.iterator(); it.hasNext();) {
        // we create a reader for a certain document
        PdfReader reader = new PdfReader(it.next());
        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 (first) {
            first = false;

            // 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, output);
            // 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 (master.size() > 0)
        writer.setOutlines(master);
    // step 5: we close the document
    if (document != null)
        document.close();
    return output.toByteArray();
}

From source file:org.jaffa.modules.printing.services.PdfHelper.java

License:Open Source License

/**
 * Scale the pages of the input pdfOutput document to the given pageSize.
 * @param pdfOutput The PDF document to rescale, in the form of a ByteArrayOutputStream.
 * @param pageSize The new page size to which to scale to PDF document, e.g. "A4".
 * @param noEnlarge If true, center pages instead of enlarging them.
 *        Use noEnlarge if the new page size is larger than the old one
 *        and the pages should be centered instead of enlarged.
 * @param preserveAspectRatio If true, the aspect ratio will be preserved.
 * @return The PDF document with its pages scaled to the input pageSize.
 *//*w w w  .  j  ava 2 s  .co m*/
public static byte[] scalePdfPages(byte[] pdfOutput, String pageSize, boolean noEnlarge,
        boolean preserveAspectRatio) throws FormPrintException {
    if (pageSize == null || pdfOutput == null) {
        return pdfOutput;
    }

    // Get the dimensions of the given pageSize in PostScript points.
    // A PostScript point is a 72th of an inch.
    float dimX;
    float dimY;
    Rectangle rectangle;
    try {
        rectangle = PageSize.getRectangle(pageSize);
    } catch (Exception ex) {
        FormPrintException e = new PdfProcessingException(
                "scalePdfPages  - Invalid page size = " + pageSize + "  ");
        log.error(" scalePdfPages  - Invalid page size: " + pageSize + ".  " + ex.getMessage() + ". ");
        throw e;
    }
    if (rectangle != null) {
        dimX = rectangle.getWidth();
        dimY = rectangle.getHeight();
    } else {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Invalid page size: " + pageSize);
        log.error(" scalePdfPages  - Invalid page size: " + pageSize);
        throw e;
    }
    //Create portrait and landscape rectangles for the given page size.
    Rectangle portraitPageSize;
    Rectangle landscapePageSize;
    if (dimY > dimX) {
        portraitPageSize = new Rectangle(dimX, dimY);
        landscapePageSize = new Rectangle(dimY, dimX);
    } else {
        portraitPageSize = new Rectangle(dimY, dimX);
        landscapePageSize = new Rectangle(dimX, dimY);
    }

    // Remove the document rotation before resizing the document.
    byte[] output = removeRotation(pdfOutput);
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(output);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Reader");
        log.error(" scalePdfPages  - Failed to create a PDF Reader ");
        throw e;
    }

    OutputStream baos = new ByteArrayOutputStream();
    Rectangle newSize = new Rectangle(dimX, dimY);
    Document document = new Document(newSize, 0, 0, 0, 0);
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException("scalePdfPages  - Failed to create a PDF Writer");
        log.error(" scalePdfPages  - Failed to create a PDF Writer ");
        throw e;
    }
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    PdfImportedPage page;
    float offsetX, offsetY;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        if (currentReader.getPageRotation(i) != 0) {
            FormPrintException e = new PdfProcessingException("Page Rotation, "
                    + currentReader.getPageRotation(i) + ", must be removed to re-scale the form.");
            log.error(" Page Rotation, " + currentReader.getPageRotation(i)
                    + ", must be removed to re-scale the form. ");
            throw e;
        }
        //Reset the page size for each page because there may be a mix of sizes in the document.
        float currentWidth = currentSize.getWidth();
        float currentHeight = currentSize.getHeight();
        if (currentWidth > currentHeight) {
            newSize = landscapePageSize;
        } else {
            newSize = portraitPageSize;
        }
        document.setPageSize(newSize);
        document.newPage();
        float factorX = newSize.getWidth() / currentSize.getWidth();
        float factorY = newSize.getHeight() / currentSize.getHeight();
        // Use noEnlarge if the new page size is larger than the old one
        // and the pages should be centered instead of enlarged.
        if (noEnlarge) {
            if (factorX > 1) {
                factorX = 1;
            }
            if (factorY > 1) {
                factorY = 1;
            }
        }
        if (preserveAspectRatio) {
            factorX = Math.min(factorX, factorY);
            factorY = factorX;
        }
        offsetX = (newSize.getWidth() - (currentSize.getWidth() * factorX)) / 2f;
        offsetY = (newSize.getHeight() - (currentSize.getHeight() * factorY)) / 2f;
        page = writer.getImportedPage(currentReader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, offsetX, offsetY);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}

From source file:org.jaffa.modules.printing.services.PdfHelper.java

License:Open Source License

/**
 * Remove the rotation from the pdfOutput document pages.
 *///from  w  w  w  . j a va 2 s.co  m
private static byte[] removeRotation(byte[] pdfOutput) throws FormPrintException {
    PdfReader currentReader = null;
    try {
        currentReader = new PdfReader(pdfOutput);
    } catch (IOException ex) {
        FormPrintException e = new PdfProcessingException(
                "Remove PDF Page Rotation  - Failed to create a PDF Reader");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Reader ");
        throw e;
    }
    boolean needed = false;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        if (currentReader.getPageRotation(i) != 0) {
            needed = true;
        }
    }
    if (!needed) {
        return pdfOutput;
    }

    OutputStream baos = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baos);
    } catch (DocumentException ex) {
        FormPrintException e = new PdfProcessingException(
                "Remove PDF Page Rotation  - Failed to create a PDF Writer");
        log.error(" Remove PDF Page Rotation  - Failed to create a PDF Writer ");
        throw e;
    }
    PdfContentByte cb = null;
    PdfImportedPage page;
    for (int i = 1; i <= currentReader.getNumberOfPages(); i++) {
        Rectangle currentSize = currentReader.getPageSizeWithRotation(i);
        currentSize = new Rectangle(currentSize.getWidth(), currentSize.getHeight()); // strip rotation
        document.setPageSize(currentSize);
        if (cb == null) {
            document.open();
            cb = writer.getDirectContent();
        } else {
            document.newPage();
        }
        int rotation = currentReader.getPageRotation(i);
        page = writer.getImportedPage(currentReader, i);
        float a, b, c, d, e, f;
        if (rotation == 0) {
            a = 1;
            b = 0;
            c = 0;
            d = 1;
            e = 0;
            f = 0;
        } else if (rotation == 90) {
            a = 0;
            b = -1;
            c = 1;
            d = 0;
            e = 0;
            f = currentSize.getHeight();
        } else if (rotation == 180) {
            a = -1;
            b = 0;
            c = 0;
            d = -1;
            e = currentSize.getWidth();
            f = currentSize.getHeight();
        } else if (rotation == 270) {
            a = 0;
            b = 1;
            c = -1;
            d = 0;
            e = currentSize.getWidth();
            f = 0;
        } else {
            FormPrintException ex = new PdfProcessingException(
                    "Remove PDF Page Rotation - Unparsable rotation value: " + rotation);
            log.error(" Remove PDF Page Rotation - Unparsable form rotation value: " + rotation);
            throw ex;
        }
        cb.addTemplate(page, a, b, c, d, e, f);
    }
    document.close();
    return ((ByteArrayOutputStream) baos).toByteArray();
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void handouts(String file) {
    try {/*from   www  .ja  v a  2 s  . c o  m*/
        File src = new File(selectedFile);

        File dest = new File(file);

        int pages = 4;

        float x1 = 30f;
        float x2 = 280f;
        float x3 = 320f;
        float x4 = 565f;

        float[] y1 = new float[pages];
        float[] y2 = new float[pages];

        float height = (778f - (20f * (pages - 1))) / pages;
        y1[0] = 812f;
        y2[0] = 812f - height;

        for (int i = 1; i < pages; i++) {
            y1[i] = y2[i - 1] - 20f;
            y2[i] = y1[i] - height;
        }

        // we create a reader for a certain document
        PdfReader reader = new PdfReader(src.getAbsolutePath());
        // we retrieve the total number of pages
        int n = reader.getNumberOfPages();

        // step 1: creation of a document-object
        Document document = new Document(PageSize.A4);
        // step 2: we create a writer that listens to the document
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
        // step 3: we open the document
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfImportedPage page;
        int rotation;
        int i = 0;
        int p = 0;
        // step 4: we add content
        while (i < n) {
            i++;
            Rectangle rect = reader.getPageSizeWithRotation(i);
            float factorx = (x2 - x1) / rect.width();
            float factory = (y1[p] - y2[p]) / rect.height();
            float factor = (factorx < factory ? factorx : factory);
            float dx = (factorx == factor ? 0f : ((x2 - x1) - rect.width() * factor) / 2f);
            float dy = (factory == factor ? 0f : ((y1[p] - y2[p]) - rect.height() * factor) / 2f);
            page = writer.getImportedPage(reader, i);
            rotation = reader.getPageRotation(i);
            if (rotation == 90 || rotation == 270) {
                cb.addTemplate(page, 0, -factor, factor, 0, x1 + dx, y2[p] + dy + rect.height() * factor);
            } else {
                cb.addTemplate(page, factor, 0, 0, factor, x1 + dx, y2[p] + dy);
            }
            cb.setRGBColorStroke(0xC0, 0xC0, 0xC0);
            cb.rectangle(x3 - 5f, y2[p] - 5f, x4 - x3 + 10f, y1[p] - y2[p] + 10f);
            for (float l = y1[p] - 19; l > y2[p]; l -= 16) {
                cb.moveTo(x3, l);
                cb.lineTo(x4, l);
            }
            cb.rectangle(x1 + dx, y2[p] + dy, rect.width() * factor, rect.height() * factor);
            cb.stroke();

            p++;
            if (p == pages) {
                p = 0;
                document.newPage();
            }
        }
        // step 5: we close the document
        document.close();
    } catch (Exception e) {

        System.err.println(e.getMessage());
    }
}

From source file:org.jpedal.examples.simpleviewer.utils.ItextFunctions.java

License:Open Source License

public void stampImage(int pageCount, PdfPageData currentPageData, final StampImageToPDFPages stampImage) {
    File tempFile = null;/*from   w  w w  .  j  av a 2 s .  c o  m*/

    try {
        tempFile = File.createTempFile("temp", null);

        ObjectStore.copy(selectedFile, tempFile.getAbsolutePath());
    } catch (Exception e) {
        return;
    }

    try {

        int[] pgsToEdit = stampImage.getPages();

        if (pgsToEdit == null)
            return;

        File fileToTest = new File(stampImage.getImageLocation());
        if (!fileToTest.exists()) {
            currentGUI.showMessageDialog(Messages.getMessage("PdfViewerError.ImageDoesNotExist"));
            return;
        }

        List pagesToEdit = new ArrayList();
        for (int i = 0; i < pgsToEdit.length; i++)
            pagesToEdit.add(new Integer(pgsToEdit[i]));

        final PdfReader reader = new PdfReader(tempFile.getAbsolutePath());

        int n = reader.getNumberOfPages();

        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(selectedFile));

        Image img = Image.getInstance(fileToTest.getAbsolutePath());

        int chosenWidthScale = stampImage.getWidthScale();
        int chosenHeightScale = stampImage.getHeightScale();

        img.scalePercent(chosenWidthScale, chosenHeightScale);

        String chosenPlacement = stampImage.getPlacement();

        int chosenRotation = stampImage.getRotation();
        img.setRotationDegrees(chosenRotation);

        String chosenHorizontalPosition = stampImage.getHorizontalPosition();
        String chosenVerticalPosition = stampImage.getVerticalPosition();

        float chosenHorizontalOffset = stampImage.getHorizontalOffset();
        float chosenVerticalOffset = stampImage.getVerticalOffset();

        for (int page = 0; page <= n; page++) {
            if (pagesToEdit.contains(new Integer(page))) {

                PdfContentByte cb;
                if (chosenPlacement.equals("Overlay"))
                    cb = stamp.getOverContent(page);
                else
                    cb = stamp.getUnderContent(page);

                int currentRotation = currentPageData.getRotation(page);
                Rectangle pageSize;
                if (currentRotation == 90 || currentRotation == 270)
                    pageSize = reader.getPageSize(page).rotate();
                else
                    pageSize = reader.getPageSize(page);

                float startx, starty;
                if (chosenVerticalPosition.equals("From the top")) {
                    starty = pageSize.height() - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else if (chosenVerticalPosition.equals("Centered")) {
                    starty = (pageSize.height() / 2) - ((img.height() * (chosenHeightScale / 100)) / 2);
                } else {
                    starty = 0;
                }

                if (chosenHorizontalPosition.equals("From the left")) {
                    startx = 0;
                } else if (chosenHorizontalPosition.equals("Centered")) {
                    startx = (pageSize.width() / 2) - ((img.width() * (chosenWidthScale / 100)) / 2);
                } else {
                    startx = pageSize.width() - ((img.width() * (chosenWidthScale / 100)) / 2);
                }

                img.setAbsolutePosition(startx + chosenHorizontalOffset, starty + chosenVerticalOffset);

                cb.addImage(img);
            }
        }

        stamp.close();

    } catch (Exception e) {

        ObjectStore.copy(tempFile.getAbsolutePath(), selectedFile);

        e.printStackTrace();

    } finally {
        tempFile.delete();
    }
}

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

License:Apache License

/**
 * Junta varios arquivos pdf em um s.//  www  . j  a  v  a  2s .  c  om
 * 
 * @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);
    }
}