Example usage for com.itextpdf.text.pdf PdfCopy getImportedPage

List of usage examples for com.itextpdf.text.pdf PdfCopy getImportedPage

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfCopy getImportedPage.

Prototype

@Override
public PdfImportedPage getImportedPage(PdfReader reader, int pageNumber) 

Source Link

Document

Grabs a page from the input document

Usage

From source file:Separator.java

License:Apache License

public static void splitPDFFile(String fileName) {
    // splitting "documents" up by consecutive orientations
    try {//w w  w. j a v a2 s  .c o m
        int[] oriens = new int[pReader.getNumberOfPages()];
        ArrayList<Integer> splitSizes = new ArrayList<Integer>();
        int splitSize = 1;
        int position = 0;
        for (int i = 1; i <= pReader.getNumberOfPages(); i++) {
            String picName = System.getProperty("user.home")
                    + "\\Desktop\\Scan Folder\\Temp Pictures\\my_image_" + i + ".jpg";
            oriens[i - 1] = getOrientation(new Picture(picName));
            System.out.print(oriens[i - 1]);
            if (i == 1) {
                splitSizes.add(1);
            } else if (oriens[i - 1] == oriens[i - 2]) {
                splitSize++;
                if (i == pReader.getNumberOfPages()) {
                    splitSizes.set(position, splitSize);
                }
            } else if (oriens[i - 1] != oriens[i - 2]) {
                splitSizes.set(position, splitSize);
                position++;
                splitSizes.add(1);
                splitSize = 1;
            } else {
                System.out.println("Error");
            }

        }
        System.out.println("\n\n" + splitSizes);
        System.out.println("\nSuccessfully read input file: " + fileName + "\n");
        int totalPages = pReader.getNumberOfPages();
        System.out.println("There are total " + totalPages + " pages in this input file\n");
        split = 0;

        // Page numbers start from 1 to n; writing each set of pages to one file
        for (int pageNum = 1; pageNum <= totalPages; pageNum += splitSizes.get(split - 1)) {
            String outFile = System.getProperty("user.home") + "\\Desktop\\Scan Folder\\Temp PDFs\\temp_"
                    + split + ".pdf";
            Document document = new Document(pReader.getPageSizeWithRotation(pageNum));
            PdfCopy writer = new PdfCopy(document, new FileOutputStream(outFile));
            document.open();
            int tempPageCount = 0;
            for (int pN = 0; pN < splitSizes.get(split); pN++) {
                PdfImportedPage page = writer.getImportedPage(pReader, pageNum + pN);
                writer.addPage(page);
                tempPageCount++;
            }

            System.out.println("pageNum: " + pageNum + "     splitSizes.get(split): " + splitSizes.get(split));

            document.close();
            /*
             * The following will trigger the PDF file being written to the
             * system
             */

            writer.close();

            crop(outFile, fileName, split, verFlag);

            System.out.println("Split: [" + tempPageCount + " page]: " + outFile);
            split++;
            verFlag = !verFlag; // alternating to determine the cropped orientation of the PDF
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null, "There was an error while splitting up\n" + "the PDF.", "Error!",
                JOptionPane.OK_OPTION);
        System.exit(0);
    }
}

From source file:Separator.java

License:Apache License

public static void crop(String inFileName, String outFileName, int split, boolean vert) throws Exception {

    PdfReader reader = new PdfReader(new File(inFileName).getAbsolutePath());
    String PDFName = outFileName.substring(outFileName.lastIndexOf("Folder\\") + 7,
            outFileName.indexOf(".pdf"));
    File fn = new File(scanFolder + PDFName + "\\" + PDFName + "_split_" + split + ".pdf");
    fn.getParentFile().mkdirs();//w  w  w. java 2 s.  c o m

    int count = reader.getNumberOfPages();
    Document doc = new Document();
    PdfCopy copy = new PdfCopy(doc, new FileOutputStream(fn.getAbsolutePath()));
    doc.open();
    if (vert) {
        for (int i = 1; i <= count; i++) {
            reader.getPageN(i).put(PdfName.CROPBOX, new PdfRectangle(PageSize.LETTER));
            copy.addPage(copy.getImportedPage(reader, i));
        }
    } else {
        if (!doubSided) {
            for (int j = 1; j <= count; j++) {
                reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle((new Rectangle(0, 180, 792, 792))));
                PdfDictionary pageDict;
                int rot = reader.getPageRotation(j);
                pageDict = reader.getPageN(j);
                pageDict.put(PdfName.ROTATE, new PdfNumber(rot + 90));
                copy.addPage(copy.getImportedPage(reader, j));
            }
        } else {
            for (int j = 1; j <= count; j++) {
                reader.getPageN(j).put(PdfName.CROPBOX, new PdfRectangle(new Rectangle(0, 180, 792, 792)));
                PdfDictionary pageDict;
                pageDict = reader.getPageN(j);
                if (j % 2 == 0) { // even
                    pageDict.put(PdfName.ROTATE, new PdfNumber(270));
                } else { // odd
                    pageDict.put(PdfName.ROTATE, new PdfNumber(90));
                }
                copy.addPage(copy.getImportedPage(reader, j));
            }
        }
    }
    doc.close();
}

From source file:adams.flow.transformer.PDFExtract.java

License:Open Source License

/**
 * Executes the flow item.//  ww  w .  j a v  a  2 s  .com
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    File file;
    int i;
    Document document;
    PdfCopy copy;
    PdfReader reader;
    int[] pages;
    int page;
    FileOutputStream fos;

    result = null;

    // get file
    if (m_InputToken.getPayload() instanceof File)
        file = (File) m_InputToken.getPayload();
    else
        file = new PlaceholderFile((String) m_InputToken.getPayload());

    fos = null;
    try {
        if (isLoggingEnabled())
            getLogger().info("Extracting pages from '" + file + "' into '" + m_Output + "'");
        document = new Document();
        fos = new FileOutputStream(m_Output.getAbsolutePath());
        copy = new PdfCopy(document, fos);
        document.open();
        document.addCreationDate();
        document.addCreator(Environment.getInstance().getProject());
        document.addAuthor(System.getProperty("user.name"));
        reader = new PdfReader(file.getAbsolutePath());
        if (isLoggingEnabled())
            getLogger().info("- #pages: " + reader.getNumberOfPages());
        m_Pages.setMax(reader.getNumberOfPages());
        pages = m_Pages.getIntIndices();
        for (i = 0; i < pages.length; i++) {
            page = pages[i] + 1;
            copy.addPage(copy.getImportedPage(reader, page));
            if (isLoggingEnabled())
                getLogger().info("- adding page: " + page);
        }
        copy.freeReader(reader);
        document.close();
    } catch (Exception e) {
        result = handleException("Failed to extract pages: ", e);
    } finally {
        FileUtils.closeQuietly(fos);
    }

    if (result == null)
        m_OutputToken = new Token(m_Output.getAbsolutePath());

    return result;
}

From source file:adams.flow.transformer.PDFMerge.java

License:Open Source License

/**
 * Executes the flow item.//from w  w  w.  j a v a2 s  .  co  m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    PlaceholderFile[] files;
    int i;
    int n;
    int pages;
    Document document;
    PdfCopy copy;
    PdfReader reader;
    FileOutputStream fos;

    result = null;

    // get files
    files = FileUtils.toPlaceholderFileArray(m_InputToken.getPayload());

    fos = null;
    try {
        if (isLoggingEnabled())
            getLogger().info("Merging PDFs into: " + m_Output);
        document = new Document();
        fos = new FileOutputStream(m_Output.getAbsolutePath());
        copy = new PdfCopy(document, fos);
        document.open();
        document.addCreationDate();
        document.addCreator(Environment.getInstance().getProject());
        document.addAuthor(System.getProperty("user.name"));
        for (i = 0; i < files.length; i++) {
            if (isLoggingEnabled())
                getLogger().info("Adding file: " + files[i]);
            reader = new PdfReader(files[i].getAbsolutePath());
            // loop over the pages in that document
            pages = reader.getNumberOfPages();
            if (isLoggingEnabled())
                getLogger().info("- #pages: " + pages);
            for (n = 1; n <= pages; n++) {
                copy.addPage(copy.getImportedPage(reader, n));
                if (isLoggingEnabled())
                    getLogger().info("- adding page: " + n);
            }
            copy.freeReader(reader);
        }
        document.close();
    } catch (Exception e) {
        result = handleException("Failed to merge PDF files: ", e);
    } finally {
        FileUtils.closeQuietly(fos);
    }

    if (result == null)
        m_OutputToken = new Token(m_Output.getAbsolutePath());

    return result;
}

From source file:be.rheynaerde.pufmanager.gui.workers.ExportFullPdfWorker.java

License:Open Source License

private void addPdfToDocument(ByteArrayOutputStream baos, PdfCopy copy, String stampText)
        throws IOException, BadPdfFormatException {
    PdfReader reader = new PdfReader(new ByteArrayInputStream(baos.toByteArray()));
    int n = reader.getNumberOfPages();
    for (int page = 1; page <= n; page++) {
        PdfImportedPage importedPage = copy.getImportedPage(reader, page);
        PdfCopy.PageStamp stamp = copy.createPageStamp(importedPage);
        Rectangle rectangle = importedPage.getBoundingBox();
        ColumnText.showTextAligned(stamp.getUnderContent(), Element.ALIGN_RIGHT, new Phrase(stampText),
                rectangle.getRight() - 20f, rectangle.getTop() - 20f, 0);
        stamp.alterContents();/*from ww  w.  j ava  2  s . c  o  m*/
        copy.addPage(importedPage);
    }
}

From source file:be.roots.taconic.pricingguide.util.iTextUtil.java

License:Open Source License

public static byte[] merge(byte[]... pdfAsBytes) throws DocumentException, IOException {

    try (final ByteArrayOutputStream copyBaos = new ByteArrayOutputStream()) {
        final Document doc = new Document();
        final PdfCopy copy = new PdfSmartCopy(doc, copyBaos);

        doc.open();//from w  ww  .j  a  va 2  s . c o  m

        int numberOfPages = 0;
        final java.util.List<HashMap<String, Object>> bookmarks = new ArrayList<>();
        PdfReader pdf = null;
        for (byte[] pdfAsByte : pdfAsBytes) {

            if (pdfAsByte != null && pdfAsByte.length > 0) {
                pdf = new PdfReader(pdfAsByte);
                pdf.consolidateNamedDestinations();
                final List<HashMap<String, Object>> pdfBookmarks = SimpleBookmark.getBookmark(pdf);
                if (!CollectionUtils.isEmpty(pdfBookmarks)) {
                    SimpleBookmark.shiftPageNumbers(pdfBookmarks, numberOfPages, null);
                    bookmarks.addAll(pdfBookmarks);
                }

                for (int i = 1; i <= pdf.getNumberOfPages(); i++) {
                    copy.addPage(copy.getImportedPage(pdf, i));
                }
                numberOfPages += pdf.getNumberOfPages();
            }

        }
        if (pdf != null) {
            SimpleNamedDestination.getNamedDestination(pdf, false);
        }

        if (!CollectionUtils.isEmpty(bookmarks)) {
            copy.setOutlines(bookmarks);
        }

        copy.close();
        return copyBaos.toByteArray();
    }
}

From source file:be.roots.taconic.pricingguide.util.iTextUtil.java

License:Open Source License

public static byte[] organize(byte[] pdf, Toc tableOfContents) throws IOException, DocumentException {

    try (final ByteArrayOutputStream copyBaos = new ByteArrayOutputStream()) {

        final Document doc = new Document();
        final PdfCopy copy = new PdfSmartCopy(doc, copyBaos);

        final PdfReader reader = new PdfReader(pdf);
        reader.selectPages(tableOfContents.getPageSequence());

        doc.open();// w ww .  j a v a  2s.  c  o  m

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            copy.addPage(copy.getImportedPage(reader, i));
        }

        reader.close();
        copy.close();
        return copyBaos.toByteArray();
    }

}

From source file:com.betel.flowers.pdf.util.RemoveBlankPageFromPDF.java

public static void removeBlankPdfPages(String source, String destination)
        throws IOException, DocumentException {
    PdfReader r = null;/*www  . j  a  va 2 s . c o m*/
    RandomAccessSourceFactory rasf = null;
    RandomAccessFileOrArray raf = null;
    Document document = null;
    PdfCopy writer = null;

    try {
        r = new PdfReader(source);
        // deprecated
        //    RandomAccessFileOrArray raf
        //           = new RandomAccessFileOrArray(pdfSourceFile);
        // itext 5.4.1
        rasf = new RandomAccessSourceFactory();
        raf = new RandomAccessFileOrArray(rasf.createBestSource(source));
        document = new Document(r.getPageSizeWithRotation(1));
        writer = new PdfCopy(document, new FileOutputStream(destination));
        document.open();
        PdfImportedPage page = null;

        for (int i = 1; i <= r.getNumberOfPages(); i++) {
            // first check, examine the resource dictionary for /Font or
            // /XObject keys.  If either are present -> not blank.
            PdfDictionary pageDict = r.getPageN(i);
            PdfDictionary resDict = (PdfDictionary) pageDict.get(PdfName.RESOURCES);
            boolean noFontsOrImages = true;
            if (resDict != null) {
                noFontsOrImages = resDict.get(PdfName.FONT) == null && resDict.get(PdfName.XOBJECT) == null;
            }

            if (!noFontsOrImages) {
                byte bContent[] = r.getPageContent(i, raf);
                ByteArrayOutputStream bs = new ByteArrayOutputStream();
                bs.write(bContent);

                if (bs.size() > BLANK_THRESHOLD) {
                    page = writer.getImportedPage(r, i);
                    writer.addPage(page);
                }
            }
        }
    } finally {
        if (document != null) {
            document.close();
        }
        if (writer != null) {
            writer.close();
        }
        if (raf != null) {
            raf.close();
        }
        if (r != null) {
            r.close();
        }
    }
}

From source file:com.docdoku.server.extras.TitleBlockGenerator.java

License:Open Source License

public static InputStream mergePdfDocuments(InputStream input1, InputStream input2) {

    try {//ww  w. jav  a 2  s . c  o  m
        File tmpDir = com.google.common.io.Files.createTempDir();
        File tmpCopyFile = new File(tmpDir, TEMP_FILE_NAME);
        InputStream[] files = { input1, input2 };

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, new FileOutputStream(tmpCopyFile));
        doc.open();
        PdfReader pdfReader;

        int n;
        // TODO check for resources to be closed
        for (InputStream file : files) {
            pdfReader = new PdfReader(file);
            n = pdfReader.getNumberOfPages();
            for (int page = 0; page < n;) {
                copy.addPage(copy.getImportedPage(pdfReader, ++page));
            }
        }

        doc.close();

        tmpDir.deleteOnExit();

        return new FileInputStream(tmpCopyFile);
    } catch (Exception e) {
        LOGGER.log(Level.INFO, null, e);
    }

    return null;
}

From source file:com.github.sgelb.sldownloader.model.Pdf.java

License:Open Source License

public void mergePdfs() throws DocumentException, IOException {
    String title = book.getPdfTitle() + ".pdf";
    File saveFile = new File(saveFolder, title);

    int count = 1;
    while (saveFile.exists()) {
        title = book.getPdfTitle() + "_" + count++ + ".pdf";
        saveFile = new File(saveFolder, title);
    }/*w  ww . java  2 s  .  com*/
    book.setInfo("saveFile", saveFile.toString());

    Document document = new Document();
    PdfCopy destPdf = new PdfCopy(document, new FileOutputStream(saveFile));
    document.open();
    PdfReader reader;
    int page_offset = 0;
    int n;
    ArrayList<HashMap<String, Object>> bookmarks = new ArrayList<HashMap<String, Object>>();
    List<HashMap<String, Object>> tmp;

    count = 1;
    System.out.println("Start mergin\u2026");
    for (File srcPdf : src) {

        if (Thread.interrupted()) {
            return;
        }

        System.out.print(":: " + count++ + "/" + src.size());
        reader = new PdfReader(srcPdf.toString());

        tmp = SimpleBookmark.getBookmark(reader);
        if (tmp != null) {
            SimpleBookmark.shiftPageNumbers(tmp, page_offset, null);
            bookmarks.addAll(tmp);
        }

        n = reader.getNumberOfPages();
        page_offset += n;
        for (int page = 0; page < n;) {
            destPdf.addPage(destPdf.getImportedPage(reader, ++page));
        }
        destPdf.freeReader(reader);
        reader.close();
        System.out.println(" succeed.");
    }
    if (!bookmarks.isEmpty()) {
        destPdf.setOutlines(bookmarks);
    }

    if (book.getInfo("author") != null)
        document.addAuthor(book.getInfo("author"));
    if (book.getInfo("title") != null)
        document.addTitle(book.getInfo("title"));
    if (book.getInfo("subtitle") != null)
        document.addSubject(book.getInfo("subtitle"));
    document.close();

    System.out.println("Merge complete. Saved to " + saveFile);
}