List of usage examples for org.apache.pdfbox.pdmodel PDPage getMediaBox
public PDRectangle getMediaBox()
From source file:org.dspace.disseminate.CitationDocumentServiceImpl.java
License:BSD License
@Override public void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin, String[][] content, PDFont font, int fontSize, boolean cellBorders) throws IOException { final int rows = content.length; final int cols = content[0].length; final float rowHeight = 20f; final float tableWidth = page.getMediaBox().getWidth() - (2 * margin); final float tableHeight = rowHeight * rows; final float colWidth = tableWidth / (float) cols; final float cellMargin = 5f; if (cellBorders) { //draw the rows float nexty = y; for (int i = 0; i <= rows; i++) { contentStream.drawLine(margin, nexty, margin + tableWidth, nexty); nexty -= rowHeight;/*from w w w . ja v a 2 s. c o m*/ } //draw the columns float nextx = margin; for (int i = 0; i <= cols; i++) { contentStream.drawLine(nextx, y, nextx, y - tableHeight); nextx += colWidth; } } //now add the text contentStream.setFont(font, fontSize); float textx = margin + cellMargin; float texty = y - 15; for (int i = 0; i < content.length; i++) { for (int j = 0; j < content[i].length; j++) { String text = content[i][j]; contentStream.beginText(); contentStream.moveTextPositionByAmount(textx, texty); contentStream.drawString(text); contentStream.endText(); textx += colWidth; } texty -= rowHeight; textx = margin + cellMargin; } }
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./* ww w . j a va2 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(); } } }
From source file:org.mycore.media.MCRMediaPDFParser.java
License:Open Source License
/** * Parse file and store metadata in related Object. * // www.ja v a 2s .co m * @return MCRMediaObject * can be held any MCRMediaObject * @see MCRMediaObject#clone() */ @SuppressWarnings("unchecked") public synchronized MCRMediaObject parse(File file) throws Exception { if (!file.exists()) throw new IOException("File \"" + file.getName() + "\" doesn't exists!"); MCRPDFObject media = new MCRPDFObject(); LOGGER.info("parse " + file.getName() + "..."); PDDocument pdf = PDDocument.load(file); try { media.fileName = file.getName(); media.fileSize = file.length(); media.folderName = (file.getAbsolutePath()).replace(file.getName(), ""); PDPageTree pages = pdf.getDocumentCatalog().getPages(); media.numPages = pdf.getNumberOfPages(); PDPage page = (PDPage) pages.get(0); PDRectangle rect = page.getMediaBox(); media.width = Math.round(rect.getWidth()); media.height = Math.round(rect.getHeight()); PDDocumentInformation info = pdf.getDocumentInformation(); if (info != null) { media.tags = new MCRMediaTagObject(); media.tags.author = info.getAuthor(); media.tags.creator = info.getCreator(); media.tags.producer = info.getProducer(); media.tags.title = info.getTitle(); media.tags.subject = info.getSubject(); media.tags.keywords = info.getKeywords(); } } catch (Exception e) { LOGGER.error(e.getMessage()); throw new Exception(e.getMessage()); } finally { pdf.close(); } return media; }
From source file:org.nmrfx.processor.gui.graphicsio.PDFWriter.java
License:Open Source License
public void create(boolean landScape, double width, double height, String fileName) throws GraphicsIOException { // the document this.landScape = landScape; this.fileName = fileName; doc = new PDDocument(); try {/*from w w w.ja va 2 s .c om*/ PDPage page = new PDPage(PDRectangle.LETTER); doc.addPage(page); PDRectangle pageSize = page.getMediaBox(); pageWidth = pageSize.getWidth(); pageHeight = pageSize.getHeight(); contentStream = new PDPageContentStream(doc, page, false, false); // add the rotation using the current transformation matrix // including a translation of pageWidth to use the lower left corner as 0,0 reference if (landScape) { page.setRotation(90); contentStream.transform(new Matrix(0, 1, -1, 0, pageWidth, 0)); } } catch (IOException ioE) { throw new GraphicsIOException(ioE.getMessage()); } }
From source file:org.pdfgal.pdfgal.utils.impl.WatermarkUtilsImpl.java
License:Open Source License
@Override public void addWatermark(final PDDocument doc, final PDPage page, final Color color, final String text, final WatermarkPosition watermarkPosition) throws IOException, WatermarkOutOfLengthException { if (doc != null && page != null && color != null && StringUtils.isNotBlank(text) && watermarkPosition != null) { // Attributes are extrated from the watermarkPosition argument. Double rotationAngle = 0D; Double rotationTX = 0D;//from w ww . j a va 2s .c o m Double rotationTY = 0D; Integer maxLength = 0; if (page.getMediaBox().getHeight() > page.getMediaBox().getWidth()) { // Page is portrait rotationAngle = watermarkPosition.getRotationAnglePortrait(); rotationTX = watermarkPosition.getRotationTXPortrait(); rotationTY = watermarkPosition.getRotationTYPortrait(); maxLength = watermarkPosition.getMaxLengthPortrait(); } else { // Page is landscape rotationAngle = watermarkPosition.getRotationAngleLandscape(); rotationTX = watermarkPosition.getRotationTXLandscape(); rotationTY = watermarkPosition.getRotationTYLandscape(); maxLength = watermarkPosition.getMaxLengthLandscape(); } // In case text is too large, an exception is thrown. if (text.length() > maxLength) { throw new WatermarkOutOfLengthException(Constants.WATERMARK_OUT_OF_LENGTH_EXCEPTION_MESSAGE); } final PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true); contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.setNonStrokingColor(color); contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA, 70); contentStream.setTextRotation(rotationAngle, rotationTX, rotationTY); // Text is centered final Integer size = (maxLength * 2) - text.length(); final String centeredText = StringUtils.center(text, size); contentStream.drawString(centeredText); contentStream.endText(); contentStream.close(); } }
From source file:org.pdfgal.pdfgal.validator.impl.PDFGalValidatorImpl.java
License:Open Source License
@Override public boolean allLandscape(final String path) { boolean result = true; PDDocument document;/*from ww w. java2 s . c o m*/ try { document = PDDocument.load(path); @SuppressWarnings("unchecked") final List<PDPage> pagesList = document.getDocumentCatalog().getAllPages(); if (CollectionUtils.isNotEmpty(pagesList)) { for (final PDPage page : pagesList) { if ((page != null) && (page.getMediaBox() != null) && (page.getMediaBox().getHeight() > page.getMediaBox().getWidth())) { result = false; break; } } } document.close(); } catch (final IOException e) { result = false; } return result; }
From source file:org.pensco.CreateStatementsOp.java
License:Open Source License
protected Blob buildPDF(String inCustomer, Calendar inStart, Calendar inEnd) throws IOException, COSVisitorException { Blob result = null;// w w w . j a va2s . c o m PDDocument pdfDoc = new PDDocument(); PDPage page = new PDPage(); pdfDoc.addPage(page); PDRectangle rect = page.getMediaBox(); float rectH = rect.getHeight(); PDFont font = PDType1Font.HELVETICA; PDFont fontBold = PDType1Font.HELVETICA_BOLD; PDFont fontOblique = PDType1Font.HELVETICA_OBLIQUE; PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page); int line = 0; contentStream.beginText(); contentStream.setFont(fontOblique, 10); contentStream.moveTextPositionByAmount(230, 20); contentStream.drawString("(Statement randomly generated)"); contentStream.endText(); line += 3; contentStream.beginText(); contentStream.setFont(fontBold, 12); contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line)); contentStream.drawString(inCustomer); contentStream.endText(); contentStream.beginText(); contentStream.setFont(fontBold, 12); contentStream.moveTextPositionByAmount(300, rectH - 20 * (++line)); contentStream.drawString( "Statement from " + yyyyMMdd.format(inStart.getTime()) + " to " + yyyyMMdd.format(inEnd.getTime())); contentStream.endText(); line += 3; statementLines = ToolsMisc.randomInt(3, 9); boolean isDebit = false; for (int i = 1; i <= statementLines; ++i) { contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(100, rectH - 20 * line); contentStream.drawString("" + i); contentStream.endText(); contentStream.beginText(); contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(120, rectH - 20 * line); isDebit = ToolsMisc.randomInt(0, 10) > 7; if (isDebit) { contentStream.drawString("Withdraw Funds to account " + MiscUtils.getSomeUID(6)); } else { contentStream.drawString("Add Funds to account " + MiscUtils.getSomeUID(6)); } contentStream.endText(); contentStream.beginText(); if (isDebit) { contentStream.setFont(fontOblique, 12); contentStream.moveTextPositionByAmount(350, rectH - 20 * line); } else { contentStream.setFont(font, 12); contentStream.moveTextPositionByAmount(450, rectH - 20 * line); } contentStream.drawString("" + ToolsMisc.randomInt(1000, 9000) + "." + ToolsMisc.randomInt(10, 90)); contentStream.endText(); line += 1; } contentStream.close(); contentStream = null; if (logoImage != null) { PDXObjectImage ximage = new PDPixelMap(pdfDoc, logoImage); contentStream = new PDPageContentStream(pdfDoc, page, true, true); contentStream.endMarkedContentSequence(); contentStream.drawXObject(ximage, 10, rectH - 20 - ximage.getHeight(), ximage.getWidth(), ximage.getHeight()); contentStream.close(); contentStream = null; } result = MiscUtils.saveInTempFile(pdfDoc); pdfDoc.close(); return result; }
From source file:org.primaresearch.pdf.PageToPdfConverterUsingPdfBox.java
License:Apache License
private void addPage(PDDocument doc, Page page) { try {/*from w w w . j a v a 2 s. c om*/ // Create a new blank page and add it to the document //TODO Use image DPI and size //The measurement unit of the PDF is point (1 Point = 0.0352777778 cm) //For now: Set the PDF size to the PAGE size (1px = 1pt) //PDPage pdfPage = new PDPage(PDPage.PAGE_SIZE_A4); PDPage pdfPage = new PDPage(new PDRectangle(page.getLayout().getWidth(), page.getLayout().getHeight())); doc.addPage(pdfPage); if (DEBUG) { System.out.println("Mediabox width: " + pdfPage.getMediaBox().getWidth()); System.out.println("Mediabox height: " + pdfPage.getMediaBox().getHeight()); } // Start a new content stream which will "hold" the to be created content PDPageContentStream contentStream = new PDPageContentStream(doc, pdfPage); try { addText(contentStream, page); // Define a text content stream using the selected font, moving the cursor and drawing the text "Hello World" //contentStream.beginText(); //contentStream.setFont( font, 12 ); //contentStream.moveTextPositionByAmount( 100, 700 ); //contentStream.drawString( "Hello World" ); //contentStream.endText(); } finally { // Make sure that the content stream is closed: contentStream.close(); } } catch (Exception exc) { exc.printStackTrace(); } }
From source file:org.xwiki.test.misc.PDFTest.java
License:Open Source License
/** * Code adapted from http://www.docjar.com/html/api/org/apache/pdfbox/examples/pdmodel/PrintURLs.java.html *///from ww w. ja v a2 s .com private Map<String, PDAction> extractLinks(PDPage page) throws Exception { Map<String, PDAction> links = new HashMap<String, PDAction>(); PDFTextStripperByArea stripper = new PDFTextStripperByArea(); List<PDAnnotation> annotations = page.getAnnotations(); // First setup the text extraction regions. for (int j = 0; j < annotations.size(); j++) { PDAnnotation annotation = annotations.get(j); if (annotation instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annotation; PDRectangle rect = link.getRectangle(); // Need to reposition link rectangle to match text space. float x = rect.getLowerLeftX(); float y = rect.getUpperRightY(); float width = rect.getWidth(); float height = rect.getHeight(); int rotation = page.getRotation(); if (rotation == 0) { PDRectangle pageSize = page.getMediaBox(); y = pageSize.getHeight() - y; } else if (rotation == 90) { // Do nothing. } Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height); stripper.addRegion(String.valueOf(j), awtRect); } } stripper.extractRegions(page); for (int j = 0; j < annotations.size(); j++) { PDAnnotation annotation = annotations.get(j); if (annotation instanceof PDAnnotationLink) { PDAnnotationLink link = (PDAnnotationLink) annotation; String label = stripper.getTextForRegion(String.valueOf(j)).trim(); links.put(label, link.getAction()); } } return links; }
From source file:org.xwiki.test.misc.PDFTest.java
License:Open Source License
private Rectangle2D getRectangleBelowDestination(PDPageXYZDestination destination) { PDPage page = destination.getPage(); PDRectangle pageSize = page.getMediaBox(); float x = destination.getLeft(); float y = pageSize.getHeight() - destination.getTop(); float width = pageSize.getWidth(); float height = destination.getTop(); return new Rectangle2D.Float(x, y, width, height); }