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:papertoolkit.paper.bundles.PDFBundle.java

License:BSD License

/**
 * Reads the PDF file. For each page, create a new PDFSheet referencing that page. Add that
 * sheet to this bundle./* www .j  a  va  2 s .  c om*/
 */
private void addPDFSheetsFromFile() {
    try {
        final PdfReader reader = new PdfReader(new FileInputStream(file));
        numSheets = reader.getNumberOfPages();
        reader.close();
        for (int i = 0; i < numSheets; i++) {
            // (i+1) because Page Numbers start from 1
            addSheets(new PDFSheet(file, i + 1));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:papertoolkit.render.sheets.PDFSheetRenderer.java

License:BSD License

/**
 * Uses the iText package to render a PDF file. iText is nice because we can write to a
 * Graphics2D context. Alternatively, we can use PDF-like commands.
 * //from   w w w  . java 2 s  .c  o  m
 * @param destPDFFile
 */
public void renderToPDF(File destPDFFile) {
    try {
        final FileOutputStream fileOutputStream = new FileOutputStream(destPDFFile);

        final PdfReader reader = pdfSheet.getReader();
        DebugUtils.println("NumPages in Existing PDF: " + reader.getNumberOfPages());

        // allows us to stamp on top of an existing PDF
        final PdfStamper stamp = new PdfStamper(reader, fileOutputStream);

        // change the content on top of page 1
        // bottom layer for regions
        final PdfContentByte topLayer = stamp.getOverContent(1 /* page number */);
        final PdfContentByte bottomLayer = stamp.getUnderContent(1);
        renderToPDFContentLayers(destPDFFile, topLayer, bottomLayer);
        stamp.close();

        // save the pattern info to the same directory automatically
        savePatternInformation(); // do this automatically
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:questions.importpages.ConcatenateMakeTOC.java

public static void main(String[] args) {
    Document document = new Document();
    try {/*from  w  w  w.  j a  v  a2 s . c om*/
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        copy.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        document.open();
        List<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
        List<HashMap<String, Object>> kids;
        PdfReader reader;
        int page = 1;
        for (int i = 0; i < 3; i++) {
            createPdf(i);
            HashMap<String, Object> titlepage = new HashMap<String, Object>();
            titlepage.put("Title", String.format("Document %d", i + 1));
            titlepage.put("Action", "GoTo");
            titlepage.put("Page", String.format("%d Fit", page));
            kids = new ArrayList<HashMap<String, Object>>();
            reader = new PdfReader(RESULTS[i]);
            for (int j = 1; j <= reader.getNumberOfPages(); j++) {
                copy.addPage(copy.getImportedPage(reader, j));
                HashMap<String, Object> kid = new HashMap<String, Object>();
                kid.put("Title", String.format("Page %d in document %d", j, i + 1));
                kid.put("Action", "GoTo");
                kid.put("Page", String.format("%d FitH 806", page));
                kids.add(kid);
                page++;
            }
            titlepage.put("Kids", kids);
            bookmarks.add(titlepage);
        }
        copy.setOutlines(bookmarks);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:questions.importpages.ConcatenateWithTOC.java

public static void main(String[] args) {
    try {/*  w  w  w .  j  a v  a2 s.  c  o m*/
        // suppose we have some TEST PDF files
        for (int i = 0; i < TEST.length; i++) {
            createTestPdf(i);
        }
        // and we want to concatenate them
        Document document = new Document();
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(RESULT));
        copy.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        document.open();
        // but we want to create an outline tree
        PdfOutline root = copy.getRootOutline();
        // we also want an extra page with the file name
        Document coverpage;
        ByteArrayOutputStream baos;
        PdfReader reader;
        // we want to add page numbers too
        int pagenumber = 0;
        BaseFont bf = BaseFont.createFont();
        for (int i = 0; i < TEST.length; i++) {
            // we create the coverpage in memory
            coverpage = new Document();
            baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(coverpage, baos);
            coverpage.open();
            coverpage.add(new Paragraph("file: " + TEST[i]));
            coverpage.close();
            // we import that page
            reader = new PdfReader(baos.toByteArray());
            pagenumber++;
            copy.addPage(getStampedPage(reader, copy, 1, pagenumber, bf));
            // we create the bookmark to that page
            PdfDestination dest = new PdfDestination(PdfDestination.FIT);
            new PdfOutline(root, PdfAction.gotoLocalPage(pagenumber, dest, copy), TEST[i]);
            // we import the document itself
            reader = new PdfReader(TEST[i]);
            for (int j = 1; j <= reader.getNumberOfPages(); j++) {
                pagenumber++;
                copy.addPage(getStampedPage(reader, copy, j, pagenumber, bf));
            }
        }
        document.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (DocumentException de) {
        de.printStackTrace();
    }
}

From source file:questions.importpages.ConcatenateWithTOC2.java

public static void main(String[] args) {
    try {//from   ww  w  . j a  va  2  s  .  c om
        // suppose we have some TEST PDF files
        for (int i = 0; i < TEST.length; i++) {
            createTestPdf(i);
        }
        // and we want to concatenate them
        Document document = new Document();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PdfCopy copy = new PdfCopy(document, os);
        copy.setViewerPreferences(PdfWriter.PageModeUseOutlines);
        document.open();
        // but we want to create an outline tree
        PdfOutline root = copy.getRootOutline();
        // we also want an extra page with the file name
        Document coverpage;
        ByteArrayOutputStream baos;
        PdfReader reader;
        // we want keep track of the page numbers
        int pagenumber = 0;
        for (int i = 0; i < TEST.length; i++) {
            // we create the coverpage in memory
            coverpage = new Document();
            baos = new ByteArrayOutputStream();
            PdfWriter.getInstance(coverpage, baos);
            coverpage.open();
            coverpage.add(new Paragraph("file: " + TEST[i]));
            coverpage.close();
            // we import that page
            reader = new PdfReader(baos.toByteArray());
            pagenumber++;
            copy.addPage(copy.getImportedPage(reader, 1));
            // we create the bookmark to that page
            PdfDestination dest = new PdfDestination(PdfDestination.FIT);
            new PdfOutline(root, PdfAction.gotoLocalPage(pagenumber, dest, copy), TEST[i]);
            // we import the document itself
            reader = new PdfReader(TEST[i]);
            for (int j = 1; j <= reader.getNumberOfPages(); j++) {
                pagenumber++;
                copy.addPage(copy.getImportedPage(reader, j));
            }
        }
        document.close();

        // we want to add page X of Y
        reader = new PdfReader(os.toByteArray());
        int n = reader.getNumberOfPages();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        BaseFont bf = BaseFont.createFont();
        for (int i = 1; i <= n; i++) {
            PdfContentByte canvas = stamper.getOverContent(i);
            canvas.beginText();
            canvas.setFontAndSize(bf, 12);
            canvas.showTextAligned(Element.ALIGN_LEFT, "page " + i + " of " + n, 36, 26, 0);
            canvas.endText();
        }
        stamper.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (DocumentException de) {
        de.printStackTrace();
    }
}

From source file:questions.importpages.HelloWorldImportedPages.java

public static void main(String[] args) {
    // we create a PDF file
    createPdf(SOURCE);/*from   w w  w. j a  va  2  s.  co m*/
    // step 1
    Document document = new Document(PageSize.A4);
    try {
        // we create a PdfReader object
        PdfReader reader = new PdfReader(SOURCE);
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfImportedPage page;
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            page = writer.getImportedPage(reader, i);
            Image image = Image.getInstance(page);
            image.scalePercent(15f);
            image.setBorder(Rectangle.BOX);
            image.setBorderWidth(3f);
            image.setBorderColor(new GrayColor(0.5f));
            image.setRotationDegrees(-reader.getPageRotation(i));
            document.add(image);
            document.add(new Paragraph("This is page: " + i));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    // step 5
    document.close();
}

From source file:questions.stamppages.AddCropbox.java

public static void main(String[] args) {
    try {/*from w  ww .  ja va2s.c om*/
        PdfImportedPage page;
        PdfDictionary pageDict;
        PdfReader reader = new PdfReader(RESOURCE);
        Document document = new Document(reader.getPageSizeWithRotation(1));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT2));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            page = writer.getImportedPage(reader, 1);
            cb.rectangle(0, 52, 612, 668);
            cb.clip();
            cb.newPath();
            cb.addTemplate(page, 0, 0);
            pageDict = reader.getPageN(i);
            PdfArray crop = new PdfRectangle(0, 52, 612, 720);
            pageDict.put(PdfName.CROPBOX, crop);
        }
        document.close();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT1));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.stamppages.IncreaseMediabox.java

public static void main(String[] args) {
    try {//w  w w  . ja  va2 s.  c o  m
        PdfDictionary pageDict;
        PdfReader reader = new PdfReader(RESOURCE);
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            Rectangle rect = reader.getPageSize(i);
            pageDict = reader.getPageN(i);
            PdfRectangle pdfrect = new PdfRectangle(rect.getLeft(-36), rect.getBottom(-36), rect.getRight(-36),
                    rect.getTop(-36));
            pageDict.put(PdfName.MEDIABOX, pdfrect);
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.stamppages.RemoveAttachmentAnnotations.java

public static void main(String[] args) throws IOException, DocumentException {
    createPdfWithAttachments();//  w ww. ja  v a  2  s. c  o m
    PdfReader reader = new PdfReader(RESOURCE);
    PdfDictionary page;
    PdfDictionary annotation;
    for (int i = 1; i <= reader.getNumberOfPages(); i++) {
        page = reader.getPageN(i);
        PdfArray annots = page.getAsArray(PdfName.ANNOTS);
        if (annots != null) {
            for (int j = annots.size() - 1; j >= 0; j--) {
                annotation = annots.getAsDict(j);
                if (PdfName.FILEATTACHMENT.equals(annotation.get(PdfName.SUBTYPE))) {
                    annots.remove(j);
                }
            }
        }
    }
    reader.removeUnusedObjects();
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    stamper.close();
}

From source file:s2s.luna.reports.Stampa_documento.java

License:GNU General Public License

@SuppressWarnings("CallToThreadDumpStack")
private boolean addPDF(String titolo, byte[] fileContent, Document document, PdfWriter writer) {
    try {//from ww w  . j a  v a2  s  .c  om
        // Inizializzo il contenitore del pdf da importare.
        PdfContentByte cb = writer.getDirectContent();

        // Inizializzo la variabile dove appogger (una alla volta)
        // le pagine del pdf da importare.
        PdfImportedPage page;

        // Apro in lettura il pdf da importare.
        PdfReader pdfReader = new PdfReader(fileContent);

        // Ne determino il numero di pagine totali.
        int pdfPageNumber = pdfReader.getNumberOfPages();

        // Inzializzo il contatore delle pagine.
        int pageOfCurrentReaderPDF = 1;

        // Per ogni pagina...
        while (pageOfCurrentReaderPDF <= pdfPageNumber) {
            // Creo una nuova pagina vuota sul pdf di destinazione.
            document.newPage();
            // Estraggo la pagina dal pdf da importare.
            page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
            // Coverto la pagina in un immagine.
            Image pageImg = Image.getInstance(page);
            // Aggiungo la pagina estratta al pdf di destinazione, ruotandola se necessario.
            PdfPTable table = new PdfPTable(1);
            PdfPCell defaultCell = table.getDefaultCell();
            defaultCell.setRotation(-pdfReader.getPageRotation(pageOfCurrentReaderPDF));
            defaultCell.setBorder(Rectangle.NO_BORDER);
            table.addCell(pageImg);
            document.add(table);
            // Incremento il contatore delle pagine
            pageOfCurrentReaderPDF++;
        }
        return true;
    } catch (Exception ex) {
        // Eccezione silenziosa.
        // Gestisce il caso in cui si verifica un errore non previsto
        ex.printStackTrace();
        return false;
    }
}