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

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

Introduction

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

Prototype

public void addPage(PdfImportedPage iPage) throws IOException, BadPdfFormatException 

Source Link

Document

Add an imported page to our output

Usage

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

public void pdfSplitDropSupplierDoc(File[] files) throws IOException, DocumentException {
    // TODO Instead of hard code path, pass in as argument

    String path;// w ww .  ja va  2 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("."));
        System.out.println(fileNameWithoutExt);
        PdfReader pdfFileReader = new PdfReader(file.getPath());
        Document document = new Document(PageSize.LETTER, 0, 0, 0,
                0); /* instantiates a new document to be made */
        // 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
        // Split on a space '\s'
        String[] fileNames = fileNameWithoutExt.split("-");

        String fileNameFirst = fileNames[1];
        String fileNameSecond = fileNames[2];
        System.out.println("First lot number: " + fileNameFirst + " Second lot number: " + fileNameSecond);
        // Project num is always the 1st part
        String projectNum = fileNames[0];
        if (!projectNum.equals(fileNames[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(fileNameFirst);
        secondLotNum = Integer.parseInt(fileNameSecond);
        int numPages = secondLotNum - firstLotNum;
        // Create a copy of the orignal source file. We will pick specific pages out below
        document.open();
        for (int j = 1; j < numPages + 1; j++) {
            String FileName = projectNum + "-" + (firstLotNum) + ".pdf"; /* Dynamic file name */
            firstLotNum++;
            document = new Document(PageSize.LETTER, 0, 0, 0, 0);
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(path + "\\" + FileName));
            document.open();
            copy.addPage(copy.getImportedPage(pdfFileReader, j)); /* Import pages from original document */

            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();
        }
    }
}

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;
        }/*from w  w w . j a  v  a2s  . c  o  m*/

        // 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.wabacus.system.assistant.PdfAssistant.java

License:Open Source License

public void addPdfPageToDocument(PdfCopy pdfCopy, ByteArrayOutputStream baos) {
    if (baos == null)
        return;/*  w w  w.ja  v  a 2 s .co  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 ww . ja  v  a 2 s. co  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;
}

From source file:de.mat.utils.pdftools.PdfExtractEmptyPages.java

License:Mozilla Public License

/**
 * <h4>FeatureDomain:</h4>/*w ww .ja  v a 2s. com*/
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     reads readerOrig and adds pages to writerRemoved if empty, or to 
 *     writerTrimmed if not empty
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>updates writerTrimmed - add all pages which are not empty
 *     <li>updates writerRemoved - add all empty pages
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param origFileName - orig filename of the sourcepdf
 * @param readerOrig - reader of source
 * @param writerTrimmed - writer for trimmed pages
 * @param writerRemoved - writer for empty pages
 * @param flgTrim - ??
 * @return - count of trimmed pages
 * @throws Exception
 */
public static int addTrimmedPages(String origFileName, PdfReader readerOrig, PdfCopy writerTrimmed,
        PdfCopy writerRemoved, boolean flgTrim) throws Exception {
    PdfImportedPage page = null;
    int countTrimmedPages = 0;

    //loop each page
    for (int i = 1; i <= readerOrig.getNumberOfPages(); i++) {
        boolean flgIsEmpty = true;

        // get dictionary
        PdfDictionary pageDict = readerOrig.getPageN(i);

        // every pdf-version has its own way :-(
        char version = readerOrig.getPdfVersion();

        if (version == '3') {
            // PDF-Version: 3

            // examine the resource dictionary for /Font or
            // /XObject keys.  If either are present, they're almost
            // certainly actually used on the page -> not blank.
            PdfObject myObj = pageDict.get(PdfName.RESOURCES);
            PdfDictionary resDict = null;
            if (myObj instanceof PdfDictionary) {
                resDict = (PdfDictionary) myObj;
            } else {
                resDict = (PdfDictionary) PdfReader.getPdfObject(myObj);
            }
            if (resDict != null) {
                flgIsEmpty = resDict.get(PdfName.FONT) == null && resDict.get(PdfName.XOBJECT) == null;
                if (LOGGER.isInfoEnabled()) {
                    if (flgIsEmpty) {
                        LOGGER.info("probably empty page " + i + " Version: 1." + version
                                + " FONT/XOBJECT found in File:" + origFileName);
                    } else {
                        LOGGER.info("normal page " + i + " Version: 1." + version
                                + " no FONT/XOBJECT found in File:" + origFileName);
                    }
                }
            }
        } else if (version == '4') {
            // PDF-Version: 4
            // check the contentsize.

            // get the page content
            byte bContent[] = readerOrig.getPageContent(i);
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            // write the content to an output stream
            bs.write(bContent);

            flgIsEmpty = true;
            if (bs.size() > blankPdfsize) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("normal page " + i + " Version: 1." + version + " BS:" + bs.size() + " File:"
                            + origFileName);
                flgIsEmpty = false;
            } else {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("probably empty page " + i + " Version: 1." + version + " BS:" + bs.size()
                            + " File:" + origFileName);
            }
        } else if (version == '5') {
            // PDF-Version: 5
            // check the contentsize.

            // get the page content
            byte bContent[] = readerOrig.getPageContent(i);
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            // write the content to an output stream
            bs.write(bContent);

            flgIsEmpty = true;
            if (bs.size() > blankPdfsize_v5) {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("normal page " + i + " Version: 1." + version + " BS:" + bs.size() + " File:"
                            + origFileName);
                flgIsEmpty = false;
            } else {
                if (LOGGER.isInfoEnabled())
                    LOGGER.info("probably empty page " + i + " Version: 1." + version + " BS:" + bs.size()
                            + " File:" + origFileName);
            }
        }

        // add page to removed or trimmed document
        if (!flgIsEmpty || !flgTrim) {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("add page " + i);
            page = writerTrimmed.getImportedPage(readerOrig, i);
            writerTrimmed.addPage(page);
            countTrimmedPages++;
        } else {
            if (LOGGER.isInfoEnabled())
                LOGGER.info("skip page " + i + " Version: 1." + version + " File:" + origFileName);
            if (writerRemoved != null) {
                page = writerRemoved.getImportedPage(readerOrig, i);
                writerRemoved.addPage(page);
            }
        }
    }

    return countTrimmedPages;
}

From source file:de.mat.utils.pdftools.PdfSort4Print.java

License:Mozilla Public License

public static void sortPdfPages(String pdfSourceFile, String pdfDestinationFile, int perPage) throws Exception {
    PdfImportedPage page = null;/*from   w w  w .ja  v a2  s .  co  m*/

    if (perPage != 2 && perPage != 4) {
        throw new IllegalArgumentException(
                "Sorry, perPage must only be " + "2 or 4. All other is not implemented yet :-(");
    }

    // #######
    // # fill to odd pagecount
    // #######

    // create reader
    PdfReader readerOrig = new PdfReader(pdfSourceFile);

    // calc data
    int countPage = readerOrig.getNumberOfPages();
    int blaetter = new Double(Math.ceil((countPage + 0.0) / perPage / 2)).intValue();
    int zielPages = (blaetter * perPage * 2) - countPage;

    if (LOGGER.isInfoEnabled())
        LOGGER.info("CurPages: " + countPage + " Blaetter:" + blaetter + " AddPage:" + zielPages);

    // add sites
    String oddFile = pdfDestinationFile + ".filled.pdf";
    PdfStamper stamper = new PdfStamper(readerOrig, new FileOutputStream(oddFile));
    // add empty pages
    for (int i = 1; i <= zielPages; i++) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("addEmptyPage: " + i);
        stamper.insertPage(readerOrig.getNumberOfPages() + 1, readerOrig.getPageSizeWithRotation(1));
    }
    stamper.close();
    readerOrig.close();

    // ########
    // # read new odd document and sort pages
    // ########
    // step 1: create new reader
    PdfReader readerOdd = new PdfReader(oddFile);

    // create writerSorted
    String sortedFile = pdfDestinationFile;
    Document documentSorted = new Document(readerOrig.getPageSizeWithRotation(1));
    PdfCopy writerSorted = new PdfCopy(documentSorted, new FileOutputStream(sortedFile));
    documentSorted.open();

    // add pages in calced order
    List<Integer> lstPageNr = new ArrayList<Integer>();
    int pageCount = readerOdd.getNumberOfPages();
    int startseite = 1;
    for (int i = 1; i <= blaetter; i++) {
        if (perPage == 2) {
            startseite = ((i - 1) * perPage) + 1;

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Blatt:" + i + " Startseite: " + startseite);
            // front top
            lstPageNr.add(new Integer(pageCount - startseite + 1));
            // front bottom
            lstPageNr.add(new Integer(startseite));

            // back top
            lstPageNr.add(new Integer(startseite + 1));
            // back bottom
            lstPageNr.add(new Integer(pageCount - startseite + 1 - 1));
        } else if (perPage == 4) {
            startseite = ((i - 1) * perPage) + 1;

            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Blatt:" + i + " Startseite: " + startseite);

            // front top left
            lstPageNr.add(new Integer(pageCount - startseite + 1));
            // front top right
            lstPageNr.add(new Integer(startseite));
            // front bottom lefts
            lstPageNr.add(new Integer(pageCount - startseite + 1 - 2));
            // front bottom right
            lstPageNr.add(new Integer(startseite + 2));

            // back top left
            lstPageNr.add(new Integer(startseite + 1));
            // back top right
            lstPageNr.add(new Integer(pageCount - startseite + 1 - 1));
            // back bottom left
            lstPageNr.add(new Integer(startseite + 1 + 2));
            // back bottom right
            lstPageNr.add(new Integer(pageCount - startseite + 1 - 1 - 2));
        } else {
            throw new IllegalArgumentException(
                    "Sorry, perPage must " + "only be 2 or 4. All other is not implemented yet :-(");
        }
    }
    if (LOGGER.isInfoEnabled())
        LOGGER.info("Seiten:" + lstPageNr.size());

    // copy pages
    for (Iterator iter = lstPageNr.iterator(); iter.hasNext();) {
        int pageNum = ((Integer) iter.next()).intValue();
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("addSortPage: " + pageNum);
        page = writerSorted.getImportedPage(readerOdd, pageNum);
        writerSorted.addPage(page);
    }

    // close everything
    documentSorted.close();
    writerSorted.close();
    readerOdd.close();

    // delete Tmp-File
    File file = new File(oddFile);
    file.delete();
}

From source file:edu.clemson.lph.civet.CVIFileController.java

License:Open Source License

/**
 * From the current pdfDecoder, extract the page(s) in aPagesInCurrent to a new pdfData buffer as output stream.
 * @param aPages int[]//from  www . jav a 2 s  . co m
 * @return byte[]
 */
public byte[] extractPagesToNewPDF() {
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    try {
        byte[] pdfDataIn = rawPdfBytes;
        PdfReader reader = new PdfReader(pdfDataIn);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        PdfCopy writer = new PdfCopy(document, baOut);
        document.open();
        for (Integer iPage : aPagesInCurrent) {
            PdfImportedPage pip = writer.getImportedPage(reader, iPage.intValue());
            writer.addPage(pip);
        }
        document.close();
    } catch (IOException ioe) {
        logger.info("IO error extracting pages to byte array", ioe);
        return rawPdfBytes;
    } catch (DocumentException de) {
        logger.info(de.getMessage() + "\nDocument error extracting pages to byte array");
        return rawPdfBytes;
    }
    return baOut.toByteArray();
}

From source file:edu.clemson.lph.pdfgen.MergePDF.java

License:Open Source License

public static void concatPDFs(List<InputStream> pdfInputStreams, OutputStream outputStream, boolean paginate) {
    Document document = new Document();
    try {/*from  ww  w .j  a v a 2  s  .  co  m*/
        PdfCopy cp = new PdfCopy(document, outputStream);
        document.open();
        Iterator<InputStream> iteratorPDFReader = pdfInputStreams.iterator();

        // Loop through the PDF streams and add to the output.
        while (iteratorPDFReader.hasNext()) {
            InputStream is = iteratorPDFReader.next();
            PdfReader pdfReader = new PdfReader(is);
            int n = pdfReader.getNumberOfPages();
            for (int pageNo = 0; pageNo < n;) {
                pdfReader.getPageN(pageNo);
                cp.addPage(cp.getImportedPage(pdfReader, ++pageNo));
            }
        }
        document.close();
        outputStream.flush();
        outputStream.close();
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:edu.clemson.lph.pdfgen.PDFUtils.java

License:Open Source License

/**
 * Given an array of bytes from a PDF determine whether at least the first page can be extracted
 * by iText;/* w w w. jav a  2  s . c o  m*/
 * @param byte[] data to test parse
 * @return byte[]
 */
public static boolean canExtractPages(byte[] pdfDataIn) {
    boolean bRet = false;
    ByteArrayOutputStream baOut = new ByteArrayOutputStream();
    try {
        PdfReader reader = new PdfReader(pdfDataIn);
        com.itextpdf.text.Document document = new com.itextpdf.text.Document();
        PdfCopy writer = new PdfCopy(document, baOut);
        document.open();
        PdfImportedPage pip = writer.getImportedPage(reader, 1);
        writer.addPage(pip);
        document.close();
        byte[] pdfDataOut = baOut.toByteArray();
        int iLen = pdfDataOut.length;
        if (iLen > 0)
            bRet = true;
    } catch (IOException ioe) {
        logger.error(ioe.getMessage() + "\nIO error extracting pages to byte array\n");
        bRet = false;
    } catch (DocumentException de) {
        logger.error(de.getMessage() + "\nDocument error extracting pages to byte array");
        bRet = false;
    }
    return bRet;
}

From source file:eu.mrbussy.pdfsplitter.Application.java

License:Open Source License

/**
 * Split the given PDF file into multiple files using pages.
 * /*from w  w w . j  a va  2  s.c  o  m*/
 * @param filename
 *            - Name of the PDF to split
 * @param useSubFolder
 *            - Use a separate folder to place the files in.
 */
public static void SplitFile(File file, boolean useSubFolder) {
    PdfReader reader = null;
    String format = null;

    if (useSubFolder)
        format = "%1$s%2$s%4$s%2$s_%%03d.%3$s";
    else
        format = "%1$s%2$s_%%03d.%3$s";

    String splitFile = String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
            FilenameUtils.getBaseName(file.getAbsolutePath()),
            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR);

    try {
        reader = new PdfReader(new FileInputStream(file));

        if (reader.getNumberOfPages() > 0) {
            for (int pageNum = 1; pageNum <= reader.getNumberOfPages(); pageNum++) {
                System.out.println(String.format(splitFile, pageNum));
                String filename = String.format(splitFile, pageNum);
                Document document = new Document(reader.getPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(filename));
                document.open();
                // Copy the page from the original
                PdfImportedPage page = writer.getImportedPage(reader, pageNum);
                writer.addPage(page);
                document.close();
                writer.close();
            }
        }
    } catch (Exception ex) {
        // TODO Implement exception handling
        ex.printStackTrace(System.err);
    } finally {
        if (reader != null)
            // Always close the stream
            reader.close();
    }
}