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

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

Introduction

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

Prototype

public PdfCopy(Document document, OutputStream os) throws DocumentException 

Source Link

Document

Constructor

Usage

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

License:Open Source License

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

    if (useSubFolder) {
        format = "%1$s%2$s%4$s"; // Directory format
        try {
            FileUtils.forceMkdir(
                    new File(String.format(format, FilenameUtils.getFullPath(file.getAbsolutePath()),
                            FilenameUtils.getBaseName(file.getAbsolutePath()),
                            FilenameUtils.getExtension(file.getAbsolutePath()), IOUtils.DIR_SEPARATOR)));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        format = "%1$s%2$s%4$s%2$s_%%03d.%3$s"; // Directory format + filename
    } 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();
    }
}

From source file:fenix.planner.pdf.PDFGenerator.java

License:Open Source License

public void generate(OutputStream output) {
    final Rectangle pageSize = PageSize.A4;
    final ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();

    document = new Document(pageSize, LEFT_MARGIN, RIGHT_MARGIN, TOP_MARGIN, BOTTOM_MARGIN);
    try {/* w  w  w .  java 2s.c o  m*/
        final PdfWriter writer = PdfWriter.getInstance(document, outputBuffer);
        writer.setBoxSize("art", new Rectangle(ART_BOX_LEFT_MARGIN, ART_BOX_BOTTOM_MARGIN,
                pageSize.getRight() - ART_BOX_RIGHT_MARGIN, pageSize.getTop() - ART_BOX_TOP_MARGIN));
        writer.setPageEvent(new HeaderFooter());
        document.open();
        createAndAddForeword();
        createAndAddEventTable();
        createAndAddAfterword();
        createAndAddOrganizerTable();
        document.close();
        writer.close();

        // Loop through the document again to add the missing page numbers
        document = new Document();
        final PdfCopy copy = new PdfCopy(document, output);
        document.open();
        final PdfReader reader = new PdfReader(outputBuffer.toByteArray());
        addPageNumbers(reader, copy);
        document.close();
        reader.close();
    } catch (DocumentException | IOException ex) {
        throw new PDFGenerationException("Error generating PDF", ex);
    }
}

From source file:itextblast.ITextBlast.java

public static void splitByPage(String[] args) throws IOException, DocumentException {

    // use one of the previous examples to create a PDF
    // new MovieTemplates().createPdf(MovieTemplates.RESULT);
    // Create a reader; from current existing file
    // Next time pass it from args ..
    PdfReader reader = new PdfReader("./source/imokman.pdf");
    // We'll create as many new PDFs as there are pages
    Document document;//from  www . jav  a  2  s .  co  m
    PdfCopy copy;
    // loop over all the pages in the original PDF
    int n = reader.getNumberOfPages();
    for (int i = 0; i < n;) {
        // step 1
        document = new Document();
        // step 2
        copy = new PdfCopy(document, new FileOutputStream(String.format(RESULT, ++i)));
        // step 3
        document.open();
        // step 4
        copy.addPage(copy.getImportedPage(reader, i));
        // step 5
        document.close();
    }
    reader.close();
}

From source file:itextblast.ITextBlast.java

private static void copySelectedQuestionPage(int start_page, int end_page, String question_number)
        throws FileNotFoundException, DocumentException, IOException {

    Document document;/*from w  w w  .j av  a 2 s  .c om*/
    PdfCopy copy;
    document = new Document();
    copy = new PdfCopy(document, new FileOutputStream(
            String.format(ITextBlast.working_dir + RESULT, ITextBlast.qa_filename, question_number)));
    document.open();
    for (int i = start_page; i <= end_page; i++) {
        copy.addPage(copy.getImportedPage(ITextBlast.my_reader, i));
    }
    document.close();
}

From source file:Logic.AddCover1.java

/**
 * Manipulates a PDF file src with the file dest as result
 * @param src the original PDF/* w  w  w  . j a  va 2  s.  com*/
 * @param dest the resulting PDF
 * @throws IOException
 * @throws DocumentException
 */
public void manipulatePdf(String src, String dest, String cov) throws IOException, DocumentException {
    PdfReader cover = new PdfReader(cov);
    PdfReader reader = new PdfReader(src);
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));
    document.open();
    copy.addDocument(cover);
    copy.addDocument(reader);

    document.close();
    cover.close();
    reader.close();
}

From source file:mergevoucher.MainJFrame.java

private void deletePages(File file, String str) throws IOException, DocumentException {
    //open the old pdf file and open a blank new one 
    String fullFileName = file.getPath();
    //System.out.println(fullFileName);
    PdfReader reader = new PdfReader(fullFileName);
    Document document = new Document(reader.getPageSizeWithRotation(1));
    String out = fullFileName.replaceFirst(".pdf", "(new).pdf");
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(out));
    document.open();// www  . j av a 2s  . co  m
    int pdfPageNumber = reader.getNumberOfPages(); //get pdf page number
    //change pageNumber string to int array
    Boolean[] preservePages = getPages(pdfPageNumber, str);
    //copy pages except need delete to new pdf file
    for (int i = 1; i <= pdfPageNumber; i++) {
        //filter not preserve pages 
        if (preservePages[i]) { //if preserve,copy;else bypass
            //String content = PdfTextExtractor.getTextFromPage(reader, i); //?i;
            copy.addPage(copy.getImportedPage(reader, i));
        }
    }
    System.out.println("New pdf file is:" + fullFileName.replaceFirst(".pdf", "(new).pdf"));
    //close files 
    reader.close();
    document.close();
    copy.close();
}

From source file:nakpil.proccess.Form2316Process.java

@Override
public void run() {
    try {/* w w w.j  a  v  a2s. c  o m*/

        reset();

        if (Datas.size() > 1) {
            Bar.setMaximum(Datas.size());
            int i = 0;
            document = new com.itextpdf.text.Document();
            oStream_bulk = new FileOutputStream(Output_batch + File.separator + Datas.get(0).getSequenceID()
                    + "-" + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf");
            PDFcopy = new PdfCopy(document, oStream_bulk);
            document.open();
            PDialog.printResult("Starting Module Services.");
            for (BIRAccount Temp : Datas) {
                i++;
                Bar.setString("Encoding " + Temp.getFullname());

                //Open Template
                Template = new WorkBook();
                iStream = new FileInputStream(Source);
                Template.readXLSB(iStream);

                //Forming Data Encode
                BIR_Form = new Data2316();
                BIR_Form.setBIRAccount(Temp, Personel);
                BIR_Form.encodeTo(Template);

                //Prepare Pdf Output
                Output = ((Output.isEmpty())
                        ? System.getProperty("user.home") + File.separator + "Desktop" + File.separator
                                + "BIR2316" + File.separator + Temp.getTinNumber() + ".pdf"
                        : Output + File.separator + Temp.getTinNumber() + ".pdf");
                oStream = new FileOutputStream(Output);
                Bar.setString("Exporting PDF : " + Output);
                Template.exportPDF(oStream);

                //Close Exported PDF
                oStream.flush();
                oStream.close();
                oStream = null;

                //Patch Document
                PDFreader = new PdfReader(Output);
                PDFcopy.addDocument(PDFreader);
                PDFcopy.freeReader(PDFreader);
                PDFcopy.flush();

                //Close Copied PDF
                PDFreader.close();
                PDFreader = null;

                //Close Template
                Template.dispose();
                Template = null;
                iStream.close();
                iStream = null;

                Bar.setValue(i);
                PDialog.printResult(Temp.getFullname() + " Encoding completed...");
                System.gc();
            }
            PDFcopy.close();
            document.close();
            oStream_bulk.flush();
            oStream_bulk.close();
            PDFcopy = null;
            oStream = null;
            if (Print) {
                if (Copy == 1) {
                    if (printCMD.isEmpty()) {
                        PrintProgram = com.lowagie.tools.Executable.printDocumentSilent(
                                Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                        + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf",
                                false);
                    } else {
                        PrintProgram = Runtime.getRuntime()
                                .exec(printCMD + ((printPreARG.isEmpty()) ? "" : " " + printPreARG + " ") + "\""
                                        + Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                        + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf\""
                                        + ((printPostARG.isEmpty()) ? "" : " " + printPostARG));
                    }
                    Bar.setString("Print Job Sent.");
                } else if (Copy > 1) {
                    for (int c = 1; c <= Copy; c++) {
                        if (printCMD.isEmpty()) {
                            PrintProgram = com.lowagie.tools.Executable
                                    .printDocumentSilent(
                                            Output_batch + File.separator + Datas.get(0).getSequenceID() + "-"
                                                    + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf",
                                            false);
                        } else {
                            PrintProgram = Runtime.getRuntime()
                                    .exec(printCMD + ((printPreARG.isEmpty()) ? "" : " " + printPreARG + " ")
                                            + "\"" + Output_batch + File.separator
                                            + Datas.get(0).getSequenceID() + "-"
                                            + Datas.get(Datas.size() - 1).getSequenceID() + ".pdf\""
                                            + ((printPostARG.isEmpty()) ? "" : " " + printPostARG));

                        }
                        Bar.setString("Print Job [" + i + "] Sent.");
                    }

                }
            }
            Bar.setString("Finished");
            Thread.sleep(2000);
            PDialog.stop();
        } else if (Datas.size() == 1) {
            Bar.setMaximum(2);
            Bar.setValue(1);
            Bar.setString("Encoding " + Datas.get(0).getFullname());

            //Load Template
            Template = new WorkBook();
            iStream = new FileInputStream(Source);
            Template.readXLSX(iStream);

            //Encode Data
            BIR_Form = new Data2316();
            BIR_Form.setBIRAccount(Datas.get(0), Personel);
            BIR_Form.encodeTo(Template);

            //Prepare PDF Export;
            Output = ((Output.isEmpty())
                    ? System.getProperty("user.home") + File.separator + "Desktop" + File.separator + "BIR2316"
                            + File.separator + Datas.get(0).getTinNumber() + ".pdf"
                    : Output + File.separator + Datas.get(0).getTinNumber() + ".pdf");
            oStream = new FileOutputStream(Output);
            if (Print) {
                Bar.setString("Printing 1 of 1");
                Template.setPrintNumberOfCopies(Copy);
                Template.print();
            }
            Bar.setString("Exporting PDF : " + Output);
            Template.exportPDF(oStream);

            Bar.setValue(2);
            Bar.setString("Process Done");
            Thread.sleep(2000);
            PDialog.stop();
        }
    } catch (Exception er) {
        Bar.setString(er.toString());
    } finally {
        try {
            if (iStream != null) {
                iStream.close();
            }
            if (oStream != null) {
                oStream.flush();
                oStream.close();
            }
            if (PDFcopy != null) {
                PDFcopy.close();
                document.close();
                oStream_bulk.flush();
                oStream_bulk.close();
            }
            BIR_Form = null;
            Datas = null;
            Template = null;
            iStream = null;
            oStream = null;
            PDFcopy = null;
            oStream = null;
            document = null;
            System.gc();
        } catch (Exception er) {
            Bar.setString(er.toString());
        }
    }
}

From source file:org.arc42.pdfutil.PdfConcatenizer.java

License:Open Source License

/**
 * concats all files given in sourceFile
 *///from  w  ww.  ja v  a2  s .c  om
public void concatFiles() {
    Document document = new Document();
    try {
        PdfCopy copy = new PdfCopy(document, new FileOutputStream(targetFileName));
        document.open();
        PdfReader reader;
        int nrOfPagesInCurrentFile;
        for (int i = 0; i < sourceFiles.size(); i++) {
            reader = new PdfReader(sourceFiles.get(i));

            nrOfPagesInCurrentFile = reader.getNumberOfPages();
            for (int page = 0; page < nrOfPagesInCurrentFile;) {
                copy.addPage(copy.getImportedPage(reader, ++page));
            }

            if (evenify && (nrOfPagesInCurrentFile % 2 == 1)) {
                addBlankPage(copy);
            }

        }
        document.close();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Exception: wrong file you gave me, Yoda muttered...", e);
    } catch (BadPdfFormatException e) {
        LOGGER.log(Level.SEVERE, "Exception: Encountered bad pdf format", e);
    } catch (DocumentException e) {
        LOGGER.log(Level.SEVERE, "Exception: Something bad happened to the output document.", e);
    }

}

From source file:org.ednovo.gooru.domain.service.resource.ResourceServiceImpl.java

License:Open Source License

/**
 * @param mainFileUrl/*from   w  w w .  ja  v a 2 s  .c  om*/
 *            : PDF file that has to be splitted
 * @param splittedPageSize
 *            : Page size of each splitted files
 */
private static String splitAndSaveChapter(String mainFileUrl, int pageBeginNum, int pageEndNum, String name) {
    try {
        PdfReader reader = new PdfReader(mainFileUrl);

        int splittedPageSize = pageEndNum - pageBeginNum + 1;
        int pageNum = pageBeginNum;

        String chapterUrl = mainFileUrl.substring(0, mainFileUrl.indexOf(DOT_PDF)) + "-" + name + DOT_PDF;

        Document document = new Document(reader.getPageSizeWithRotation(1));

        FileOutputStream fos = new FileOutputStream(chapterUrl);
        PdfCopy writer = new PdfCopy(document, fos);
        Map<String, String> info = reader.getInfo();

        document.open();
        if ((info != null) && (info.get(_AUTHOR) != null)) {
            document.addAuthor(info.get(_AUTHOR));
        }

        document.addTitle(name);

        for (int offset = 0; offset < splittedPageSize && (pageNum + offset) < pageEndNum; offset++) {
            PdfImportedPage page = writer.getImportedPage(reader, pageNum + offset);
            writer.addPage(page);
        }

        document.close();
        writer.close();
        return chapterUrl;

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:oscar.dms.IncomingDocUtil.java

License:Open Source License

public static void deletePage(String queueId, String myPdfDir, String myPdfName, String PageNumberToDelete)
        throws Exception {
    long lastModified;
    String filePathName, tempFilePathName;

    tempFilePathName = getIncomingDocumentFilePath(queueId, myPdfDir) + File.separator + "T" + myPdfName;
    filePathName = getIncomingDocumentFilePathName(queueId, myPdfDir, myPdfName);

    File f = new File(filePathName);
    lastModified = f.lastModified();/*w w w. j av a 2s .  co m*/
    f.setReadOnly();

    String deletePath = getIncomingDocumentDeletedFilePath(queueId, myPdfDir) + File.separator;
    String deletePathFileName = "";
    int index = myPdfName.indexOf(".pdf");

    String myPdfNameF = myPdfName.substring(0, index);
    String myPdfNameExt = myPdfName.substring(index, myPdfName.length());

    PdfReader reader = null;
    Document document = null;
    PdfCopy copy = null;
    PdfCopy deleteCopy = null;

    try {
        reader = new PdfReader(filePathName);
        deletePathFileName = deletePath + myPdfNameF + "d" + PageNumberToDelete + "of"
                + Integer.toString(reader.getNumberOfPages()) + myPdfNameExt;

        document = new Document(reader.getPageSizeWithRotation(1));
        copy = new PdfCopy(document, new FileOutputStream(tempFilePathName));
        deleteCopy = new PdfCopy(document, new FileOutputStream(deletePathFileName));
        document.open();

        for (int pageNumber = 1; pageNumber <= reader.getNumberOfPages(); pageNumber++) {
            if (!(pageNumber == (Integer.parseInt(PageNumberToDelete)))) {
                copy.addPage(copy.getImportedPage(reader, pageNumber));
            } else {
                deleteCopy.addPage(copy.getImportedPage(reader, pageNumber));
            }
        }
    } catch (Exception e) {
        throw (e);
    } finally {
        try {
            if (copy != null) {
                copy.close();
            }
            if (deleteCopy != null) {
                deleteCopy.close();
            }

            if (document != null) {
                document.close();
            }

            if (reader != null) {
                reader.close();
            }

        } catch (Exception e) {
            throw (e);
        }
    }

    boolean success;
    if (!oscar.OscarProperties.getInstance().getBooleanProperty("INCOMINGDOCUMENT_RECYCLEBIN", "true")) {
        File f1 = new File(deletePathFileName);
        success = f1.delete();
        if (!success) {
            throw new Exception("Error in deleting file:" + deletePathFileName);
        }
    }

    success = f.delete();
    if (success) {
        File f1 = new File(tempFilePathName);
        f1.setLastModified(lastModified);
        success = f1.renameTo(new File(filePathName));
        if (!success) {
            throw new Exception("Error in renaming file from:" + tempFilePathName + "to " + filePathName);
        }
    } else {
        throw new Exception("Error in deleting file:" + filePathName);
    }
}