List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getHeight
public float getHeight()
From source file:org.nuxeo.pdf.PDFPageNumbering.java
License:Open Source License
/** * Add page numbers and returns a <i>new</i> Blob. Original blob is not * modified. This code assumes:/* w w w. ja v a2s . c o m*/ * <ul> * <li>There is no page numbers already (it always draw the numbers)</li> * <li>The pdf is not rotated</li> * <li>Default values apply: * <ul> * <li><code>inStartAtPage</code> and <code>inStartAtNumber</code> are set * to 1 if they are passed < 1.</li> * <li>If <code>inStartAtPage</code> is > number of pages it also is reset * to 1</li> * <li><code>inFontName</code> is set to "Helvetica" if "" or null</li> * <li><code>inFontSize</code> is <= 0, it is set to 16</li> * <li><code>inHex255Color</code> is set to black if "", null or if its * length < 6. Expected format is 0xrrggbb, #rrggbb or just rrggbb</li> * <li><code>inPosition</code> is set to <code>BOTTOM_RIGHT</code> if null</li> * </ul> * </li> * <li></li> * </ul> * * @param inBlob * @param inStartAtPage * @param inStartAtNumber * @param inFontName * @param inFontSize * @param inHex255Color * @param inPosition * @return Blob * @throws IOException * @throws COSVisitorException * * @since 5.9.5 */ public Blob addPageNumbers(int inStartAtPage, int inStartAtNumber, String inFontName, float inFontSize, String inHex255Color, PAGE_NUMBER_POSITION inPosition) throws IOException, COSVisitorException { Blob result = null; PDDocument doc = null; inStartAtPage = inStartAtPage < 1 ? 1 : inStartAtPage; int pageNumber = inStartAtNumber < 1 ? 1 : inStartAtNumber; inFontSize = inFontSize <= 0 ? DEFAULT_FONT_SIZE : inFontSize; int[] rgb = PDFUtils.hex255ToRGB(inHex255Color); try { doc = PDDocument.load(blob.getStream()); List<?> allPages; PDFont font; int max; if (inFontName == null || inFontName.isEmpty()) { font = PDType1Font.HELVETICA; } else { font = PDType1Font.getStandardFont(inFontName); if (font == null) { font = new PDType1Font(inFontName); } } allPages = doc.getDocumentCatalog().getAllPages(); max = allPages.size(); inStartAtPage = inStartAtPage > max ? 1 : inStartAtPage; for (int i = inStartAtPage; i <= max; i++) { String pageNumAsStr = "" + pageNumber; pageNumber += 1; PDPage page = (PDPage) allPages.get(i - 1); PDPageContentStream footercontentStream = new PDPageContentStream(doc, page, true, true); float stringWidth = font.getStringWidth(pageNumAsStr) * inFontSize / 1000f; float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * inFontSize / 1000; PDRectangle pageRect = page.findMediaBox(); float xMoveAmount, yMoveAmount; if (inPosition == null) { inPosition = PAGE_NUMBER_POSITION.BOTTOM_RIGHT; } switch (inPosition) { case BOTTOM_LEFT: xMoveAmount = 10; yMoveAmount = pageRect.getLowerLeftY() + 10; break; case BOTTOM_CENTER: xMoveAmount = (pageRect.getUpperRightX() / 2) - (stringWidth / 2); yMoveAmount = pageRect.getLowerLeftY() + 10; break; case TOP_LEFT: xMoveAmount = 10; yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; case TOP_CENTER: xMoveAmount = (pageRect.getUpperRightX() / 2) - (stringWidth / 2); yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; case TOP_RIGHT: xMoveAmount = pageRect.getUpperRightX() - 10 - stringWidth; yMoveAmount = pageRect.getHeight() - stringHeight - 10; break; // Bottom-right is the default default: xMoveAmount = pageRect.getUpperRightX() - 10 - stringWidth; yMoveAmount = pageRect.getLowerLeftY() + 10; break; } footercontentStream.beginText(); footercontentStream.setFont(font, inFontSize); footercontentStream.moveTextPositionByAmount(xMoveAmount, yMoveAmount); footercontentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); footercontentStream.drawString(pageNumAsStr); footercontentStream.endText(); footercontentStream.close(); } File tempFile = File.createTempFile("pdfutils-", ".pdf"); doc.save(tempFile); result = new FileBlob(tempFile); Framework.trackFile(tempFile, result); } finally { if (doc != null) { doc.close(); } } return result; }
From source file:org.nuxeo.pdf.PDFWatermarking.java
License:Open Source License
/** * Adds the watermark to the Blob passed to the constructor. * <p>//from w w w . ja v a 2 s . c om * If no setter has been used, the DEFAULT_nnn values apply * <p> * If * <code>text</text> is empty or null, a simple copy of the original Blob is returned * <p> * With thanks to the sample code found at https://issues.apache.org/jira/browse/PDFBOX-1176 * and to Jack (https://jackson-brain.com/a-better-simple-pdf-stamper-in-java/) * * @return a new Blob with the watermark on each page * * @throws ClientException * * @since 6.0 */ public Blob watermark() throws ClientException { Blob result = null; PDDocument pdfDoc = null; PDPageContentStream contentStream = null; if (text == null || text.isEmpty()) { try { File tempFile = File.createTempFile("nuxeo-pdfwatermarking-", ".pdf"); blob.transferTo(tempFile); result = new FileBlob(tempFile); // Just duplicate the info result.setFilename(blob.getFilename()); result.setMimeType(blob.getMimeType()); result.setEncoding(blob.getEncoding()); Framework.trackFile(tempFile, result); return result; } catch (IOException e) { throw new ClientException(e); } } // Set up the graphic state to handle transparency // Define a new extended graphic state PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState(); // Set the transparency/opacity extendedGraphicsState.setNonStrokingAlphaConstant(alphaColor); try { pdfDoc = PDDocument.load(blob.getStream()); PDFont font = PDType1Font.getStandardFont(fontFamily); int[] rgb = PDFUtils.hex255ToRGB(hex255Color); List<?> allPages = pdfDoc.getDocumentCatalog().getAllPages(); int max = allPages.size(); for (int i = 0; i < max; i++) { contentStream = null; PDPage page = (PDPage) allPages.get(i); PDRectangle pageSize = page.findMediaBox(); PDResources resources = page.findResources(); // Get the defined graphic states. HashMap<String, PDExtendedGraphicsState> graphicsStateDictionary = (HashMap<String, PDExtendedGraphicsState>) resources .getGraphicsStates(); if (graphicsStateDictionary != null) { graphicsStateDictionary.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(graphicsStateDictionary); } else { Map<String, PDExtendedGraphicsState> m = new HashMap<>(); m.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(m); } if (invertY) { yPosition = pageSize.getHeight() - yPosition; } float stringWidth = font.getStringWidth(text) * fontSize / 1000f; int pageRot = page.findRotation(); boolean pageRotated = pageRot == 90 || pageRot == 270; boolean textRotated = textRotation != 0 && textRotation != 360; int totalRot = pageRot - textRotation; float pageWidth = pageRotated ? pageSize.getHeight() : pageSize.getWidth(); float pageHeight = pageRotated ? pageSize.getWidth() : pageSize.getHeight(); double centeredXPosition = pageRotated ? pageHeight / 2f : (pageWidth - stringWidth) / 2f; double centeredYPosition = pageRotated ? (pageWidth - stringWidth) / 2f : pageHeight / 2f; contentStream = new PDPageContentStream(pdfDoc, page, true, true, true); contentStream.beginText(); contentStream.setFont(font, fontSize); contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); if (pageRotated) { contentStream.setTextRotation(Math.toRadians(totalRot), centeredXPosition, centeredYPosition); } else if (textRotated) { contentStream.setTextRotation(Math.toRadians(textRotation), xPosition, yPosition); } else { contentStream.setTextTranslation(xPosition, yPosition); } contentStream.drawString(text); contentStream.endText(); contentStream.close(); contentStream = null; } result = PDFUtils.saveInTempFile(pdfDoc); } catch (IOException | COSVisitorException e) { throw new ClientException(e); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { // Ignore } } PDFUtils.closeSilently(pdfDoc); } return result; }
From source file:org.nuxeo.pdf.service.PDFTransformationServiceImpl.java
License:Apache License
@Override public Blob applyTextWatermark(Blob input, String text, WatermarkProperties properties) { // Set up the graphic state to handle transparency // Define a new extended graphic state PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState(); // Set the transparency/opacity extendedGraphicsState.setNonStrokingAlphaConstant((float) properties.getAlphaColor()); try (PDDocument pdfDoc = PDDocument.load(input.getStream())) { PDFont font = PDType1Font.getStandardFont(properties.getFontFamily()); float watermarkWidth = (float) (font.getStringWidth(text) * properties.getFontSize() / 1000f); int[] rgb = PDFUtils.hex255ToRGB(properties.getHex255Color()); for (Object o : pdfDoc.getDocumentCatalog().getAllPages()) { PDPage page = (PDPage) o;/*from w ww . j av a2s. c o m*/ PDRectangle pageSize = page.findMediaBox(); PDResources resources = page.findResources(); // Get the defined graphic states. HashMap<String, PDExtendedGraphicsState> graphicsStateDictionary = (HashMap<String, PDExtendedGraphicsState>) resources .getGraphicsStates(); if (graphicsStateDictionary != null) { graphicsStateDictionary.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(graphicsStateDictionary); } else { Map<String, PDExtendedGraphicsState> m = new HashMap<>(); m.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(m); } try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page, true, true, true)) { contentStream.beginText(); contentStream.setFont(font, (float) properties.getFontSize()); contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.setNonStrokingColor(rgb[0], rgb[1], rgb[2]); Point2D position = computeTranslationVector(pageSize.getWidth(), watermarkWidth, pageSize.getHeight(), properties.getFontSize(), properties); contentStream.setTextRotation(Math.toRadians(properties.getTextRotation()), position.getX(), position.getY()); contentStream.drawString(text); contentStream.endText(); } } return saveInTempFile(pdfDoc); } catch (Exception e) { throw new NuxeoException(e); } }
From source file:org.nuxeo.pdf.service.PDFTransformationServiceImpl.java
License:Apache License
@Override public Blob applyImageWatermark(Blob input, Blob watermark, WatermarkProperties properties) { // Set up the graphic state to handle transparency // Define a new extended graphic state PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState(); // Set the transparency/opacity extendedGraphicsState.setNonStrokingAlphaConstant((float) properties.getAlphaColor()); try (PDDocument pdfDoc = PDDocument.load(input.getStream())) { BufferedImage image = ImageIO.read(watermark.getStream()); PDXObjectImage ximage = new PDPixelMap(pdfDoc, image); for (Object o : pdfDoc.getDocumentCatalog().getAllPages()) { PDPage page = (PDPage) o;// w w w. ja va 2 s .c om PDRectangle pageSize = page.findMediaBox(); PDResources resources = page.findResources(); // Get the defined graphic states. HashMap<String, PDExtendedGraphicsState> graphicsStateDictionary = (HashMap<String, PDExtendedGraphicsState>) resources .getGraphicsStates(); if (graphicsStateDictionary != null) { graphicsStateDictionary.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(graphicsStateDictionary); } else { Map<String, PDExtendedGraphicsState> m = new HashMap<>(); m.put("TransparentState", extendedGraphicsState); resources.setGraphicsStates(m); } try (PDPageContentStream contentStream = new PDPageContentStream(pdfDoc, page, true, true)) { contentStream.appendRawCommands("/TransparentState gs\n"); contentStream.endMarkedContentSequence(); double watermarkWidth = ximage.getWidth() * properties.getScale(); double watermarkHeight = ximage.getHeight() * properties.getScale(); Point2D position = computeTranslationVector(pageSize.getWidth(), watermarkWidth, pageSize.getHeight(), watermarkHeight, properties); contentStream.drawXObject(ximage, (float) position.getX(), (float) position.getY(), (float) watermarkWidth, (float) watermarkHeight); } } return saveInTempFile(pdfDoc); } catch (COSVisitorException | IOException e) { throw new NuxeoException(e); } }
From source file:org.opencps.util.ExtractTextLocations.java
License:Open Source License
public ExtractTextLocations(String fullPath) throws IOException { PDDocument document = null;//from www. j ava 2 s . c o m try { File input = new File(fullPath); document = PDDocument.load(input); if (document.isEncrypted()) { try { document.decrypt(StringPool.BLANK); } catch (Exception e) { _log.error(e); } } // ExtractTextLocations printer = new ExtractTextLocations(); List allPages = document.getDocumentCatalog().getAllPages(); if (allPages != null && allPages.size() > 0) { PDPage page = (PDPage) allPages.get(0); PDStream contents = page.getContents(); if (contents != null) { this.processStream(page, page.findResources(), page.getContents().getStream()); } PDRectangle pageSize = page.findMediaBox(); if (pageSize != null) { setPageWidth(pageSize.getWidth()); setPageHeight(pageSize.getHeight()); setPageLLX(pageSize.getLowerLeftX()); setPageURX(pageSize.getUpperRightX()); setPageLLY(pageSize.getLowerLeftY()); setPageURY(pageSize.getUpperRightY()); } } } catch (Exception e) { _log.error(e); } finally { if (document != null) { document.close(); } } }
From source file:org.paxle.parser.pdf.impl.PdfParser.java
License:Open Source License
/** * A function to extract embedded URIs from the PDF-document. * /* w w w . j a v a 2 s . c o m*/ */ protected void extractURLs(IParserDocument parserDoc, PDDocument pddDoc) throws IOException { final PDDocumentCatalog pddDocCatalog = pddDoc.getDocumentCatalog(); if (pddDocCatalog == null) return; @SuppressWarnings("unchecked") final List<PDPage> allPages = pddDocCatalog.getAllPages(); if (allPages == null || allPages.isEmpty()) return; for (int i = 0; i < allPages.size(); i++) { final PDFTextStripperByArea stripper = new PDFTextStripperByArea(); final PDPage page = (PDPage) allPages.get(i); @SuppressWarnings("unchecked") final List<PDAnnotation> annotations = page.getAnnotations(); if (annotations == null || annotations.isEmpty()) return; //first setup text extraction regions for (int j = 0; j < annotations.size(); j++) { final PDAnnotation annot = (PDAnnotation) annotations.get(j); if (annot instanceof PDAnnotationLink) { final PDAnnotationLink link = (PDAnnotationLink) annot; final 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.findRotation(); if (rotation == 0) { PDRectangle pageSize = page.findMediaBox(); y = pageSize.getHeight() - y; } else if (rotation == 90) { //do nothing } Rectangle2D.Float awtRect = new Rectangle2D.Float(x, y, width, height); stripper.addRegion("" + j, awtRect); } } stripper.extractRegions(page); for (int j = 0; j < annotations.size(); j++) { final PDAnnotation annot = (PDAnnotation) annotations.get(j); if (annot instanceof PDAnnotationLink) { final PDAnnotationLink link = (PDAnnotationLink) annot; final PDAction action = link.getAction(); final String urlText = stripper.getTextForRegion("" + j); if (action instanceof PDActionURI) { final PDActionURI embeddedUri = (PDActionURI) action; final URI temp = URI.create(embeddedUri.getURI()); parserDoc.addReference(temp, urlText, Constants.SERVICE_PID + ":" + PID); } } } } }
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;//from w w w. j a v a 2s . co 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.qi4j.envisage.print.PDFWriter.java
License:Apache License
private void writeGraphPage(GraphDisplay graphDisplay) throws IOException { File tFile = File.createTempFile("envisage", "png"); graphDisplay.saveImage(new FileOutputStream(tFile), "png", 1d); BufferedImage img = ImageIO.read(tFile); int w = img.getWidth(); int h = img.getHeight(); int inset = 40; PDRectangle pdRect = new PDRectangle(w + inset, h + inset); PDPage page = new PDPage(); page.setMediaBox(pdRect);//from w w w .java2 s . c om doc.addPage(page); PDJpeg xImage = new PDJpeg(doc, img); PDPageContentStream contentStream = new PDPageContentStream(doc, page); contentStream.drawImage(xImage, (pdRect.getWidth() - w) / 2, (pdRect.getHeight() - h) / 2); contentStream.close(); }
From source file:org.sejda.impl.pdfbox.component.PdfHeaderFooterWriter.java
License:Apache License
public void writeFooter(SetHeaderFooterParameters parameters) throws TaskIOException { PDFont font = defaultIfNull(getStandardType1Font(parameters.getFont()), PDType1Font.HELVETICA); BigDecimal fontSize = defaultIfNull(parameters.getFontSize(), BigDecimal.TEN); HorizontalAlign horAlignment = defaultIfNull(parameters.getHorizontalAlign(), HorizontalAlign.CENTER); VerticalAlign verAlignment = defaultIfNull(parameters.getVerticalAlign(), VerticalAlign.BOTTOM); SortedSet<Integer> pages = parameters.getPageRange().getPages(documentHandler.getNumberOfPages()); LOG.debug("Found {} pages to apply header or footer", pages.size()); Integer labelPageNumber = parameters.getNumbering().getLogicalPageNumber(); for (Integer pageNumber : pages) { String label = parameters.styledLabelFor(labelPageNumber); PDPage page = documentHandler.getPage(pageNumber); PDRectangle pageSize = page.findCropBox(); try {//from w w w . j a v a 2 s . co m float stringWidth = font.getStringWidth(label) * fontSize.floatValue() / 1000f; float xPosition = horAlignment.position(pageSize.getWidth(), stringWidth, DEFAULT_MARGIN); float yPosition = verAlignment.position(pageSize.getHeight(), DEFAULT_MARGIN); PDPageContentStream contentStream = new PDPageContentStream( documentHandler.getUnderlyingPDDocument(), page, true, true); contentStream.beginText(); contentStream.setFont(font, fontSize.floatValue()); contentStream.moveTextPositionByAmount(xPosition, yPosition); contentStream.drawString(label); contentStream.endText(); contentStream.close(); } catch (IOException e) { throw new TaskIOException("An error occurred writing the header or footer of the page.", e); } labelPageNumber++; } }
From source file:org.sejda.impl.pdfbox.component.PdfTextExtractorByArea.java
License:Apache License
private Rectangle getFooterAreaRectangle(PDPage page) { PDRectangle pageSize = page.findCropBox(); int pageHeight = (int) pageSize.getHeight(); int pageWidth = (int) pageSize.getWidth(); return new Rectangle(0, pageHeight - STANDARD_FOOTER_HEIGHT, pageWidth, STANDARD_FOOTER_HEIGHT); }