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: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);//  w  ww .ja  va  2  s .co m
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    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();

}

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

License:Apache License

private OutputStream doCreate(Exchange exchange)
        throws IOException, BadSecurityHandlerException, COSVisitorException {
    LOG.debug("Got {} operation, going to create and write provided string to pdf document.",
            pdfConfiguration.getOperation());
    String body = exchange.getIn().getBody(String.class);
    PDDocument document = new PDDocument();
    StandardProtectionPolicy protectionPolicy = exchange.getIn().getHeader(PROTECTION_POLICY_HEADER_NAME,
            StandardProtectionPolicy.class);
    appendToPdfDocument(body, document, protectionPolicy);
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    document.save(byteArrayOutputStream);
    return byteArrayOutputStream;
}

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

License:Apache License

@Test
public void testExtractText() throws Exception {
    final String expectedText = "Test string";
    PDDocument document = new PDDocument();
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);/*from   w w  w .j  ava 2  s  . c  o m*/
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(expectedText);
    contentStream.endText();
    contentStream.close();

    template.sendBody("direct:start", document);

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(String.class));
            assertThat((String) body, containsString(expectedText));
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();
}

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

License:Apache License

@Test
public void testExtractTextFromEncrypted() throws Exception {
    final String ownerPass = "ownerPass";
    final String userPass = "userPass";
    AccessPermission accessPermission = new AccessPermission();
    accessPermission.setCanExtractContent(false);
    StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy(ownerPass, userPass,
            accessPermission);/*ww  w .  j  a va2  s . co  m*/
    protectionPolicy.setEncryptionKeyLength(128);
    PDDocument document = new PDDocument();

    final String expectedText = "Test string";
    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    PDPageContentStream contentStream = new PDPageContentStream(document, page);
    contentStream.setFont(PDType1Font.HELVETICA, 12);
    contentStream.beginText();
    contentStream.moveTextPositionByAmount(20, 400);
    contentStream.drawString(expectedText);
    contentStream.endText();
    contentStream.close();

    document.protect(protectionPolicy);

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

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

    template.sendBodyAndHeader("direct:start", encryptedDocument,
            PdfHeaderConstants.DECRYPTION_MATERIAL_HEADER_NAME, new StandardDecryptionMaterial(userPass));

    resultEndpoint.setExpectedMessageCount(1);
    resultEndpoint.expectedMessagesMatches(new Predicate() {
        @Override
        public boolean matches(Exchange exchange) {
            Object body = exchange.getIn().getBody();
            assertThat(body, instanceOf(String.class));
            assertThat((String) body, containsString(expectedText));
            return true;
        }
    });
    resultEndpoint.assertIsSatisfied();
    document.isEncrypted();
}

From source file:org.apache.fop.render.pdf.PDFRotateTestCase.java

License:Apache License

@Test
public void test() throws Exception {
    ImageConverterPDF2G2D i = new ImageConverterPDF2G2D();
    ImageInfo imgi = new ImageInfo("a", "b");
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage();
    page.setRotation(90);//w  ww  .j  a v a 2  s  .c  o m
    doc.addPage(page);
    Image img = new ImagePDF(imgi, doc);
    ImageGraphics2D ig = (ImageGraphics2D) i.convert(img, null);
    Rectangle2D rect = new Rectangle2D.Float(0, 0, 100, 100);

    PSGraphics2D g2d = new PSPDFGraphics2D(true);
    GraphicContext gc = new GraphicContext();
    g2d.setGraphicContext(gc);
    ig.getGraphics2DImagePainter().paint(g2d, rect);
    Assert.assertEquals(g2d.getTransform().getShearX(), 0.16339869281045735);
}

From source file:org.apache.openmeetings.web.room.wb.WbPanel.java

License:Apache License

@Override
protected void processWbAction(WbAction a, JSONObject obj, AjaxRequestTarget target) throws IOException {
    Client c = rp.getClient();// w w w . j a v a2  s  . c o m
    if (c == null) {
        return;
    }
    switch (a) {
    case createObj:
    case modifyObj: {
        JSONObject o = obj.optJSONObject("obj");
        if (o != null && "pointer".equals(o.getString(ATTR_TYPE))) {
            sendWbOthers(a, obj);
            return;
        }
    }
        break;
    case downloadPdf: {
        boolean moder = c.hasRight(Room.Right.moderator);
        Room r = rp.getRoom();
        if ((moder && !r.isHidden(RoomElement.ActionMenu)) || (!moder && r.isAllowUserQuestions())) {
            try (PDDocument doc = new PDDocument()) {
                JSONArray arr = obj.getJSONArray("slides");
                for (int i = 0; i < arr.length(); ++i) {
                    String base64Image = arr.getString(i).split(",")[1];
                    byte[] bb = Base64.decodeBase64(base64Image);
                    BufferedImage img = ImageIO.read(new ByteArrayInputStream(bb));
                    float width = img.getWidth();
                    float height = img.getHeight();
                    PDPage page = new PDPage(new PDRectangle(width, height));
                    PDImageXObject pdImageXObject = LosslessFactory.createFromImage(doc, img);
                    try (PDPageContentStream contentStream = new PDPageContentStream(doc, page,
                            AppendMode.APPEND, false)) {
                        contentStream.drawImage(pdImageXObject, 0, 0, width, height);
                    }
                    doc.addPage(page);
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                doc.save(baos);
                rp.startDownload(target, baos.toByteArray());
            }
        }
        return;
    }
    case loadVideos: {
        StringBuilder sb = new StringBuilder("WbArea.initVideos(");
        JSONArray arr = new JSONArray();
        for (Entry<Long, Whiteboard> entry : wbm.list(roomId)) {
            Whiteboard wb = entry.getValue();
            for (JSONObject o : wb.list()) {
                String ft = o.optString(ATTR_FILE_TYPE);
                if (BaseFileItem.Type.Recording.name().equals(ft)
                        || BaseFileItem.Type.Video.name().equals(ft)) {
                    JSONObject _sts = o.optJSONObject(PARAM_STATUS);
                    if (_sts == null) {
                        continue;
                    }
                    JSONObject sts = new JSONObject(_sts.toString()); //copy
                    sts.put("pos", sts.getDouble("pos")
                            + (System.currentTimeMillis() - sts.getLong(PARAM_UPDATED)) * 1. / 1000);
                    arr.put(new JSONObject().put("wbId", wb.getId()).put("uid", o.getString("uid"))
                            .put(ATTR_SLIDE, o.getString(ATTR_SLIDE)).put(PARAM_STATUS, sts));
                }
            }
        }
        sb.append(arr.toString()).append(");");
        target.appendJavaScript(sb);
        return;
    }
    default:
        break;
    }

    //presenter-right
    if (c.hasRight(Right.presenter)) {
        switch (a) {
        case createWb: {
            Whiteboard wb = wbm.add(roomId, c.getUser().getLanguageId());
            sendWbAll(WbAction.createWb, getAddWbJson(wb));
        }
            break;
        case removeWb: {
            long id = obj.optLong("wbId", -1);
            if (id > -1) {
                wbm.remove(roomId, id);
                sendWbAll(WbAction.removeWb, obj);
            }
        }
            break;
        case activateWb: {
            long _id = obj.optLong("wbId", -1);
            if (_id > -1) {
                wbm.activate(roomId, _id);
                sendWbAll(WbAction.activateWb, obj);
            }
        }
            break;
        case renameWb: {
            Whiteboard wb = wbm.get(roomId).get(obj.optLong("wbId", -1));
            if (wb != null) {
                wbm.update(roomId, wb.setName(obj.getString("name")));
                sendWbAll(WbAction.renameWb, obj);
            }
        }
            break;
        case setSlide: {
            Whiteboard wb = wbm.get(roomId).get(obj.optLong("wbId", -1));
            if (wb != null) {
                wb.setSlide(obj.optInt(ATTR_SLIDE, 0));
                wbm.update(roomId, wb);
                sendWbOthers(WbAction.setSlide, obj);
            }
        }
            break;
        case clearAll: {
            clearAll(roomId, obj.getLong("wbId"));
        }
            break;
        case setSize: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            wb.setWidth(obj.getInt(ATTR_WIDTH));
            wb.setHeight(obj.getInt(ATTR_HEIGHT));
            wb.setZoom(obj.getDouble(ATTR_ZOOM));
            wb.setZoomMode(ZoomMode.valueOf(obj.getString("zoomMode")));
            wbm.update(roomId, wb);
            sendWbOthers(WbAction.setSize, getAddWbJson(wb));
        }
            break;
        default:
            break;
        }
    }
    //wb-right
    if (c.hasRight(Right.presenter) || c.hasRight(Right.whiteBoard)) {
        switch (a) {
        case createObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONObject o = obj.getJSONObject("obj");
            wb.put(o.getString("uid"), o);
            wbm.update(roomId, wb);
            addUndo(wb.getId(), new UndoObject(UndoObject.Type.add, o));
            sendWbOthers(WbAction.createObj, obj);
        }
            break;
        case modifyObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = obj.getJSONArray("obj");
            JSONArray undo = new JSONArray();
            for (int i = 0; i < arr.length(); ++i) {
                JSONObject _o = arr.getJSONObject(i);
                String uid = _o.getString("uid");
                JSONObject po = wb.get(uid);
                if (po != null) {
                    undo.put(po);
                    wb.put(uid, _o);
                }
            }
            if (arr.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.modify, undo));
            }
            sendWbOthers(WbAction.modifyObj, obj);
        }
            break;
        case deleteObj: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = obj.getJSONArray("obj");
            JSONArray undo = new JSONArray();
            for (int i = 0; i < arr.length(); ++i) {
                JSONObject _o = arr.getJSONObject(i);
                JSONObject u = wb.remove(_o.getString("uid"));
                if (u != null) {
                    undo.put(u);
                }
            }
            if (undo.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.remove, undo));
            }
            sendWbAll(WbAction.deleteObj, obj);
        }
            break;
        case clearSlide: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            JSONArray arr = wb.clearSlide(obj.getInt(ATTR_SLIDE));
            if (arr.length() != 0) {
                wbm.update(roomId, wb);
                addUndo(wb.getId(), new UndoObject(UndoObject.Type.remove, arr));
            }
            sendWbAll(WbAction.clearSlide, obj);
        }
            break;
        case save:
            wb2save = obj.getLong("wbId");
            fileName.open(target);
            break;
        case undo: {
            Long wbId = obj.getLong("wbId");
            UndoObject uo = getUndo(wbId);
            if (uo != null) {
                Whiteboard wb = wbm.get(roomId).get(wbId);
                switch (uo.getType()) {
                case add: {
                    JSONObject o = new JSONObject(uo.getObject());
                    wb.remove(o.getString("uid"));
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.deleteObj, obj.put("obj", new JSONArray().put(o)));
                }
                    break;
                case remove: {
                    JSONArray arr = new JSONArray(uo.getObject());
                    for (int i = 0; i < arr.length(); ++i) {
                        JSONObject o = arr.getJSONObject(i);
                        wb.put(o.getString("uid"), o);
                    }
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.createObj, obj.put("obj", new JSONArray(uo.getObject())));
                }
                    break;
                case modify: {
                    JSONArray arr = new JSONArray(uo.getObject());
                    for (int i = 0; i < arr.length(); ++i) {
                        JSONObject o = arr.getJSONObject(i);
                        wb.put(o.getString("uid"), o);
                    }
                    wbm.update(roomId, wb);
                    sendWbAll(WbAction.modifyObj, obj.put("obj", arr));
                }
                    break;
                }
            }
        }
            break;
        case videoStatus: {
            Whiteboard wb = wbm.get(roomId).get(obj.getLong("wbId"));
            String uid = obj.getString("uid");
            JSONObject po = wb.get(uid);
            if (po != null && "video".equals(po.getString(ATTR_TYPE))) {
                JSONObject ns = obj.getJSONObject(PARAM_STATUS);
                po.put(PARAM_STATUS, ns.put(PARAM_UPDATED, System.currentTimeMillis()));
                wbm.update(roomId, wb.put(uid, po));
                obj.put(ATTR_SLIDE, po.getInt(ATTR_SLIDE));
                sendWbAll(WbAction.videoStatus, obj);
            }
        }
            break;
        default:
            break;
        }
    }
}

From source file:org.apache.pdflens.example.HelloWorld.java

License:Apache License

/**
 * create the second sample document from the PDF file format specification.
 *
 * @param file The file to write the PDF to.
 * @param message The message to write in the file.
 *
 * @throws IOException If there is an error writing the data.
 * @throws COSVisitorException If there is an error writing the PDF.
 *//*  www  .j a v  a2s .c  o  m*/
public void doIt(String file, String message) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

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

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.beginText();
        contentStream.setFont(font, 12);
        contentStream.moveTextPositionByAmount(100, 700);
        contentStream.drawString(message);
        contentStream.endText();
        contentStream.close();
        doc.save(file);

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

From source file:org.apache.pdflens.example.HelloWorldMutiPage.java

License:Apache License

/**
 * create the second sample document from the PDF file format specification.
 *
 * @param file The file to write the PDF to.
 * @param message The message to write in the file.
 *
 * @throws IOException If there is an error writing the data.
 * @throws COSVisitorException If there is an error writing the PDF.
 *//*from  www . j  a  v  a 2 s .  c  o  m*/
public void doIt(String file, String message) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        for (int i = 0; i < 10; i++) {
            PDPage page = generatePage(message + i, doc);
            doc.addPage(page);
        }

        doc.save(file);

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

From source file:org.data2semantics.annotate.D2S_SampleAnnotation.java

License:Apache License

/**
 * This will create a doucument showing various annotations.
 * /*from   w w w.ja v a  2s. com*/
 * @param args
 *            The command line arguments.
 * 
 * @throws Exception
 *             If there is an error parsing the document.
 */
public static void main(String[] args) throws Exception {

    PDDocument document = new PDDocument();

    try {
        PDPage page = new PDPage();
        document.addPage(page);
        List annotations = page.getAnnotations();

        // Setup some basic reusable objects/constants
        // Annotations themselves can only be used once!

        float inch = 72;
        PDGamma colourRed = new PDGamma();
        colourRed.setR(1);
        PDGamma colourBlue = new PDGamma();
        colourBlue.setB(1);
        PDGamma colourBlack = new PDGamma();

        PDBorderStyleDictionary borderThick = new PDBorderStyleDictionary();
        borderThick.setWidth(inch / 12); // 12th inch
        PDBorderStyleDictionary borderThin = new PDBorderStyleDictionary();
        borderThin.setWidth(inch / 72); // 1 point
        PDBorderStyleDictionary borderULine = new PDBorderStyleDictionary();
        borderULine.setStyle(PDBorderStyleDictionary.STYLE_UNDERLINE);
        borderULine.setWidth(inch / 72); // 1 point

        float pw = page.getMediaBox().getUpperRightX();
        float ph = page.getMediaBox().getUpperRightY();

        // First add some text, two lines we'll add some annotations to this
        // later

        PDFont font = PDType1Font.HELVETICA_BOLD;

        PDPageContentStream contentStream = new PDPageContentStream(document, page);
        contentStream.beginText();
        contentStream.setFont(font, 18);
        contentStream.moveTextPositionByAmount(inch, ph - inch - 18);
        contentStream.drawString("PDFBox");
        contentStream.moveTextPositionByAmount(0, -(inch / 2));
        contentStream.drawString("Click Here");
        contentStream.endText();

        contentStream.close();

        // Now add the markup annotation, a highlight to PDFBox text
        PDAnnotationTextMarkup txtMark = new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT);
        txtMark.setColour(colourBlue);
        txtMark.setConstantOpacity((float) 0.2); // Make the highlight 20%
        // transparent

        // Set the rectangle containing the markup

        float textWidth = (font.getStringWidth("PDFBox") / 1000) * 18;
        PDRectangle position = new PDRectangle();
        position.setLowerLeftX(inch);
        position.setLowerLeftY(ph - inch - 18);
        position.setUpperRightX(72 + textWidth);
        position.setUpperRightY(ph - inch);
        txtMark.setRectangle(position);

        // work out the points forming the four corners of the annotations
        // set out in anti clockwise form (Completely wraps the text)
        // OK, the below doesn't match that description.
        // It's what acrobat 7 does and displays properly!
        float[] quads = new float[8];

        quads[0] = position.getLowerLeftX(); // x1
        quads[1] = position.getUpperRightY() - 2; // y1
        quads[2] = position.getUpperRightX(); // x2
        quads[3] = quads[1]; // y2
        quads[4] = quads[0]; // x3
        quads[5] = position.getLowerLeftY() - 2; // y3
        quads[6] = quads[2]; // x4
        quads[7] = quads[5]; // y5

        txtMark.setQuadPoints(quads);
        txtMark.setContents("Highlighted since it's important");

        annotations.add(txtMark);

        // Now add the link annotation, so the clickme works
        PDAnnotationLink txtLink = new PDAnnotationLink();
        txtLink.setBorderStyle(borderULine);

        // Set the rectangle containing the link

        textWidth = (font.getStringWidth("Click Here") / 1000) * 18;
        position = new PDRectangle();
        position.setLowerLeftX(inch);
        position.setLowerLeftY(ph - (float) (1.5 * inch) - 20); // down a
        // couple of
        // points
        position.setUpperRightX(72 + textWidth);
        position.setUpperRightY(ph - (float) (1.5 * inch));
        txtLink.setRectangle(position);

        // add an action
        PDActionURI action = new PDActionURI();
        action.setURI("http://www.pdfbox.org");
        txtLink.setAction(action);

        annotations.add(txtLink);

        // Now draw a few more annotations

        PDAnnotationSquareCircle aCircle = new PDAnnotationSquareCircle(
                PDAnnotationSquareCircle.SUB_TYPE_CIRCLE);
        aCircle.setContents("Circle Annotation");
        aCircle.setInteriorColour(colourRed); // Fill in circle in red
        aCircle.setColour(colourBlue); // The border itself will be blue
        aCircle.setBorderStyle(borderThin);

        // Place the annotation on the page, we'll make this 1" round
        // 3" down, 1" in on the page

        position = new PDRectangle();
        position.setLowerLeftX(inch);
        position.setLowerLeftY(ph - (3 * inch) - inch); // 1" height, 3"
        // down
        position.setUpperRightX(2 * inch); // 1" in, 1" width
        position.setUpperRightY(ph - (3 * inch)); // 3" down
        aCircle.setRectangle(position);

        // add to the annotations on the page
        annotations.add(aCircle);

        // Now a square annotation

        PDAnnotationSquareCircle aSquare = new PDAnnotationSquareCircle(
                PDAnnotationSquareCircle.SUB_TYPE_SQUARE);
        aSquare.setContents("Square Annotation");
        aSquare.setColour(colourRed); // Outline in red, not setting a fill
        aSquare.setBorderStyle(borderThick);

        // Place the annotation on the page, we'll make this 1" (72points)
        // square
        // 3.5" down, 1" in from the right on the page

        position = new PDRectangle(); // Reuse the variable, but note it's a
        // new object!
        position.setLowerLeftX(pw - (2 * inch)); // 1" in from right, 1"
        // wide
        position.setLowerLeftY(ph - (float) (3.5 * inch) - inch); // 1" height, 3.5"
        // down
        position.setUpperRightX(pw - inch); // 1" in from right
        position.setUpperRightY(ph - (float) (3.5 * inch)); // 3.5" down
        aSquare.setRectangle(position);

        // add to the annotations on the page
        annotations.add(aSquare);

        // Now we want to draw a line between the two, one end with an open
        // arrow

        PDAnnotationLine aLine = new PDAnnotationLine();

        aLine.setEndPointEndingStyle(PDAnnotationLine.LE_OPEN_ARROW);
        aLine.setContents("Circle->Square");
        aLine.setCaption(true); // Make the contents a caption on the line

        // Set the rectangle containing the line

        position = new PDRectangle(); // Reuse the variable, but note it's a
        // new object!
        position.setLowerLeftX(2 * inch); // 1" in + width of circle
        position.setLowerLeftY(ph - (float) (3.5 * inch) - inch); // 1" height, 3.5"
        // down
        position.setUpperRightX(pw - inch - inch); // 1" in from right, and
        // width of square
        position.setUpperRightY(ph - (3 * inch)); // 3" down (top of circle)
        aLine.setRectangle(position);

        // Now set the line position itself
        float[] linepos = new float[4];
        linepos[0] = 2 * inch; // x1 = rhs of circle
        linepos[1] = ph - (float) (3.5 * inch); // y1 halfway down circle
        linepos[2] = pw - (2 * inch); // x2 = lhs of square
        linepos[3] = ph - (4 * inch); // y2 halfway down square
        aLine.setLine(linepos);

        aLine.setBorderStyle(borderThick);
        aLine.setColour(colourBlack);

        // add to the annotations on the page
        annotations.add(aLine);

        // Finally all done

        document.save("testAnnotation.pdf");
    } finally {
        document.close();
    }
}

From source file:org.dspace.disseminate.CitationDocument.java

License:BSD License

/**
 * Creates a//from ww  w. jav a 2s.c o  m
 * cited document from the given bitstream of the given item. This
 * requires that bitstream is contained in item.
 * <p>
 * The Process for adding a cover page is as follows:
 * <ol>
 *  <li> Load source file into PdfReader and create a
 *     Document to put our cover page into.</li>
 *  <li> Create cover page and add content to it.</li>
 *  <li> Concatenate the coverpage and the source
 *     document.</li>
 * </p>
 *
 * @param bitstream The source bitstream being cited. This must be a PDF.
 * @return The temporary File that is the finished, cited document.
 * @throws java.io.FileNotFoundException
 * @throws SQLException
 * @throws org.dspace.authorize.AuthorizeException
 */
public File makeCitedDocument(Bitstream bitstream)
        throws IOException, SQLException, AuthorizeException, COSVisitorException {
    PDDocument document = new PDDocument();
    PDDocument sourceDocument = new PDDocument();
    try {
        Item item = (Item) bitstream.getParentObject();
        sourceDocument = sourceDocument.load(bitstream.retrieve());
        PDPage coverPage = new PDPage(PDPage.PAGE_SIZE_LETTER);
        generateCoverPage(document, coverPage, item);
        addCoverPageToDocument(document, sourceDocument, coverPage);

        document.save(tempDir.getAbsolutePath() + "/bitstream.cover.pdf");
        return new File(tempDir.getAbsolutePath() + "/bitstream.cover.pdf");
    } finally {
        sourceDocument.close();
        document.close();
    }
}