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

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

Introduction

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

Prototype

public void addPage(PDPage page) 

Source Link

Document

This will add a page to the document.

Usage

From source file:merge_split.MergeSplit.java

License:Apache License

private void SplitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SplitButtonActionPerformed
    try {//from  ww  w. j av a2  s  . com

        File file = new File(SplitFileField.getText());
        PDDocument doc1;
        if (splitcode.equals("ok")) {
            doc1 = PDDocument.load(file);
        } else {
            doc1 = PDDocument.load(file, splitcode);

        }
        doc1.setAllSecurityToBeRemoved(true);

        if (MultipleButton.isSelected()) {
            PDDocument pdf1 = new PDDocument();
            PDDocument pdf2 = new PDDocument();
            TreeSet tree = findPages(SplitPagesField.getText());
            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                PDPage page = doc1.getPage(j);
                if (tree.contains(j + 1)) {
                    pdf1.addPage(page);
                } else {
                    pdf2.addPage(page);

                }
            }
            String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "1.pdf";
            String destination2 = SplitDestinationField.getText() + "\\" + SplitNameField.getText() + "2.pdf";

            PDDocumentInformation info = pdf1.getDocumentInformation();
            info.setAuthor(SplitAuthorField.getText());
            PDDocumentInformation info2 = pdf2.getDocumentInformation();
            info2.setAuthor(SplitAuthorField.getText());
            if (pdf1.getNumberOfPages() > 0) {
                File output1 = new File(destination1);
                pdf1.save(output1);
            }
            if (pdf2.getNumberOfPages() > 0) {
                File output2 = new File(destination2);
                pdf2.save(output2);
            }
            pdf1.close();
            pdf2.close();
        } else if (SingleButton.isSelected()) {

            for (int j = 0; j < doc1.getNumberOfPages(); j++) {
                PDDocument pdf1 = new PDDocument();

                PDPage page = doc1.getPage(j);
                pdf1.addPage(page);
                int pagenumber = j + 1;
                String destination1 = SplitDestinationField.getText() + "\\" + SplitNameField.getText()
                        + pagenumber + ".pdf";

                PDDocumentInformation info = pdf1.getDocumentInformation();
                info.setAuthor(SplitAuthorField.getText());

                if (pdf1.getNumberOfPages() > 0) {
                    File output1 = new File(destination1);
                    pdf1.save(output1);
                }

                pdf1.close();
            }

        }
        doc1.close();

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null, "Your input is incorrect. Please fill all the fields.",
                "Input warning", JOptionPane.WARNING_MESSAGE);
        java.util.logging.Logger.getLogger(MergeSplit.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);

    }
}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);/*from www.j a v  a 2 s. co m*/
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:model.objects.Project.java

License:Apache License

/**
 * //from  w  w  w . j a va2 s .c  o m
 * @param _doc
 * @param _bi
 * @param _pageindex       index of page to which the BufferedImage is 
 *                      inserted.
 *                      If it is equal to -1, new page is created.
 *                   
 */
public void attatchToPDF(final PDDocument _doc, final BufferedImage _bi, final int _pageindex) {
    PDPage page = null;
    try {
        if (_pageindex == -1) {
            page = new PDPage(new PDRectangle(State.getImageSize().width, State.getImageSize().height));

            _doc.addPage(page);
        } else {
            page = _doc.getPage(_pageindex);
            //             page.setCropBox(new PDRectangle(State.getImageSize().width , 
            //                   State.getImageSize().height ));

        }

        int width = (int) page.getCropBox().getWidth();
        int height = (int) page.getCropBox().getHeight();

        PDImageXObject ximage = LosslessFactory.createFromImage(_doc,
                //                 _bi);
                Utils.resizeImage(width, height, _bi));

        PDPageContentStream content = new PDPageContentStream(_doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        content.drawImage(ximage, 20, 20, ximage.getWidth() * scale, ximage.getHeight() * scale);

        content.close();
        //  LosslessFactory.createFromImage(doc, bim)
        //              content.drawImage(ximage, 0, 0);
        //              content.close();
    } catch (IOException ie) {
        //handle exception
    }
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile    pdf input/*from   w  ww. j  ava  2s .c  om*/
 * @param _imagePath    image input
 * @param _outputFile    pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void saveAsPdf(String _imagePath, String _outputFile) throws IOException {

    PDDocument doc = null;
    try {

        // create new document and insert empty page to the document.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

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

From source file:nominas.sei.form.Principal.java

private void ordenaNominas(String rutaEntrada, String rutaSalida) {
    ArrayList<PaginaNomina> paginasNomina = new ArrayList<PaginaNomina>();

    for (int x = 0; x < 1; x++) {//RECORREMOS EL ARREGLO CON LOS NOMBRES DE ARCHIVO

        try {//from w  w w  .j a v  a  2 s .c  o m
            PDDocument pd = PDDocument.load(rutaEntrada); //CARGAR EL PDF
            List l = pd.getDocumentCatalog().getAllPages();//NUMERO LAS PAGINAS DEL ARCHIVO
            Object[] obj = l.toArray();//METO EN UN OBJETO LA LISTA DE PAGINAS PARA MANIPULARLA
            for (int i = 0; i < l.size(); i++) {
                PDPage page = (PDPage) obj[i];//PAGE ES LA PAGINA 1 DE LA QUE CONSTA EL ARCHIVO
                PageFormat pageFormat = pd.getPageFormat(0);//PROPIEDADES DE LA PAGINA (FORMATO)
                Double d1 = new Double(pageFormat.getHeight());//ALTO
                Double d2 = new Double(pageFormat.getWidth());//ANCHO
                int width = d1.intValue();//ANCHO
                int eigth = 1024;//ALTO

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();//COMPONENTE PARA ACCESO AL TEXTO
                Rectangle rect = new Rectangle(0, 0, width, eigth);//DEFNIR AREA DONDE SE BUSCARA EL TEXTO
                stripper.addRegion("area1", rect);//REGISTRAMOS LA REGION CON UN NOMBRE
                stripper.extractRegions(page);//EXTRAE TEXTO DEL AREA

                String contenido = new String();//CONTENIDO = A LO QUE CONTENGA EL AREA O REGION
                contenido = (stripper.getTextForRegion("area1"));
                String[] lines = contenido.split("[\\r\\n]+");
                String nombre = lines[1].substring(28, lines[1].length() - 10);//Separamos el nombre
                PaginaNomina nomina = new PaginaNomina(page, nombre);
                paginasNomina.add(nomina);
            }
            Collections.sort(paginasNomina);
            // Create a new empty document
            PDDocument document = new PDDocument();

            for (int i = 0; i < paginasNomina.size(); i++) {
                System.out.println(paginasNomina.get(i).getNombre());
                document.addPage(paginasNomina.get(i).getPagina());
            }
            // Save the newly created document
            document.save(rutaSalida);

            // finally make sure that the document is properly
            // closed.
            document.close();
            pd.close();//CERRAMOS OBJETO ACROBAT
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } //CATCH
    } //FOR
}

From source file:nominas.sei.NominasSEI.java

/**
 * @param args the command line arguments
 *///from   w  w  w .  j  a  v a 2s  .c om
public static void main(String[] args) {

    ArrayList<PaginaNomina> paginasNomina = new ArrayList<PaginaNomina>();

    for (int x = 0; x < 1; x++) {//RECORREMOS EL ARREGLO CON LOS NOMBRES DE ARCHIVO
        String ruta = new String();//VARIABLE QUE DETERMINARA LA RUTA DEL ARCHIVO A LEER.
        ruta = (".\\NOMINAS.pdf"); //SE ALMACENA LA RUTA DEL ARCHIVO A LEER. 

        try {
            PDDocument pd = PDDocument.load(ruta); //CARGAR EL PDF
            List l = pd.getDocumentCatalog().getAllPages();//NUMERO LAS PAGINAS DEL ARCHIVO
            Object[] obj = l.toArray();//METO EN UN OBJETO LA LISTA DE PAGINAS PARA MANIPULARLA
            for (int i = 0; i < l.size(); i++) {
                PDPage page = (PDPage) obj[i];//PAGE ES LA PAGINA 1 DE LA QUE CONSTA EL ARCHIVO
                PageFormat pageFormat = pd.getPageFormat(0);//PROPIEDADES DE LA PAGINA (FORMATO)
                Double d1 = new Double(pageFormat.getHeight());//ALTO
                Double d2 = new Double(pageFormat.getWidth());//ANCHO
                int width = d1.intValue();//ANCHO
                int eigth = 1024;//ALTO

                PDFTextStripperByArea stripper = new PDFTextStripperByArea();//COMPONENTE PARA ACCESO AL TEXTO
                Rectangle rect = new Rectangle(0, 0, width, eigth);//DEFNIR AREA DONDE SE BUSCARA EL TEXTO
                stripper.addRegion("area1", rect);//REGISTRAMOS LA REGION CON UN NOMBRE
                stripper.extractRegions(page);//EXTRAE TEXTO DEL AREA

                String contenido = new String();//CONTENIDO = A LO QUE CONTENGA EL AREA O REGION
                contenido = (stripper.getTextForRegion("area1"));
                String[] lines = contenido.split("[\\r\\n]+");
                String nombre = lines[1].substring(28, lines[1].length() - 10);
                PaginaNomina nomina = new PaginaNomina(page, nombre);
                paginasNomina.add(nomina);
            }
            Collections.sort(paginasNomina);
            // Create a new empty document
            PDDocument document = new PDDocument();

            for (int i = 0; i < paginasNomina.size(); i++) {
                System.out.println(paginasNomina.get(i).getNombre());
                document.addPage(paginasNomina.get(i).getPagina());
            }
            // Save the newly created document
            document.save("NominasOrdenadas.pdf");

            // finally make sure that the document is properly
            // closed.
            document.close();
            pd.close();//CERRAMOS OBJETO ACROBAT
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } //CATCH
    } //FOR

}

From source file:openstitcher.core.PDFRenderer.java

License:Open Source License

public static void render(Design design, String location, ArrayList<LegendEntry> legend)
        throws IOException, COSVisitorException {
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();
    document.addPage(page);
    PDFont font = PDType1Font.HELVETICA;
    PDPageContentStream contentStream = new PDPageContentStream(document, page);

    float pageWidth = page.getMediaBox().getWidth();
    float pageHeight = page.getMediaBox().getHeight();

    float sideMargin = 70.0f;
    float capsMargin = 30.0f;

    // draw the document title
    contentStream.beginText();/*from   w  w  w.  j a va  2  s . c  om*/
    contentStream.setFont(font, 24.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - 24.0f);
    contentStream.drawString(design.title);
    contentStream.endText();

    // draw the document author
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f));
    contentStream.drawString(design.author);
    contentStream.endText();

    // draw the document license
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(sideMargin, pageHeight - capsMargin - (24.0f + 12.0f + 12.0f));
    contentStream.drawString(design.license);
    contentStream.endText();

    // draw the physical size
    contentStream.beginText();
    contentStream.setFont(font, 12.0f);
    contentStream.moveTextPositionByAmount(pageWidth - sideMargin - 100.0f,
            pageHeight - capsMargin - (24.0f + 12.0f + 12.0f));
    contentStream.drawString(design.physicalSize);
    contentStream.endText();

    // draw the pattern
    float gridWidth = pageWidth - (sideMargin * 2);
    float widthPerCell = gridWidth / (float) design.pattern.getPatternWidth();
    float gridStartX = sideMargin;
    float gridStopX = sideMargin + (widthPerCell * design.pattern.getPatternWidth());
    float gridStartY = pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f);
    float gridStopY = (pageHeight - capsMargin - (24.0f + 12.0f + 12.0f + 12.0f))
            - (widthPerCell * design.pattern.getPatternHeight());

    // draw the pattern: background
    for (int i = 0; i < design.pattern.getPatternWidth(); i++) {
        for (int j = 0; j < design.pattern.getPatternHeight(); j++) {
            Yarn cellYarn = design.pattern.getPatternCell(i, j);
            if (cellYarn != null) {
                contentStream.setNonStrokingColor(cellYarn.color);
                contentStream.fillRect(gridStartX + (widthPerCell * i),
                        gridStartY - (widthPerCell * j) - widthPerCell, widthPerCell, widthPerCell);
            }

        }
    }

    // draw the pattern: grid outline
    contentStream.setStrokingColor(Color.black);
    for (int i = 0; i < design.pattern.getPatternWidth() + 1; i++) {
        // draw vertical lines
        float xCoord = gridStartX + (widthPerCell * i);
        if (i % 5 == 0) {
            contentStream.setLineWidth(2.0f);
        } else {
            contentStream.setLineWidth(1.0f);
        }
        contentStream.drawLine(xCoord, gridStartY, xCoord, gridStopY);
    }
    for (int i = 0; i < design.pattern.getPatternHeight() + 1; i++) {
        // draw horizontal lines
        float yCoord = gridStartY - (widthPerCell * i);
        if (i % 5 == 0) {
            contentStream.setLineWidth(2.0f);
        } else {
            contentStream.setLineWidth(1.0f);
        }
        contentStream.drawLine(gridStartX, yCoord, gridStopX, yCoord);
    }

    // draw the pattern: characters
    contentStream.setNonStrokingColor(Color.black);
    float centeringOffset = widthPerCell / 5.0f;
    for (int i = 0; i < design.pattern.getPatternWidth(); i++) {
        for (int j = 0; j < design.pattern.getPatternHeight(); j++) {
            Yarn cellYarn = design.pattern.getPatternCell(i, j);
            if (cellYarn != null) {
                int index = LegendEntry.findIndexByYarn(legend, cellYarn);
                if (index == -1) {
                    throw new RuntimeException("Cell did not exist in legend.");
                }
                contentStream.beginText();
                contentStream.setFont(font, widthPerCell);
                contentStream.moveTextPositionByAmount(gridStartX + (widthPerCell * i) + centeringOffset,
                        gridStartY - (widthPerCell * j) - widthPerCell + centeringOffset);
                contentStream.drawString(legend.get(index).character);
                contentStream.endText();
            }
        }
    }

    // draw the legend
    float legendWidth = pageWidth - (sideMargin * 2);
    float widthPerLegendCell = legendWidth / (float) legend.size();
    float legendStartX = sideMargin;
    float legendStopX = pageWidth - sideMargin;
    float legendStartY = capsMargin + 12.0f;
    float legendStopY = capsMargin;
    float legendCellPadding = 1.0f;
    float exampleCellWidth = 10.0f;

    for (int i = 0; i < legend.size(); i++) {
        // draw box
        contentStream.setNonStrokingColor(legend.get(i).yarn.color);
        contentStream.fillRect(legendStartX + legendCellPadding + (i * widthPerLegendCell),
                legendStopY + legendCellPadding, exampleCellWidth, exampleCellWidth);

        // draw character
        contentStream.beginText();
        contentStream.setNonStrokingColor(legend.get(i).fontColor);
        contentStream.setFont(font, 10.0f);
        contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + (i * widthPerLegendCell),
                legendStopY + legendCellPadding);
        contentStream.drawString(legend.get(i).character);
        contentStream.endText();

        // draw yarn name
        contentStream.beginText();
        contentStream.setNonStrokingColor(Color.black);
        contentStream.setFont(font, 10.0f);
        contentStream.moveTextPositionByAmount(legendStartX + legendCellPadding + exampleCellWidth
                + legendCellPadding + (i * widthPerLegendCell), legendStopY + legendCellPadding);
        contentStream.drawString(legend.get(i).yarn.name);
        contentStream.endText();
    }

    contentStream.close();
    document.save(location);
    document.close();
}

From source file:org.alfresco.repo.content.transform.OOoContentTransformerHelper.java

License:Open Source License

/**
 * This method produces an empty PDF file at the specified File location.
 * Apache's PDFBox is used to create the PDF file.
 *///from  w  ww .ja  va 2s .c om
private void produceEmptyPdfFile(File tempToFile) {
    // If improvement PDFBOX-914 is incorporated, we can do this with a straight call to
    // org.apache.pdfbox.TextToPdf.createPDFFromText(new StringReader(""));
    // https://issues.apache.org/jira/browse/PDFBOX-914

    PDDocument pdfDoc = null;
    PDPageContentStream contentStream = null;
    try {
        pdfDoc = new PDDocument();
        PDPage pdfPage = new PDPage();
        // Even though, we want an empty PDF, some libs (e.g. PDFRenderer) object to PDFs
        // that have literally nothing in them. So we'll put a content stream in it.
        contentStream = new PDPageContentStream(pdfDoc, pdfPage);
        pdfDoc.addPage(pdfPage);

        // Now write the in-memory PDF document into the temporary file.
        pdfDoc.save(tempToFile.getAbsolutePath());

    } catch (COSVisitorException cvx) {
        throw new ContentIOException("Error creating empty PDF file", cvx);
    } catch (IOException iox) {
        throw new ContentIOException("Error creating empty PDF file", iox);
    } finally {
        if (contentStream != null) {
            try {
                contentStream.close();
            } catch (IOException ignored) {
                // Intentionally empty
            }
        }
        if (pdfDoc != null) {
            try {
                pdfDoc.close();
            } catch (IOException ignored) {
                // Intentionally empty.
            }
        }
    }
}

From source file:org.apache.camel.component.pdf.PdfAppendTest.java

License:Apache License

@Test
public void testAppend() throws Exception {
    final String originalText = "Test";
    final String textToAppend = "Append";
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();/*  ww w . j  ava  2s .  com*/
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(originalText);
    contentStream.endText();
    contentStream.close();

    template.sendBodyAndHeader("direct:start", textToAppend, PdfHeaderConstants.PDF_DOCUMENT_HEADER_NAME,
            document);

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(ByteArrayOutputStream.class));
            try {
                PDDocument doc = PDDocument
                        .load(new ByteArrayInputStream(((ByteArrayOutputStream) body).toByteArray()));
                PDFTextStripper pdfTextStripper = new PDFTextStripper();
                String text = pdfTextStripper.getText(doc);
                assertEquals(2, doc.getNumberOfPages());
                assertThat(text, containsString(originalText));
                assertThat(text, containsString(textToAppend));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();

}

From source file:org.apache.camel.component.pdf.PdfAppendTest.java

License:Apache License

@Test
public void testAppendEncrypted() throws Exception {
    final String originalText = "Test";
    final String textToAppend = "Append";
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();/* www.  j ava2s . c om*/
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(originalText);
    contentStream.endText();
    contentStream.close();

    final String ownerPass = "ownerPass";
    final String userPass = "userPass";
    AccessPermission accessPermission = new AccessPermission();
    accessPermission.setCanExtractContent(false);
    StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass,
            accessPermission);
    protectionPolicy.setEncryptionKeyLength(128);

    document.protect(protectionPolicy);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    document.save(output);

    // Encryption happens after saving.
    PDDocument encryptedDocument = PDDocument.load(new ByteArrayInputStream(output.toByteArray()));

    Map<String, Object> headers = new HashMap<String, Object>();
    headers.put(PdfHeaderConstants.PDF_DOCUMENT_HEADER_NAME, encryptedDocument);
    headers.put(PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass));

    template.sendBodyAndHeaders("direct:start", textToAppend, headers);

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(ByteArrayOutputStream.class));
            try {
                PDDocument doc = PDDocument
                        .load(new ByteArrayInputStream(((ByteArrayOutputStream) body).toByteArray()));
                PDFTextStripper pdfTextStripper = new PDFTextStripper();
                String text = pdfTextStripper.getText(doc);
                assertEquals(2, doc.getNumberOfPages());
                assertThat(text, containsString(originalText));
                assertThat(text, containsString(textToAppend));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();

}