List of usage examples for org.apache.pdfbox.pdmodel PDPage PDPage
public PDPage(COSDictionary pageDictionary)
From source file:model.objects.Project.java
License:Apache License
/** * /*from w w w.j a v a 2s.com*/ * @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: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);//from www . j a v a 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(); 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);//from www . java 2 s .c o 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.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);// w w w .ja v a 2s . co 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);//from ww w .ja v a2 s . c o 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.camel.component.pdf.text.DefaultWriteStrategy.java
License:Apache License
@Override public PDDocument write(Collection<String> lines, PDDocument document) throws IOException { PDPage page = new PDPage(pdfConfiguration.getPageSize()); document.addPage(page);//ww w . ja v a2 s.c om float x = pdfConfiguration.getMarginLeft(); float y = page.getMediaBox().getHeight() - pdfConfiguration.getMarginTop(); float averageFontHeight = PdfUtils.getAverageFontHeight(pdfConfiguration.getFont(), pdfConfiguration.getFontSize()); float lineSpacing = averageFontHeight * 2; PDPageContentStream contentStream = initializeContentStream(document, page); for (String line : lines) { writeLine(x, y, line, contentStream); y -= lineSpacing; if (goToNextPage(y)) { contentStream.close(); page = new PDPage(pdfConfiguration.getPageSize()); document.addPage(page); contentStream = initializeContentStream(document, page); y = page.getMediaBox().getHeight() - pdfConfiguration.getMarginTop(); } } contentStream.close(); return document; }
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();//from w w w . j a v a 2 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.dspace.disseminate.CitationDocument.java
License:BSD License
/** * Creates a/*from w ww. ja va 2 s.com*/ * 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(); } }
From source file:org.dspace.disseminate.CitationDocumentServiceImpl.java
License:BSD License
@Override public File makeCitedDocument(Context context, Bitstream bitstream) throws IOException, SQLException, AuthorizeException { PDDocument document = new PDDocument(); PDDocument sourceDocument = new PDDocument(); try {//from w w w . j a v a 2s . c o m Item item = (Item) bitstreamService.getParentObject(context, bitstream); sourceDocument = sourceDocument.load(bitstreamService.retrieve(context, bitstream)); PDPage coverPage = new PDPage(PDRectangle.LETTER); // TODO: needs to be configurable generateCoverPage(context, 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(); } }
From source file:org.esteco.jira.pdf.UsingTextMatrix.java
License:Apache License
/** * creates a sample document with some text using a text matrix. * * @param message The message to write in the file. * @param outfile The resulting PDF.//w w w.j ava 2 s .c o m * @throws IOException If there is an error writing the data. */ public void doIt(String message, String outfile) throws IOException { // the document PDDocument doc = null; try { doc = new PDDocument(); // Page 1 PDFont font = PDType1Font.HELVETICA; PDPage page = new PDPage(PDRectangle.A4); doc.addPage(page); float fontSize = 12.0f; PDRectangle pageSize = page.getMediaBox(); float centeredXPosition = (pageSize.getWidth() - fontSize / 1000f) / 2f; float stringWidth = font.getStringWidth(message); float centeredYPosition = (pageSize.getHeight() - (stringWidth * fontSize) / 1000f) / 3f; PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // counterclockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextMatrix(Matrix.getRotateInstance(i * Math.PI * 0.25, centeredXPosition, pageSize.getHeight() - centeredYPosition)); contentStream.showText(message + " " + i); } // clockwise rotation for (int i = 0; i < 8; i++) { contentStream.setTextMatrix( Matrix.getRotateInstance(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition)); contentStream.showText(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 2 page = new PDPage(PDRectangle.A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); // text scaling and translation for (int i = 0; i < 10; i++) { contentStream.setTextMatrix(new Matrix(12 + (i * 6), 0, 0, 12 + (i * 6), 100, 100 + i * 50)); contentStream.showText(message + " " + i); } contentStream.endText(); contentStream.close(); // Page 3 page = new PDPage(PDRectangle.A4); doc.addPage(page); fontSize = 1.0f; contentStream = new PDPageContentStream(doc, page, AppendMode.OVERWRITE, false); contentStream.setFont(font, fontSize); contentStream.beginText(); int i = 0; // text scaling combined with rotation contentStream.setTextMatrix(new Matrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.setTextMatrix(new Matrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5f)); contentStream.showText(message + " " + i++); contentStream.endText(); contentStream.close(); doc.save(outfile); } finally { if (doc != null) { doc.close(); } } }