Example usage for com.itextpdf.text.pdf PdfSmartCopy PdfSmartCopy

List of usage examples for com.itextpdf.text.pdf PdfSmartCopy PdfSmartCopy

Introduction

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

Prototype

public PdfSmartCopy(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Creates a PdfSmartCopy instance.

Usage

From source file:at.laborg.briss.CropManager.java

License:Open Source License

private static File copyToMultiplePages(CropJob cropJob) throws IOException, DocumentException {

    PdfReader reader = new PdfReader(cropJob.getSource().getAbsolutePath());
    Document document = new Document();

    File resultFile = File.createTempFile("cropped", ".pdf");
    PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile));
    document.open();//  ww w  .  j a  v  a 2 s.com
    PdfImportedPage page;

    for (int pageNumber = 1; pageNumber <= cropJob.getSourcePageCount(); pageNumber++) {
        SingleCluster currentCluster = cropJob.getClusterCollection().getSingleCluster(pageNumber);
        page = pdfCopy.getImportedPage(reader, pageNumber);
        pdfCopy.addPage(page);
        for (int j = 1; j < currentCluster.getRatiosList().size(); j++) {
            pdfCopy.addPage(page);
        }
    }
    document.close();
    pdfCopy.close();
    reader.close();
    return resultFile;
}

From source file:at.laborg.briss.utils.DocumentCropper.java

License:Open Source License

private static File copyToMultiplePages(final CropDefinition cropDefinition,
        final PdfMetaInformation pdfMetaInformation) throws IOException, DocumentException {

    PdfReader reader = new PdfReader(cropDefinition.getSourceFile().getAbsolutePath());
    HashMap<String, String> map = SimpleNamedDestination.getNamedDestination(reader, false);
    Document document = new Document();

    File resultFile = File.createTempFile("cropped", ".pdf");
    PdfSmartCopy pdfCopy = new PdfSmartCopy(document, new FileOutputStream(resultFile));
    document.open();//  w w w .  ja v  a  2  s . c o m

    Map<Integer, List<String>> pageNrToDestinations = new HashMap<Integer, List<String>>();
    for (String single : map.keySet()) {
        StringTokenizer st = new StringTokenizer(map.get(single), " ");
        if (st.hasMoreElements()) {
            String pageNrString = (String) st.nextElement();
            int pageNr = Integer.parseInt(pageNrString);
            List<String> singleList = (pageNrToDestinations.get(pageNr));
            if (singleList == null) {
                singleList = new ArrayList<String>();
                singleList.add(single);
                pageNrToDestinations.put(pageNr, singleList);
            } else {
                singleList.add(single);
            }
        }
    }

    int outputPageNumber = 0;
    for (int pageNumber = 1; pageNumber <= pdfMetaInformation.getSourcePageCount(); pageNumber++) {

        PdfImportedPage pdfPage = pdfCopy.getImportedPage(reader, pageNumber);

        pdfCopy.addPage(pdfPage);
        outputPageNumber++;
        List<String> destinations = pageNrToDestinations.get(pageNumber);
        if (destinations != null) {
            for (String destination : destinations)
                pdfCopy.addNamedDestination(destination, outputPageNumber,
                        new PdfDestination(PdfDestination.FIT));
        }
        List<Float[]> rectangles = cropDefinition.getRectanglesForPage(pageNumber);
        for (int j = 1; j < rectangles.size(); j++) {
            pdfCopy.addPage(pdfPage);
            outputPageNumber++;
        }
    }
    document.close();
    pdfCopy.close();
    reader.close();
    return resultFile;
}

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();//  ww  w . ja  v a  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 a2s.  c om

        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.github.hossman.PdfShrinker.java

License:Apache License

public static void main(String args[]) throws Exception {
    if (1 != args.length) {
        System.err.println("Run this app with a single command line PDF filename");
        System.err.println("The specified file will be read, and a shrunk version written to stdout");
        System.err.println("ie:   java -jar pdf-shrinker.jar big.pdf > small.pdf");
        System.exit(-1);//  w w  w.  j  a  v  a 2 s  . co  m
    }

    Document document = new Document();
    PdfSmartCopy copy = new PdfSmartCopy(document, System.out);
    copy.setCompressionLevel(9);
    copy.setFullCompression();
    document.open();
    PdfReader reader = new PdfReader(args[0]);
    List<HashMap<String, Object>> bookmarks = SimpleBookmark.getBookmark(reader);
    int pages = reader.getNumberOfPages();
    for (int i = 0; i < pages; i++) {
        PdfImportedPage page = copy.getImportedPage(reader, i + 1);
        copy.addPage(page);
    }
    copy.freeReader(reader);
    reader.close();
    copy.setOutlines(bookmarks);
    document.close();
}

From source file:com.preselect.pdfservice.tasks.PdfConversionTask.java

License:Open Source License

private static void copyDocument(PdfReader reader, int start, int end, String path, OutlineItems outline)
        throws IOException, DocumentException {
    Document document = new Document();
    PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(path));

    document.open();/*from ww  w .ja  va2s.co m*/
    for (int i = (start - 1); i <= (end - 1);) {
        copy.addPage(copy.getImportedPage(reader, ++i));
    }
    List<OutlineItem> outlineForChapter = getOutlineBetweenPages(outline, start, end);
    Iterator<OutlineItem> iterator = outlineForChapter.iterator();
    if (iterator.hasNext()) {
        List<HashMap<String, Object>> bookmarksForChapter = getBookmarks(iterator.next(), iterator, 1);
        SimpleBookmark.shiftPageNumbers(bookmarksForChapter, (-start + 1), null);
        copy.setOutlines(bookmarksForChapter);
    }
    if (outlineForChapter.size() > 0) {
        OutlineItem firstOutline = outlineForChapter.get(0);
        document.addTitle(firstOutline.getTitle());
    }
    document.addCreator("Content Select");
    document.close();
    copy.close();
}

From source file:de.offis.health.icardea.cied.pdf.extractor.PDFiText5Extractor.java

License:GNU General Public License

public byte[] getPDFPages(int fromPageNumber, int toPageNumber) {
    ByteArrayOutputStream byteArrayOutputStream = null;
    boolean extractionSuccessful = false;

    if (pdfReader != null) {
        int numberOfPages = getNumberOfPages();

        /*//from  w ww  .j av  a2  s.c o  m
         * Check if the given page numbers are in the allowed range.
         */
        if (fromPageNumber > 0 && fromPageNumber <= numberOfPages && toPageNumber > 0
                && toPageNumber <= numberOfPages) {
            /*
             * Now check if the given fromPageNumber is smaller
             * as the given toPageNumber. If not swap the numbers.
             */
            if (fromPageNumber > toPageNumber) {
                int tmpPageNumber = toPageNumber;
                toPageNumber = fromPageNumber;
                fromPageNumber = tmpPageNumber;
            }

            Document newDocument = new Document();

            try {
                byteArrayOutputStream = new ByteArrayOutputStream();
                PdfSmartCopy pdfCopy = new PdfSmartCopy(newDocument, byteArrayOutputStream);
                newDocument.open();
                for (int currentPage = fromPageNumber; currentPage <= toPageNumber; currentPage++) {
                    pdfCopy.addPage(pdfCopy.getImportedPage(pdfReader, currentPage));
                } // end for
                pdfCopy.flush();
                pdfCopy.close();
                newDocument.close();
                extractionSuccessful = true;
            } catch (DocumentException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } catch (IOException ex) {
                // TODO: Create an own exception for PDF processing errors.
                logger.error("An exception occurred while extracting " + "pages from the input PDF file.", ex);
            } finally {
                if (!extractionSuccessful) {
                    byteArrayOutputStream = null;
                }
            } // end try..catch..finally
        } // end if checking range of given pages
    } // end if (pdfReader != null)

    if (byteArrayOutputStream != null) {
        return byteArrayOutputStream.toByteArray();
    }
    return null;
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ?/*  w  w  w .jav a  2 s  . co m*/
 * <p>
 * ? iText in Action 2nd EditionChapter 6: Working with existing PDFs
 * Concatenate
 * </p>
 *
 * @param files  ?
 * @param result ??
 * @throws DocumentException
 * @throws java.io.IOException
 */
public static void merge(File[] files, File result) throws DocumentException, IOException {
    // step 1
    Document document = new Document();
    // step 2

    /**
     * PdfCopy  PdfSmartCopy 
     *
     * PdfCopy???
     *
     * PdfSmartCopy??????
     */
    //
    // PdfCopy copy = new PdfCopy(document, new FileOutputStream(result));
    PdfSmartCopy copy = new PdfSmartCopy(document, new FileOutputStream(result));
    // step 3
    document.open();
    // step 4
    PdfReader reader;
    int n;
    // loop over the documents you want to concatenate
    for (int i = 0; i < files.length; i++) {
        reader = getPdfReader(files[i]);
        // loop over the pages in that document
        n = reader.getNumberOfPages();
        for (int page = 0; page < n;) {
            copy.addPage(copy.getImportedPage(reader, ++page));
        }
        copy.freeReader(reader);
    }
    // step 5
    document.close();
}

From source file:org.sejda.impl.itext5.component.AbstractPdfCopier.java

License:Open Source License

/**
 * initialize the copier using the given reader and the given output version.
 * //from   www  .ja v  a 2 s  .co m
 * @param reader
 * @param outputStream
 *            the output stream to write to.
 * @param version
 *            version for the created pdf copy, if null the version number is taken from the input {@link PdfReader}
 */
void init(PdfReader reader, OutputStream outputStream, PdfVersion version) throws TaskException {
    try {
        pdfDocument = new Document(reader.getPageSizeWithRotation(1));
        pdfCopy = new PdfSmartCopy(pdfDocument, outputStream);
        if (version == null) {
            pdfCopy.setPdfVersion(reader.getPdfVersion());
        } else {
            pdfCopy.setPdfVersion(version.getVersionAsCharacter());
        }
        pdfDocument.addCreator(Sejda.CREATOR);
    } catch (DocumentException e) {
        throw new TaskException("An error occurred opening the PdfSmartCopy.", e);
    }
}