Example usage for org.apache.pdfbox.pdmodel.common PDRectangle getWidth

List of usage examples for org.apache.pdfbox.pdmodel.common PDRectangle getWidth

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.common PDRectangle getWidth.

Prototype

public float getWidth() 

Source Link

Document

This will get the width of this rectangle as calculated by upperRightX - lowerLeftX.

Usage

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;/*from   www .  j  a v  a2 s.  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)) {
                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.olat.core.util.pdf.PdfDocument.java

License:Apache License

public PDPage addPage() throws IOException {
    if (currentContentStream != null) {
        currentContentStream.close();/*  w ww  .j a va 2s.  c o  m*/
    }

    PDPage page = new PDPage(PDPage.PAGE_SIZE_A4);
    document.addPage(page);
    currentPage = page;
    currentContentStream = new PDPageContentStream(document, currentPage);

    PDRectangle mediabox = currentPage.findMediaBox();
    width = mediabox.getWidth() - 2 * marginLeftRight;
    currentY = mediabox.getUpperRightY() - marginTopBottom;
    return page;
}

From source file:org.olat.core.util.pdf.PdfDocument.java

License:Apache License

public void addPageNumbers() throws IOException {
    float footerFontSize = 10.0f;

    @SuppressWarnings("unchecked")
    List<PDPage> allPages = document.getDocumentCatalog().getAllPages();
    int numOfPages = allPages.size();
    for (int i = 0; i < allPages.size(); i++) {
        PDPage page = allPages.get(i);//from w  w  w.j  a  va  2s  .  c  o m
        PDRectangle pageSize = page.findMediaBox();

        String text = (i + 1) + " / " + numOfPages;
        float stringWidth = getStringWidth(text, footerFontSize);
        // calculate to center of the page
        float pageWidth = pageSize.getWidth();
        double x = (pageWidth - stringWidth) / 2.0f;
        double y = (marginTopBottom / 2.0f);

        // append the content to the existing stream
        PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true, true);
        contentStream.beginText();
        // set font and font size
        contentStream.setFont(font, footerFontSize);
        contentStream.setTextTranslation(x, y);
        contentStream.drawString(text);
        contentStream.endText();

        //set current date
        contentStream.beginText();
        contentStream.setFont(font, footerFontSize);
        contentStream.setTextTranslation(marginLeftRight, y);
        contentStream.drawString(printDate);
        contentStream.endText();

        contentStream.close();
    }
}

From source file:org.opencps.util.ExtractTextLocations.java

License:Open Source License

public ExtractTextLocations(String fullPath) throws IOException {

    PDDocument document = null;//from   w w w  .j ava 2s  . 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.  jav  a2s .  com*/
 */
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.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 ww.j  ava  2s  . c o m
    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  a2  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);
}

From source file:org.sejda.impl.pdfbox.component.PdfTextExtractorByArea.java

License:Apache License

private Rectangle getHeaderAreaRectangle(PDPage page) {
    PDRectangle pageSize = page.findCropBox();
    int pageWidth = (int) pageSize.getWidth();
    return new Rectangle(0, 0, pageWidth, STANDARD_FOOTER_HEIGHT);
}

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. j a v a2 s.  c  om
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;
}