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

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

Introduction

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

Prototype

public int getNumberOfPages() 

Source Link

Document

Gets the number of pages in the document.

Usage

From source file:com.tommontom.pdfsplitter.PdfCombine.java

public List<File> combine(File folder) throws IOException, DocumentException {
    if (!folder.isDirectory()) {
        throw new IllegalArgumentException("Provided folder is not a directory: " + folder);
    }// w  w  w.j  a  v  a 2  s. c om
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter);

    /*
     * Stores the listing of the files
     */
    List<File> newFileList = new ArrayList<>();
    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }

        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf('.'));

        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("\\s");
        if (fileNames.length != 2) {
            throw new RuntimeException("File name format is not in right format");
        }

        String fileNameFirst = fileNames[0];
        String fileNameSecond = fileNames[1];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        String[] fileNameFirstParts = fileNameFirst.split("-");

        // Project num is always the 1st part
        String projectNum = fileNameFirstParts[0];
        if (!projectNum.equals(fileNameFirstParts[0])) {
            throw new RuntimeException("Filename needs to be renamed to the correct format");
        }
        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNameFirstParts[1]);
        secondLotNum = Integer.parseInt(fileNameFirstParts[2]);

        // Determine number of pages by difference of lot numbers

        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf,
        // 16034-212235.pdf, 16034-212236.pdf
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        int mod = pdfFileReader.getNumberOfPages() % 2;
        if (pdfFileReader.equals(mod)) {
            throw new RuntimeException("File is not an even number of pages");
        }
        Document document = new Document();

        /*
         * instantiates a new document to be made
         */
        int numPages = pdfFileReader.getNumberOfPages();
        int p = 0;
        int j = 0;
        // Create a copy of the orignal source file. We will pick specific pages
        // out below
        document.open();
        while (j < numPages) {
            if (p == numPages) {
                break;
            }
            if (j % 2 == 2) {
                j += 1;
            }
            j += 1;
            firstLotNum++;

            // Dynamic filename
            String dynamicFileName = projectNum + "-" + (firstLotNum - 1) + ".pdf";
            document = new Document();
            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(folder.getPath() + "\\" + dynamicFileName));
            document.open();
            p += 2;

            // Import pages from original doc
            copy.addPage(copy.getImportedPage(pdfFileReader, j));
            copy.addPage(copy.getImportedPage(pdfFileReader, p));
            document.close();

            // Add to the list of compled file names
            newFileList.add(new File(dynamicFileName));
        }
        System.out.println("Number of Documents Created:" + numPages);
        System.out.println("Number of Documents Created:" + listOfFiles[i]);
    }

    return newFileList;
}

From source file:com.tommontom.pdfsplitter.PdfMerge.java

public static void doMerge(java.util.List<InputStream> list, String[] imageList, String[] listWordExcels,
        OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    writer.setFullCompression();//w w  w.  j  av a 2s  . c o  m
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Image img;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }

    }
    for (int i = 0; i < imageList.length; i++) {
        document.newPage();
        if (imageList[i] != null) {
            img = Image.getInstance(String.format("%s", imageList[i]));
            Rectangle one = new Rectangle(img.getPlainWidth(), img.getPlainHeight());
            document.setPageSize(one);
            if (img.getScaledWidth() > img.getScaledHeight()) {
                img.rotate();
            }
            if (img.getScaledWidth() > 792 || img.getScaledHeight() > 792) {
                img.scaleToFit(792, 792);

            }
            img.setDpi(150, 150);
            document.add(img);
        }
    }
    for (int i = 0; i < listWordExcels.length; i++) {
        if (imageList[i] != null) {
            File input = new File(listWordExcels[i]);
            File output = new File(listWordExcels[i] + ".pdf");
            String outputS = listWordExcels[i] + ".pdf";
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(input, output);
            PdfReader readerWord = new PdfReader(outputS);
            PdfImportedPage page = writer.getImportedPage(readerWord, readerWord.getNumberOfPages());
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplit(String path) throws IOException, DocumentException, InterruptedException {
    // TODO Instead of hard code path, pass in as argument
    File folder = new File(path);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }// ww w.  ja va 2s . c  o m
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int k = 0;
        int numPages = pdfFileReader.getNumberOfPages();
        // Split on a space '\s'
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = (fileNameWithoutExt); /* Dynamic file name */

            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf"));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            deleteFile[k] = path + "\\" + FileName + "(" + j + 1 + ")" + ".pdf";
            k++;
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();

        }

        System.out.println("Number of Documents Created:" + numPages);
        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfSplitDrop(File[] files) throws IOException, DocumentException, InterruptedException {
    // TODO Instead of hard code path, pass in as argument
    String path;/*from  ww  w . ja  v  a2 s.c  o m*/
    if (directoryField.getText().isEmpty() || directoryField.getText().equals(example)) {
        path = files[0].getParent();
    } else {
        path = directoryField.getText();
    }
    File[] listOfFiles = files; /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }
        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int numPages = pdfFileReader.getNumberOfPages();
        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        // Create a copy of the orignal source file. We will pick specific pages out below
        int k = 0;
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = fileNameWithoutExt; /* Dynamic file name */

            PdfCopy copy = new PdfCopy(document,
                    new FileOutputStream(path + "\\" + FileName + "(" + j + ")" + ".pdf"));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */
            deleteFile[k] += path + "\\" + FileName + "(" + j + ")" + ".pdf";
            k++;
            if (j == 1) {
                newFileListing = ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + path + FileName + "(" + j + ")" + ".pdf" + "\n");
            }
            document.close();
            copy.close();
        }

        pdfFileReader.close();
    }
}

From source file:com.tommontom.pdfsplitter.PdfSplit.java

public void pdfEven(String path) throws IOException, DocumentException {

    String DEFAULT_PATH = path; // TODO Instead of hard code path, pass in as argument
    File folder = new File(DEFAULT_PATH);
    FileNameFilter FileFilter = new FileNameFilter();
    File[] listOfFiles = folder.listFiles(FileFilter); /* Stores the listing of the files */

    for (int i = 0; i < listOfFiles.length; i++) {
        File file = listOfFiles[i];
        if (!file.isFile()) {
            continue;
        }// w ww  .j  a v a  2 s . com

        // Split the source filename into its 2 parts
        String fileName = file.getName();
        String fileNameWithoutExt = fileName.substring(0, fileName.lastIndexOf("."));

        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("\\s");
        if (fileNames.length != 2) {
            throw new RuntimeException("File name format is not in right format");
        }

        String fileNameFirst = fileNames[0];
        String fileNameSecond = fileNames[1];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        String[] fileNameFirstParts = fileNameFirst.split("-");
        String[] fileNameSecondParts = fileNameSecond.split("-");

        // Project num is always the 1st part
        String projectNum = fileNameFirstParts[0];
        if (!projectNum.equals(fileNameSecondParts[0])) {
            throw new RuntimeException("Filename needs to be renamed to the correct format");
        }
        // Strip off the first and second lot number, parse into integers
        int firstLotNum;
        int secondLotNum;
        firstLotNum = Integer.parseInt(fileNameFirstParts[1]);
        secondLotNum = Integer.parseInt(fileNameSecondParts[1]);

        // Determine number of pages by difference of lot numbers
        // Read in the source document
        // Example file name: 16034-212234 16034-212236.pdf > 16034-212234.pdf, 16034-212235.pdf, 16034-212236.pdf
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        int mod = pdfFileReader.getNumberOfPages() % 2;
        if (pdfFileReader.equals(mod)) {
            throw new RuntimeException("File is not an even number of pages");
        }
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */

        int numPages = secondLotNum - firstLotNum + 1;
        int p = 0;
        int j = 1;
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        while (j < numPages) {
            j++;
            if (j % 2 == 1) {
                j += 1;
            }
            firstLotNum++;
            String FileName = projectNum + "-" + (firstLotNum - 1) + ".pdf"; /* Dynamic file name */

            document = new Document(PageSize.LETTER, 0, 0, 0, 0);
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(DEFAULT_PATH + "//" + FileName));
            if (j == 1) {
                newFileListing = ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n");
            } else if (j > 1) {
                newFileListing += ("Created File:" + DEFAULT_PATH + "//" + FileName + "\n");
            }
            document.open();
            p += 2;
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            copy.addPage(copy.getImportedPage(pdfFileReader, p));
            document.close();

        }
        System.out.println("Number of Documents Created:" + numPages);
        System.out.println("Number of Documents Created:" + listOfFiles[i]);
    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public void loadPdf(File pdf, PdfWriter writer, byte[] password, ImageProcessor imageProcessor, int... pages)
        throws VectorPrintException {
    RandomAccessFileOrArray ra = null;//  w  w  w  .  jav  a2 s  .com
    try {
        RandomAccessSourceFactory rasf = new RandomAccessSourceFactory();
        ra = new RandomAccessFileOrArray(rasf.createBestSource(pdf.getPath()));
        PdfReader reader = new PdfReader(ra, password);
        if (pages == null) {
            for (int i = 0; i < reader.getNumberOfPages();) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, ++i)));
                writer.freeReader(reader);
            }
        } else {
            for (int i : pages) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, i)));
                writer.freeReader(reader);
            }
        }
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(String.format("unable to load image %s", pdf.toString()), ex);
    } finally {
        if (ra != null) {
            try {
                ra.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

@Override
public void loadPdf(InputStream pdf, PdfWriter writer, Certificate certificate, Key key,
        String securityProvider, ImageProcessor imageProcessor, int... pages) throws VectorPrintException {
    // first download, then load
    File f = null;/*from   w w  w.j  a v  a 2 s  .co m*/
    try {
        f = File.createTempFile("pdf.", "pdf");
        f.deleteOnExit();
        IOHelper.load(pdf, new FileOutputStream(f), ReportConstants.DEFAULTBUFFERSIZE, true);
        PdfReader reader = new PdfReader(f.getPath(), certificate, key, securityProvider);
        if (pages == null) {
            for (int i = 0; i < reader.getNumberOfPages();) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, ++i)));
                writer.freeReader(reader);
            }
        } else {
            for (int i : pages) {
                imageProcessor.processImage(Image.getInstance(writer.getImportedPage(reader, i)));
                writer.freeReader(reader);
            }
        }
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(String.format("unable to load image %s", pdf.toString()), ex);
    } finally {
        if (f != null) {
            f.delete();
        }
    }
}

From source file:com.vectorprint.report.itext.TocOutputStream.java

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {/* www  .  jav  a 2s  . co  m*/
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:com.wabacus.system.assistant.PdfAssistant.java

License:Open Source License

public void addPdfPageToDocument(PdfCopy pdfCopy, ByteArrayOutputStream baos) {
    if (baos == null)
        return;/*from   ww  w . j a v  a2 s .  c  o m*/
    PdfReader readerTmp = null;
    try {
        readerTmp = new PdfReader(baos.toByteArray());
        for (int i = 1, len = readerTmp.getNumberOfPages(); i <= len; i++) {
            pdfCopy.addPage(pdfCopy.getImportedPage(readerTmp, i));
        }
    } catch (Exception e) {
        throw new WabacusRuntimeException("PDF", e);
    } finally {
        try {
            if (baos != null)
                baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        readerTmp.close();
    }
}

From source file:com.whty.transform.common.utils.TransformUtils.java

public static boolean pdfTopdf(String docpath) {
    File pdfPath = new File(SysConf.getString("path.output") + docpath + "/pdf/");
    if (!pdfPath.exists()) {
        pdfPath.mkdirs();/*  w  w w.ja va2 s . c  o m*/
    }
    // pdf?
    try {
        PdfReader reader = new PdfReader(SysConf.getString("path.input") + docpath);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document(reader.getPageSize(1));
        PdfCopy copy = new PdfCopy(document,
                new FileOutputStream(pdfPath.getAbsoluteFile() + "/" + transFileName + ".pdf"));
        document.open();
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            document.newPage();
            PdfImportedPage page = copy.getImportedPage(reader, i);
            copy.addPage(page);
        }
        document.close();
        return true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    } catch (DocumentException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return false;
}