Example usage for org.apache.pdfbox.pdmodel PDDocument PDDocument

List of usage examples for org.apache.pdfbox.pdmodel PDDocument PDDocument

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel PDDocument PDDocument.

Prototype

public PDDocument() 

Source Link

Document

Creates an empty PDF document.

Usage

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

public static PDDocument generateGeoPdf(int numberOfPages, int numberOfFramesPerPage, String projectionType) {
    PDDocument pdDocument = new PDDocument();
    for (int i = 0; i < numberOfPages; i++) {
        pdDocument.addPage(generateGeoPdfPage(numberOfFramesPerPage, projectionType));
    }/*from w  ww .  ja va2  s . c om*/
    return pdDocument;
}

From source file:ddf.catalog.transformer.input.pdf.GeoPdfDocumentGenerator.java

License:Open Source License

public static PDDocument generateGeoPdf(int numberOfPages, String projectionType, boolean generateNeatLine) {
    PDDocument pdDocument = new PDDocument();
    for (int i = 0; i < numberOfPages; i++) {
        pdDocument.addPage(generateGeoPdfPage(projectionType, generateNeatLine));
    }//from   w w w .  j a  v  a  2 s. com
    return pdDocument;
}

From source file:de.fau.amos4.util.ZipGenerator.java

License:Open Source License

public void generate(OutputStream out, Locale locale, float height, Employee employee, int fontSize,
        String zipPassword) throws ZipException, NoSuchMessageException, IOException, COSVisitorException,
        CloneNotSupportedException {
    final ZipOutputStream zout = new ZipOutputStream(out);

    if (zipPassword == null) {
        // Use default password if none is set.
        zipPassword = "fragebogen";
    }//  w  ww.ja v  a 2s .c o m

    ZipParameters params = new ZipParameters();
    params.setFileNameInZip("employee.txt");
    params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
    params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
    params.setEncryptFiles(true);
    params.setReadHiddenFiles(false);
    params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
    params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
    params.setPassword(zipPassword);
    params.setSourceExternalStream(true);

    zout.putNextEntry(null, params);
    zout.write((AppContext.getApplicationContext().getMessage("HEADER", null, locale) + "\n\n").getBytes());

    zout.write(
            (AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale) + "\n\n")
                    .getBytes());

    Iterator it = employee.getPersonalDataFields().entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
        it.remove(); // avoids a ConcurrentModificationException
    }

    zout.write(("\n\n" + AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale)
            + "\n\n").getBytes());

    it = employee.getTaxesFields().entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry) it.next();
        zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
        it.remove(); // avoids a ConcurrentModificationException
    }
    zout.closeEntry();

    // Create a document and add a page to it
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    float y = -1;
    int margin = 100;

    // Create a new font object selecting one of the PDF base fonts
    PDFont font = PDType1Font.TIMES_ROMAN;

    // Start a new content stream which will "hold" the to be created content
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
    contentStream.beginText();

    y = page.getMediaBox().getHeight() - margin + height;
    contentStream.moveTextPositionByAmount(margin, y);
    /*
    List<String> list = StringUtils.splitEqually(fileContent, 90);
    for (String e : list) {
        contentStream.moveTextPositionByAmount(0, -15);
        contentStream.drawString(e);
    }
    */

    contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
    contentStream.drawString(AppContext.getApplicationContext().getMessage("HEADER", null, locale));
    contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
    contentStream.moveTextPositionByAmount(0, -4 * height);
    contentStream.drawString(
            AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream.setFont(font, fontSize);

    it = employee.getPersonalDataFields().entrySet().iterator();
    while (it.hasNext()) {
        StringBuffer nextLineToDraw = new StringBuffer();
        Map.Entry pair = (Map.Entry) it.next();
        nextLineToDraw.append(pair.getKey());
        nextLineToDraw.append(": ");
        nextLineToDraw.append(pair.getValue());

        contentStream.drawString(nextLineToDraw.toString());
        contentStream.moveTextPositionByAmount(0, -height);
        it.remove(); // avoids a ConcurrentModificationException
    }
    contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream
            .drawString(AppContext.getApplicationContext().getMessage("print.section.taxes", null, locale));
    contentStream.moveTextPositionByAmount(0, -2 * height);
    contentStream.setFont(font, fontSize);
    it = employee.getTaxesFields().entrySet().iterator();
    while (it.hasNext()) {
        StringBuffer nextLineToDraw = new StringBuffer();
        Map.Entry pair = (Map.Entry) it.next();
        nextLineToDraw.append(pair.getKey());
        nextLineToDraw.append(": ");
        nextLineToDraw.append(pair.getValue());

        contentStream.drawString(nextLineToDraw.toString());
        contentStream.moveTextPositionByAmount(0, -height);
        it.remove(); // avoids a ConcurrentModificationException
    }
    contentStream.endText();

    // Make sure that the content stream is closed:
    contentStream.close();

    // Save the results and ensure that the document is properly closed:
    ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
    document.save(pdfout);
    document.close();

    ZipParameters params2 = (ZipParameters) params.clone();
    params2.setFileNameInZip("employee.pdf");

    zout.putNextEntry(null, params2);
    zout.write(pdfout.toByteArray());
    zout.closeEntry();

    // Write the zip to client
    zout.finish();
    zout.flush();
    zout.close();
}

From source file:de.fau.amos4.web.PrintDataController.java

License:Open Source License

@RequestMapping("/employee/download/zip")
public void EmployeeDownloadZip(HttpServletResponse response,
        @RequestParam(value = "id", required = true) long employeeId) throws IOException {
    int fontSize = 12;
    float height = 1;
    height = height * fontSize * 1.05f;//from   w w w .  j av a2  s .  c  om

    //Prepare textfile contents
    Employee employee = employeeRepository.findOne(employeeId);
    Locale locale = LocaleContextHolder.getLocale();
    Map<String, String> fields = employee.getFields();

    response.setContentType("application/zip");
    response.setHeader("Content-Disposition", "attachment;filename=employee.zip");

    final ZipOutputStream zout = new ZipOutputStream(response.getOutputStream());

    try {
        ZipParameters params = new ZipParameters();
        params.setFileNameInZip("employee.txt");
        params.setCompressionLevel(Zip4jConstants.COMP_DEFLATE);
        params.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_ULTRA);
        params.setEncryptFiles(true);
        params.setReadHiddenFiles(false);
        params.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
        params.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
        params.setPassword("AMOS");
        params.setSourceExternalStream(true);

        zout.putNextEntry(null, params);
        zout.write((AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale) + "\n\n")
                .getBytes());
        //zout.println();
        zout.write((AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale)
                + "\n\n").getBytes());
        //zout.println();
        Iterator it = fields.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            zout.write((pair.getKey() + ": " + pair.getValue() + '\n').getBytes());
            it.remove(); // avoids a ConcurrentModificationException
        }
        zout.closeEntry();

        try {
            // Create a document and add a page to it
            PDDocument document = new PDDocument();
            PDPage page = new PDPage();
            document.addPage(page);
            float y = -1;
            int margin = 100;
            float maxStringLength = page.getMediaBox().getWidth() - 2 * margin;

            // Create a new font object selecting one of the PDF base fonts
            PDFont font = PDType1Font.TIMES_ROMAN;

            // Start a new content stream which will "hold" the to be created content
            PDPageContentStream contentStream = new PDPageContentStream(document, page);

            // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World"
            contentStream.beginText();

            y = page.getMediaBox().getHeight() - margin + height;
            contentStream.moveTextPositionByAmount(margin, y);
            /*
            List<String> list = StringUtils.splitEqually(fileContent, 90);
            for (String e : list) {
            contentStream.moveTextPositionByAmount(0, -15);
            contentStream.drawString(e);
            }
            */

            fields = employee.getFields();

            contentStream.setFont(PDType1Font.TIMES_BOLD, 36);
            contentStream.drawString(
                    AppContext.getApplicationContext().getMessage("EmployeeForm.header", null, locale));
            contentStream.setFont(PDType1Font.TIMES_BOLD, 14);
            contentStream.moveTextPositionByAmount(0, -4 * height);
            contentStream.drawString(
                    AppContext.getApplicationContext().getMessage("print.section.personalData", null, locale));
            contentStream.moveTextPositionByAmount(0, -2 * height);
            contentStream.setFont(font, fontSize);
            it = fields.entrySet().iterator();
            while (it.hasNext()) {
                StringBuffer nextLineToDraw = new StringBuffer();
                Map.Entry pair = (Map.Entry) it.next();
                nextLineToDraw.append(pair.getKey());
                nextLineToDraw.append(": ");
                nextLineToDraw.append(pair.getValue());

                contentStream.drawString(nextLineToDraw.toString());
                contentStream.moveTextPositionByAmount(0, -height);
                it.remove(); // avoids a ConcurrentModificationException
            }
            contentStream.endText();

            // Make sure that the content stream is closed:
            contentStream.close();

            // Save the results and ensure that the document is properly closed:
            ByteArrayOutputStream pdfout = new ByteArrayOutputStream();
            document.save(pdfout);
            document.close();

            ZipParameters params2 = (ZipParameters) params.clone();
            params2.setFileNameInZip("employee.pdf");

            zout.putNextEntry(null, params2);
            zout.write(pdfout.toByteArray());
            zout.closeEntry();
        } catch (CloneNotSupportedException | COSVisitorException e) {
            e.printStackTrace();
        }

        // Write the zip to client
        zout.finish();
        zout.flush();
        zout.close();
    } catch (ZipException e) {
        e.printStackTrace();
    }
}

From source file:de.hrogge.CompactPDFExport.PDFGenerator.java

License:Apache License

private PDDocument internErzeugePDFDokument(Konfiguration k, Daten daten) throws IOException {
    String[] guteEigenschaften;//w ww . jav  a2  s  . c o m
    List<PDFSonderfertigkeiten> sflist;
    List<Gegenstand> ausruestung;
    boolean tzm;
    PDDocument doc;
    String pfad;
    PDJpeg charakterBild;
    PDJpeg hintergrundBild;
    Hausregeln hausregeln;
    List<String> commands;
    doc = null;

    hausregeln = new Hausregeln(k);

    charakterBild = null;
    hintergrundBild = null;
    tzm = daten.getConfig().getRsmodell().equals("zone");

    /*
     * Gute Eigenschaften auslesen, da sie seitenbergreifend gebraucht
     * werden
     */
    Eigenschaften eigenschaften = daten.getEigenschaften();
    guteEigenschaften = new String[8];
    guteEigenschaften[0] = eigenschaften.getMut().getAkt().toString();
    guteEigenschaften[1] = eigenschaften.getKlugheit().getAkt().toString();
    guteEigenschaften[2] = eigenschaften.getIntuition().getAkt().toString();
    guteEigenschaften[3] = eigenschaften.getCharisma().getAkt().toString();
    guteEigenschaften[4] = eigenschaften.getFingerfertigkeit().getAkt().toString();
    guteEigenschaften[5] = eigenschaften.getGewandtheit().getAkt().toString();
    guteEigenschaften[6] = eigenschaften.getKonstitution().getAkt().toString();
    guteEigenschaften[7] = eigenschaften.getKoerperkraft().getAkt().toString();

    sflist = new ArrayList<PDFSonderfertigkeiten>();
    for (Sonderfertigkeit sf : daten.getSonderfertigkeiten().getSonderfertigkeit()) {
        if (sf.getAuswahlen() != null && sf.getAuswahlen().getAuswahl().size() > 0) {
            for (Sonderfertigkeit.Auswahlen.Auswahl a : sf.getAuswahlen().getAuswahl()) {
                sflist.add(new PDFSonderfertigkeiten(sf, a.getName()));
            }
        } else {
            sflist.add(new PDFSonderfertigkeiten(sf));
        }
    }

    ausruestung = new ArrayList<>(daten.getGegenstaende().getGegenstand());

    /* Kommandos aus Notizen extrahieren */
    Notizen n = daten.getAngaben().getNotizen();
    commands = new ArrayList<>();
    extrahiereKommandos(commands, n.getN0());
    extrahiereKommandos(commands, n.getN1());
    extrahiereKommandos(commands, n.getN2());
    extrahiereKommandos(commands, n.getN3());
    extrahiereKommandos(commands, n.getN4());
    extrahiereKommandos(commands, n.getN5());
    extrahiereKommandos(commands, n.getN6());
    extrahiereKommandos(commands, n.getN7());
    extrahiereKommandos(commands, n.getN8());
    extrahiereKommandos(commands, n.getN9());
    extrahiereKommandos(commands, n.getN10());
    extrahiereKommandos(commands, n.getN11());

    try {
        /* PDF erzeugen */
        doc = new PDDocument();

        /*
         * Bilder mssen bei PDFBox geladen werden bevor die Content-Streams
         * erzeugt werden
         */
        pfad = daten.getAngaben().getBildPfad();
        if (pfad != null && pfad.length() > 0) {
            try {
                BufferedImage img = ImageIO.read(new File(pfad));
                charakterBild = new PDJpeg(doc, img);
            } catch (Exception e) {
                System.err.println("Konnte das Bild '" + pfad + "' nicht laden.");
            }
        }

        pfad = k.getTextDaten(Konfiguration.GLOBAL_HINTERGRUND);
        if (pfad != null && pfad.length() > 0) {
            try {
                BufferedImage img = ImageIO.read(new File(pfad));
                hintergrundBild = new PDJpeg(doc, img);
            } catch (Exception e) {
                System.err.println("Konnte das Bild '" + pfad + "' nicht laden.");
            }
        }

        /* globale Settings fr Seite festlegen */
        PDFSeite.init(marginX, marginY, textMargin, hintergrundBild,
                k.getOptionsDaten(Konfiguration.GLOBAL_HINTERGRUND_VERZERREN));

        /* Sonderfertigkeiten sortieren */
        Collections.sort(sflist);

        /* Seiten erzeugen */
        FrontSeite page1 = new FrontSeite(doc);
        page1.erzeugeSeite(daten, charakterBild, hintergrundBild, guteEigenschaften, sflist, hausregeln,
                commands, tzm, k);

        TalentSeite page2 = new TalentSeite(doc);
        page2.erzeugeSeite(daten, hintergrundBild, guteEigenschaften, sflist, hausregeln, commands, k);

        if (daten.getAngaben().isMagisch()) {
            ZauberSeite page3 = new ZauberSeite(doc);
            page3.erzeugeSeite(daten, hintergrundBild, guteEigenschaften, sflist, hausregeln, commands, k);
        }

        /* Leerzeilen zu Sonderfertigkeitsliste hinzufgen */
        for (int i = 1; i < sflist.size(); i++) {
            if (sflist.get(i - 1).getKategorie() != sflist.get(i).getKategorie()) {
                sflist.add(i, null);
                i++;
            }
        }

        while (hatNichtGedruckteSonderfertigkeit(sflist) || ausruestung.size() > 0) {
            SonstigesSeite page4 = new SonstigesSeite(doc);
            page4.erzeugeSeite(hintergrundBild, guteEigenschaften, sflist, ausruestung);
        }
    } catch (IOException e) {
        if (doc != null) {
            doc.close();
            doc = null;
        }
        throw e;
    }
    return doc;
}

From source file:de.ifsr.adam.ImageGenerator.java

License:Open Source License

/**
 * Takes a snapshot of the Pane and prints it to a pdf.
 *
 * @return True if no IOException occurred
 *//*  w  ww. j a  v a  2  s . c o  m*/
private boolean printToPDF(String filePath, Pane pane) {
    //Scene set up
    Group root = new Group();
    Scene printScene = new Scene(root);
    printScene.getStylesheets().add(this.stylesheetURI.toString());

    //Snapshot generation
    ArrayList<WritableImage> images = new ArrayList<>();
    try {
        ObservableList<Node> panes = pane.getChildren();
        for (int i = 0; i < panes.size(); i++) {
            GridPane gridPane = (GridPane) panes.get(i);
            ((Group) printScene.getRoot()).getChildren().clear();
            ((Group) printScene.getRoot()).getChildren().addAll(gridPane);
            images.add(printScene.snapshot(null));
            panes.add(i, gridPane);
        }
    } catch (Exception e) {
        log.error(e);
        return false;
    }

    //PDF Setup
    File outFile = new File(filePath + "." + "pdf");
    Iterator<WritableImage> iterImages = images.iterator();
    PDDocument doc = new PDDocument();

    try {

        while (iterImages.hasNext()) {
            //Page setup
            PDPage page = new PDPage();
            doc.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, false);
            //Image setup
            BufferedImage bufImage = SwingFXUtils.fromFXImage(iterImages.next(), null);
            PDPixelMap pixelMap = new PDPixelMap(doc, bufImage);

            int width = (int) (page.getMediaBox().getWidth());
            int height = (int) (page.getMediaBox().getHeight());
            Dimension dim = new Dimension(width, height);
            contentStream.drawXObject(pixelMap, 0, 0, dim.width, dim.height);
            contentStream.close();
        }

        doc.save(outFile);
        return true;
    } catch (IOException | COSVisitorException e) {
        log.error(e);
        return false;
    }
}

From source file:de.katho.kBorrow.controller.NewLendingController.java

License:Open Source License

/**
 * Erzeugt ein PDF-File mit allen relevanten Daten zur als Parameter bergebenen Lending-ID.
 * /*from  w ww .  ja  va2  s .c  o m*/
 * @param pLendingId   ID der Ausleihe, fr die ein PDF erzeugt werden soll.
 * @throws Exception   Wenn Probleme beim Erstellen der Datei auftreten.
 */
private void createPdfFile(int pLendingId) throws Exception {
    KLending lending = kLendingModel.getElement(pLendingId);
    KArticle article = kArticleModel.getElement(lending.getArticleId());
    KUser user = kUserModel.getElement(lending.getUserId());
    KLender lender = kLenderModel.getElement(lending.getLenderId());

    PDDocument doc = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    PDRectangle rect = page.getMediaBox();
    doc.addPage(page);

    PDFont fontNormal = PDType1Font.HELVETICA;
    PDFont fontBold = PDType1Font.HELVETICA_BOLD;

    String[] text = { "Artikel: ", "Verliehen von: ", "Ausgeliehen an: ", "Start der Ausleihe: ",
            "Voraussichtliche Rckgabe: " };
    String[] vars = { article.getName(), user.getName() + " " + user.getSurname(),
            lender.getName() + " " + lender.getSurname() + " (" + lender.getStudentnumber() + ")",
            lending.getStartDate(), lending.getExpectedEndDate() };
    try {
        File file = createRandomPdf();

        PDPageContentStream cos = new PDPageContentStream(doc, page);

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 100);
        cos.setFont(fontBold, 16);
        cos.drawString("Ausleihe #" + lending.getId());
        cos.endText();

        int i = 0;

        while (i < text.length) {
            cos.beginText();
            cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
            cos.setFont(fontBold, 12);
            cos.drawString(text[i]);
            cos.moveTextPositionByAmount(rect.getWidth() / 2 - 100, 0);
            cos.setFont(fontNormal, 12);
            cos.drawString(vars[i]);
            cos.endText();
            i++;
        }

        i = i + 2;
        cos.setLineWidth(1);
        cos.addLine(100, rect.getHeight() - 25 * (i + 2) - 100, 300, rect.getHeight() - 25 * (i + 2) - 100);
        cos.closeAndStroke();

        i++;

        cos.beginText();
        cos.moveTextPositionByAmount(100, rect.getHeight() - 25 * (i + 2) - 100);
        cos.setFont(fontNormal, 12);
        cos.drawString("Unterschrift " + lender.getName() + " " + lender.getSurname());
        cos.endText();

        cos.close();
        doc.save(file);
        doc.close();

        if (Desktop.isDesktopSupported()) {
            Desktop desktop = Desktop.getDesktop();
            if (desktop.isSupported(Desktop.Action.OPEN)) {
                desktop.open(file);
            }
        }
    } catch (IOException | COSVisitorException e) {
        throw new Exception("Problem bei der Erstellung der PDF-Datei.", e);
    }
}

From source file:de.maklerpoint.office.Schnittstellen.PDF.ExportSimplePDF.java

License:Open Source License

public void write() throws IOException, COSVisitorException {
    PDDocument doc = null;/*from  w w  w  .  j ava  2 s  .  c  o  m*/
    try {
        doc = new PDDocument();

        PDPage page = new PDPage();
        doc.addPage(page);
        PDFont font = PDType1Font.HELVETICA;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(contents);

        contentStream.endText();
        contentStream.close();

        doc.save(filename);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }

}

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

License:Apache License

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

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

        /*/*from  ww  w  . j av  a2  s . com*/
         * 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;
            }

            /*
             * Now extract the pages
             * 
             * NOTE
             * ====
             * Since Apache PDFBox v1.5.0 there exists the class
             * org.apache.pdfbox.util.PageExtractor
             */

            /*
            boolean isApachePageExtractorAvailable = false;
            Class<?> pageExtractorClass = null;
            try {
               pageExtractorClass = getClass().getClassLoader().loadClass("org.apache.pdfbox.util.PageExtractor");
               Constructor<?> pdfExtractConstructor = pageExtractorClass.getConstructor(PDDocument.class, int.class, int.class);
               Method pdfExtractMethod = pageExtractorClass.getMethod("extract");
               isApachePageExtractorAvailable = true;
            } catch (ClassNotFoundException ex) {
            } catch (SecurityException ex) {
            } catch (NoSuchMethodException ex) {
            }
            */

            try {
                PDDocument extractedDocumentPages = new PDDocument();
                extractedDocumentPages.setDocumentInformation(this.pdfDocument.getDocumentInformation());
                extractedDocumentPages.getDocumentCatalog()
                        .setViewerPreferences(this.pdfDocument.getDocumentCatalog().getViewerPreferences());

                List<PDPage> pages = (List<PDPage>) this.pdfDocument.getDocumentCatalog().getAllPages();
                int pageCounter = 1;
                for (PDPage page : pages) {
                    if (pageCounter >= fromPageNumber && pageCounter <= toPageNumber) {
                        PDPage importedPdfPage;
                        importedPdfPage = extractedDocumentPages.importPage(page);
                        importedPdfPage.setCropBox(page.findCropBox());
                        importedPdfPage.setMediaBox(page.findMediaBox());
                        importedPdfPage.setResources(page.findResources());
                        importedPdfPage.setRotation(page.findRotation());
                    }
                    pageCounter++;
                } // end for

                byteArrayOutputStream = new ByteArrayOutputStream();
                extractedDocumentPages.save(byteArrayOutputStream);
                extractedDocumentPages.close();
                extractionSuccessful = true;
            } catch (COSVisitorException 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 (pdfDocument != null)

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

From source file:de.prozesskraft.pkraft.Createdoc.java

/**
 * merge the pdfs/*  w w  w. ja  v a  2s .c o m*/
 */
private static void mergePdf(Map<String, String> pdfRankFiles, String output) {
    System.out.println("merging pdfs to a single file");

    Set<String> keySet = pdfRankFiles.keySet();
    ArrayList<String> listKey = new ArrayList(keySet);
    Collections.sort(listKey);

    try {
        PDDocument document = new PDDocument();
        //         if(document.getNumberOfPages() > 0)
        //         {
        //            System.out.println("deleting empty page");
        //            document.removePage(0);
        //         }
        for (String actualKey : listKey) {

            PDDocument part = PDDocument.load(pdfRankFiles.get(actualKey));
            System.out.println("merging " + pdfRankFiles.get(actualKey));
            ArrayList<PDPage> list = (ArrayList<PDPage>) part.getDocumentCatalog().getAllPages();
            for (PDPage page : list) {
                document.addPage(page);
            }

        }
        try {
            System.out.println("writing " + output);
            document.save(output);
        } catch (COSVisitorException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}