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:de.uni_siegen.wineme.come_in.thumbnailer.thumbnailers.PDFBoxThumbnailer.java

License:Open Source License

private BufferedImage convertToImage(final PDPage page, final int imageType, final int thumbWidth,
        final int thumbHeight)/*     */ throws IOException
/*     */ {/*w  ww .  jav a  2  s  .  co  m*/
    /* 707 */ final PDRectangle mBox = page.findMediaBox();
    /* 708 */ final float widthPt = mBox.getWidth();
    /* 709 */ final float heightPt = mBox.getHeight();
    /* 711 */ final int widthPx = thumbWidth;
    // Math.round(widthPt * scaling);
    /* 712 */ final int heightPx = thumbHeight;
    // Math.round(heightPt * scaling);
    /* 710 */ final double scaling = Math.min((double) thumbWidth / widthPt, (double) thumbHeight / heightPt);
    // resolution / 72.0F;
    /*     */
    /* 714 */ final Dimension pageDimension = new Dimension((int) widthPt, (int) heightPt);
    /*     */
    /* 716 */ final BufferedImage retval = new BufferedImage(widthPx, heightPx, imageType);
    /* 717 */ final Graphics2D graphics = (Graphics2D) retval.getGraphics();
    /* 718 */ graphics.setBackground(PDFBoxThumbnailer.TRANSPARENT_WHITE);
    /* 719 */ graphics.clearRect(0, 0, retval.getWidth(), retval.getHeight());
    /* 720 */ graphics.scale(scaling, scaling);
    /* 721 */ final PageDrawer drawer = new PageDrawer();
    /* 722 */ drawer.drawPage(graphics, page, pageDimension);
    /*     */ try
    /*     */ {
        /* 728 */ final int rotation = page.findRotation();
        /* 729 */ if (rotation == 90 || rotation == 270)
        /*     */ {
            /* 731 */ final int w = retval.getWidth();
            /* 732 */ final int h = retval.getHeight();
            /* 733 */ final BufferedImage rotatedImg = new BufferedImage(w, h, retval.getType());
            /* 734 */ final Graphics2D g = rotatedImg.createGraphics();
            /* 735 */ g.rotate(Math.toRadians(rotation), w / 2, h / 2);
            /* 736 */ g.drawImage(retval, null, 0, 0);
            /*     */ }
        /*     */ }
    /*     */ catch (final ImagingOpException e)
    /*     */ {
        /* 741 */ //log.warn("Unable to rotate page image", e);
        /*     */ }
    /*     */
    /* 744 */ return retval;
    /*     */ }

From source file:edworld.pdfreader4humans.impl.MainPDFComponentLocator.java

License:Apache License

protected List<GridComponent> locateAllGridComponents(PDPage page) throws IOException {
    final PDPage pageToDraw = page;
    return new PageDrawer() {
        private List<GridComponent> list = new ArrayList<GridComponent>();

        public List<GridComponent> locateGridComponents() throws IOException {
            PDRectangle cropBox = pageToDraw.findCropBox();
            BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth()),
                    Math.round(cropBox.getHeight()), BufferedImage.TYPE_INT_ARGB);
            Graphics2D graphics = image.createGraphics();
            drawPage(graphics, pageToDraw, cropBox.createDimension());
            graphics.dispose();//from  ww w  . jav  a2s .  com
            dispose();
            Collections.sort(list);
            return list;
        }

        @Override
        protected void processOperator(PDFOperator operator, List<COSBase> arguments) throws IOException {
            processGridOPeration(operator, arguments);
        }

        private void processGridOPeration(PDFOperator operator, List<COSBase> arguments) throws IOException {
            if (isTextOperation(operator.getOperation()))
                return;
            if (operator.getOperation().equals("i")) {
                processSetFlatnessTolerance((COSNumber) arguments.get(0));
                return;
            }
            if (operator.getOperation().equals("l"))
                processLineTo((COSNumber) arguments.get(0), (COSNumber) arguments.get(1));
            else if (operator.getOperation().equals("re"))
                processAppendRectangleToPath((COSNumber) arguments.get(0), (COSNumber) arguments.get(1),
                        (COSNumber) arguments.get(2), (COSNumber) arguments.get(3));
            super.processOperator(operator, arguments);
        }

        private void processSetFlatnessTolerance(COSNumber flatnessTolerance) {
            getGraphicsState().setFlatness(flatnessTolerance.doubleValue());
        }

        private void processLineTo(COSNumber x, COSNumber y) {
            Point2D from = getLinePath().getCurrentPoint();
            Point2D to = transformedPoint(x.doubleValue(), y.doubleValue());
            addGridComponent("line", from, to);
        }

        private void processAppendRectangleToPath(COSNumber x, COSNumber y, COSNumber w, COSNumber h) {
            Point2D from = transformedPoint(x.doubleValue(), y.doubleValue());
            Point2D to = transformedPoint(w.doubleValue() + x.doubleValue(), h.doubleValue() + y.doubleValue());
            addGridComponent("rect", from, to);
        }

        private void addGridComponent(String type, Point2D from, Point2D to) {
            float fromX = (float) Math.min(from.getX(), to.getX());
            float fromY = (float) Math.min(from.getY(), to.getY());
            float toX = (float) Math.max(from.getX(), to.getX());
            float toY = (float) Math.max(from.getY(), to.getY());
            list.add(new GridComponent(type, fromX, fromY, toX, toY, getGraphicsState().getLineWidth()));
        }

        private boolean isTextOperation(String operation) {
            return "/BT/ET/T*/Tc/Td/TD/Tf/Tj/TJ/TL/Tm/Tr/Ts/Tw/Tz/'/\"/".contains("/" + operation + "/");
        }
    }.locateGridComponents();
}

From source file:edworld.pdfreader4humans.PDFReader.java

License:Apache License

public BufferedImage createPageImage(int pageNumber, int scaling, Color inkColor, Color backgroundColor,
        boolean showStructure) throws IOException {
    Map<String, Font> fonts = new HashMap<String, Font>();
    PDRectangle cropBox = getPageCropBox(pageNumber);
    BufferedImage image = new BufferedImage(Math.round(cropBox.getWidth() * scaling),
            Math.round(cropBox.getHeight() * scaling), BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    graphics.setBackground(backgroundColor);
    graphics.clearRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(backgroundColor);//  w  w w.  ja v a  2 s .  c o  m
    graphics.fillRect(0, 0, image.getWidth(), image.getHeight());
    graphics.setColor(inkColor);
    graphics.scale(scaling, scaling);
    for (Component component : getFirstLevelComponents(pageNumber))
        draw(component, graphics, inkColor, backgroundColor, showStructure, fonts);
    graphics.dispose();
    return image;
}

From source file:fi.nls.oskari.printout.printing.pdfbox.UsingTextMatrix.java

License:Apache License

/**
 * creates a sample document with some text using a text matrix.
 * //from  ww w  .  j  a  v  a  2  s  . co m
 * @param message
 *            The message to write in the file.
 * @param outfile
 *            The resulting PDF.
 * 
 * @throws IOException
 *             If there is an error writing the data.
 * @throws COSVisitorException
 *             If there is an error writing the PDF.
 */
public void doIt(String message, String outfile) throws IOException, COSVisitorException {
    // the document
    PDDocument doc = null;
    try {
        doc = new PDDocument();

        // Page 1
        PDFont font = PDType1Font.HELVETICA;
        PDPage page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        float fontSize = 12.0f;

        PDRectangle pageSize = page.findMediaBox();

        System.err.println("pageSize " + pageSize);
        System.err.println(
                "pageSize cm " + pageSize.getWidth() / 72 * 2.54 + "," + pageSize.getHeight() / 72 * 2.54);

        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, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();
        // counterclockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(i * Math.PI * 0.25, centeredXPosition,
                    pageSize.getHeight() - centeredYPosition);
            contentStream.drawString(message + " " + i);
        }
        // clockwise rotation
        for (int i = 0; i < 8; i++) {
            contentStream.setTextRotation(-i * Math.PI * 0.25, centeredXPosition, centeredYPosition);
            contentStream.drawString(message + " " + i);
        }

        contentStream.endText();
        contentStream.close();

        // Page 2
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        // text scaling
        for (int i = 0; i < 10; i++) {
            contentStream.setTextScaling(12 + (i * 6), 12 + (i * 6), 100, 100 + i * 50);
            contentStream.drawString(message + " " + i);
        }
        contentStream.endText();
        contentStream.close();

        // Page 3
        page = new PDPage();
        page.setMediaBox(PDPage.PAGE_SIZE_A4);
        doc.addPage(page);
        fontSize = 1.0f;

        contentStream = new PDPageContentStream(doc, page, false, false);
        contentStream.setFont(font, fontSize);
        contentStream.beginText();

        int i = 0;
        // text scaling combined with rotation
        contentStream.setTextMatrix(12, 0, 0, 12, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, 18, -18, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(-24, 0, 0, -24, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.setTextMatrix(0, -30, 30, 0, centeredXPosition, centeredYPosition * 1.5);
        contentStream.drawString(message + " " + i++);

        contentStream.endText();
        contentStream.close();

        // Page 4
        {
            page = new PDPage();
            page.setMediaBox(PDPage.PAGE_SIZE_A4);
            doc.addPage(page);
            fontSize = 1.0f;

            contentStream = new PDPageContentStream(doc, page, false, false);
            contentStream.setFont(font, fontSize);
            contentStream.beginText();

            AffineTransform root = new AffineTransform();
            root.scale(72.0 / 2.54, 72.0 / 2.54);

            for (i = 0; i < pageSize.getHeight() / 72 * 2.54; i++) {
                // text scaling combined with rotation
                {
                    AffineTransform rowMatrix = new AffineTransform(root);
                    rowMatrix.translate(1, i);
                    contentStream.setTextMatrix(rowMatrix);
                    contentStream.drawString(message + " " + i);
                }

            }

            contentStream.endText();
            contentStream.close();
        }

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

From source file:javaexample.RadialTextPdf.java

License:Open Source License

private void generatePage(PDDocument document) throws IOException {
    // Creates a new page.
    PDPage page = new PDPage(pageRect);
    document.addPage(page);//  w w  w .j a  v a2  s  . c  o  m

    // Gets boundings of the page.
    PDRectangle rect = page.getMediaBox();

    // Calculates the side of the square that fits into the page.
    float squareSide = Math.min(rect.getWidth(), rect.getHeight());

    // Calculates the center point of the page.
    float centerX = (rect.getLowerLeftX() + rect.getUpperRightX()) / 2;
    float centerY = (rect.getLowerLeftY() + rect.getUpperRightY()) / 2;

    PDPageContentStream cos = new PDPageContentStream(document, page);

    // Creates the font for the radial text.
    PDFont font = PDType1Font.HELVETICA_BOLD; // Standard font
    float fontSize = squareSide / 30;
    float fontAscent = font.getFontDescriptor().getAscent() / 1000 * fontSize;

    // Calculates key values for the drawings.
    float textX = squareSide / 3.4F; // x of the text.
    float textY = -fontAscent / 2; // y of the text (for vertical centering of text).
    float lineToX = textX * 0.97F; // x destination for the line.
    float lineWidth = squareSide / 900; // width of lines.

    // Moves the origin (0,0) of the axes to the center of the page.
    cos.concatenate2CTM(AffineTransform.getTranslateInstance(centerX, centerY));

    for (float degrees = 0; degrees < 360; degrees += 7.5) {
        double radians = degrees2Radians(degrees);

        // Creates a pure color with the hue based on the angle.
        Color textColor = Color.getHSBColor(degrees / 360.0F, 1, 1);

        // Saves the graphics state because the angle changes on each iteration.
        cos.saveGraphicsState();

        // Rotates the axes by the angle expressed in radians.
        cos.concatenate2CTM(AffineTransform.getRotateInstance(radians));

        // Draws a line from the center of the page.
        cos.setLineWidth(lineWidth);
        cos.moveTo(0, 0);
        cos.lineTo(lineToX, 0);
        cos.stroke();

        // Draws the radial text.
        cos.beginText();
        cos.setNonStrokingColor(textColor);
        cos.setFont(font, fontSize);
        cos.moveTextPositionByAmount(textX, textY);
        cos.drawString("PDF");
        cos.endText();

        // Restores the graphics state to remove rotation transformation.
        cos.restoreGraphicsState();
    }

    cos.close();
}

From source file:jlotoprint.PrintViewUIPanelController.java

public PDDocument generatePDF() throws Exception {

    PDDocument doc = null;//www.  j  a v  a 2  s  .c  o m
    PDPage page = null;
    PDPageContentStream content = null;

    try {
        doc = new PDDocument();
        List<Group> pageList = importPageList(Template.getSourceFile(), Template.getModel());
        for (Parent node : pageList) {

            page = new PDPage(PDPage.PAGE_SIZE_A4);

            doc.addPage(page);

            PDRectangle mediaBox = page.getMediaBox();
            float pageWidth = mediaBox.getWidth();
            float pageHeight = mediaBox.getHeight();

            node.setTranslateX(0);
            node.setTranslateY(0);
            node.setScaleX(1);
            node.setScaleY(1);
            node.applyCss();
            node.layout();
            HashMap<String, Double> result = resizeProportional(node.getBoundsInParent().getWidth(),
                    node.getBoundsInParent().getHeight(), pageWidth, pageHeight, true);

            //get node image
            WritableImage nodeImage = node.snapshot(null, null);
            BufferedImage bufferedImage = SwingFXUtils.fromFXImage(nodeImage, null);

            //set page content
            content = new PDPageContentStream(doc, page);

            PDJpeg image = new PDJpeg(doc, bufferedImage, 1f);
            content.drawXObject(image, 0, 0, result.get("width").intValue(), result.get("height").intValue());

            content.close();
        }
    } catch (Exception ex) {
        throw ex;
    } finally {
        try {
            if (content != null) {
                content.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    return doc;
}

From source file:jp.qpg.PDFPrinter.java

License:Apache License

/**
 * @param page page size//from  w w w  .j  av  a2  s  .co m
 * @param isLandscape true: landscape, false: portrait
 * @return this
 */
public PDFPrinter setPageSize(PDRectangle page, boolean isLandscape) {
    Objects.requireNonNull(page);
    pageSize = isLandscape ? new PDRectangle(page.getHeight(), page.getWidth()) : page;
    return this;
}

From source file:mil.tatrc.physiology.utilities.Excel2PDF.java

License:Apache License

public static void convert(String from, String to) throws IOException {
    FileInputStream xlFile = new FileInputStream(new File(from));
    // Read workbook into HSSFWorkbook
    XSSFWorkbook xlWBook = new XSSFWorkbook(xlFile);
    //We will create output PDF document objects at this point
    PDDocument pdf = new PDDocument();

    //pdf.addTitle();
    for (int s = 0; s < xlWBook.getNumberOfSheets(); s++) {
        XSSFSheet xlSheet = xlWBook.getSheetAt(s);
        Log.info("Processing Sheet : " + xlSheet.getSheetName());
        PDPage page = new PDPage(PDRectangle.A4);
        page.setRotation(90);/*w ww  .java 2 s  .c  o m*/
        pdf.addPage(page);
        PDRectangle pageSize = page.getMediaBox();
        PDPageContentStream contents = new PDPageContentStream(pdf, page);
        contents.transform(new Matrix(0, 1, -1, 0, pageSize.getWidth(), 0));// including a translation of pageWidth to use the lower left corner as 0,0 reference
        contents.setFont(PDType1Font.HELVETICA_BOLD, 16);
        contents.beginText();
        contents.newLineAtOffset(50, pageSize.getWidth() - 50);
        contents.showText(xlSheet.getSheetName());
        contents.endText();
        contents.close();

        int rows = xlSheet.getPhysicalNumberOfRows();
        for (int r = 0; r < rows; r++) {
            XSSFRow row = xlSheet.getRow(r);
            if (row == null)
                continue;
            int cells = row.getPhysicalNumberOfCells();
            if (cells == 0)
                continue;// Add an empty Roe

        }
    }

    /*    
        //We will use the object below to dynamically add new data to the table
        PdfPCell table_cell;
        //Loop through rows.
        while(rowIterator.hasNext()) 
        {
          Row row = rowIterator.next(); 
          Iterator<Cell> cellIterator = row.cellIterator();
          while(cellIterator.hasNext()) 
          {
            Cell cell = cellIterator.next(); //Fetch CELL
            switch(cell.getCellType()) 
            { //Identify CELL type
              //you need to add more code here based on
              //your requirement / transformations
              case Cell.CELL_TYPE_STRING:
    //Push the data from Excel to PDF Cell
    table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
    //feel free to move the code below to suit to your needs
    my_table.addCell(table_cell);
    break;
            }
            //next line
          }
        }
    */
    pdf.save(new File(to));
    pdf.close();
    xlWBook.close();
    xlFile.close(); //close xls
}

From source file:net.bookinaction.ExtractAnnotations.java

License:Apache License

public void doJob(String job, Float[] pA) throws IOException {

    PDDocument document = null;/* w  ww  .  jav  a2 s.  c  o  m*/

    Stamper s = new Stamper(); // utility class

    final String job_file = job + ".pdf";
    final String dic_file = job + "-dict.txt";
    final String new_job = job + "-new.pdf";

    PrintWriter writer = new PrintWriter(dic_file);

    ImageLocationListener imageLocationsListener = new ImageLocationListener();
    AnnotationMaker annotMaker = new AnnotationMaker();

    try {
        document = PDDocument.load(new File(job_file));

        int pageNum = 0;
        for (PDPage page : document.getPages()) {
            pageNum++;

            PDRectangle cropBox = page.getCropBox();

            List<PDAnnotation> annotations = page.getAnnotations();

            // extract image locations
            List<Rectangle2D> imageRects = new ArrayList<Rectangle2D>();
            imageLocationsListener.setImageRects(imageRects);
            imageLocationsListener.processPage(page);

            int im = 0;
            for (Rectangle2D pdImageRect : imageRects) {
                s.recordImage(writer, pageNum, "[im" + im + "]", (Rectangle2D.Float) pdImageRect);
                annotations.add(annotMaker.squareAnnotation(Color.YELLOW, (Rectangle2D.Float) pdImageRect,
                        "[im" + im + "]"));
                im++;
            }

            PDFTextStripperByArea stripper = new PDFTextStripperByArea();

            int j = 0;
            List<PDAnnotation> viableAnnots = new ArrayList();

            for (PDAnnotation annot : annotations) {
                if (annot instanceof PDAnnotationTextMarkup || annot instanceof PDAnnotationLink) {

                    stripper.addRegion(Integer.toString(j++), s.getAwtRect(
                            s.adjustedRect(annot.getRectangle(), pA[0], pA[1], pA[2], pA[3]), cropBox));
                    viableAnnots.add(annot);

                } else if (annot instanceof PDAnnotationPopup || annot instanceof PDAnnotationText) {
                    viableAnnots.add(annot);

                }
            }

            stripper.extractRegions(page);

            List<PDRectangle> rects = new ArrayList<PDRectangle>();

            List<String> comments = new ArrayList<String>();
            List<String> highlightTexts = new ArrayList<String>();

            j = 0;
            for (PDAnnotation viableAnnot : viableAnnots) {

                if (viableAnnot instanceof PDAnnotationTextMarkup) {
                    String highlightText = stripper.getTextForRegion(Integer.toString(j++));
                    String withoutCR = highlightText.replace((char) 0x0A, '^');

                    String comment = viableAnnot.getContents();

                    String colorString = String.format("%06x", viableAnnot.getColor().toRGB());

                    PDRectangle aRect = s.adjustedRect(viableAnnot.getRectangle(), pA[4], pA[5], pA[6], pA[7]);
                    rects.add(aRect);
                    comments.add(comment);
                    highlightTexts.add(highlightText);

                    s.recordTextMarkup(writer, pageNum, comment, withoutCR, aRect, colorString);

                } else if (viableAnnot instanceof PDAnnotationText) {
                    String comment = viableAnnot.getContents();
                    String colorString = String.format("%06x", viableAnnot.getColor().toRGB());

                    for (Rectangle2D pdImageRect : imageRects) {
                        if (pdImageRect.contains(viableAnnot.getRectangle().getLowerLeftX(),
                                viableAnnot.getRectangle().getLowerLeftY())) {
                            s.recordTextMarkup(writer, pageNum, comment, "", (Rectangle2D.Float) pdImageRect,
                                    colorString);
                            annotations.add(annotMaker.squareAnnotation(Color.GREEN,
                                    (Rectangle2D.Float) pdImageRect, comment));
                        }
                        ;
                    }
                }
            }
            PDPageContentStream canvas = new PDPageContentStream(document, page, true, true, true);

            int i = 0;
            for (PDRectangle pdRect : rects) {
                String comment = comments.get(i);
                String highlightText = highlightTexts.get(i);
                //annotations.add(linkAnnotation(pdRect, comment, highlightText));
                //annotations.add(annotationSquareCircle(pdRect, BLUE));
                s.showBox(canvas, new Rectangle2D.Float(pdRect.getLowerLeftX(), pdRect.getUpperRightY(),
                        pdRect.getWidth(), pdRect.getHeight()), cropBox, Color.BLUE);

                i++;
            }
            canvas.close();
        }
        writer.close();
        document.save(new_job);

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

    }

}

From source file:no.digipost.print.validate.PdfValidator.java

License:Apache License

private boolean harUgyldigeDimensjoner(final PDPage page) {
    PDRectangle pageMediaBox = page.findMediaBox();
    long pageHeightInMillimeters = pointsTomm(pageMediaBox.getHeight());
    long pageWidthInMillimeters = pointsTomm(pageMediaBox.getWidth());
    if ((pageHeightInMillimeters != A4_HEIGHT_MM) || (pageWidthInMillimeters != A4_WIDTH_MM)) {
        LOG.info(//from w  w  w  . ja  va 2  s . c o  m
                "En eller flere sider i PDF-en har ikke godkjente dimensjoner.  Godkjente dimensjoner er bredde {} mm og hyde {} mm. "
                        + "Faktiske dimensjoner er bredde {} mm og hyde: {} mm.",
                new Object[] { A4_WIDTH_MM, A4_HEIGHT_MM, pageWidthInMillimeters, pageHeightInMillimeters });
        return true;
    } else {
        return false;
    }
}