Java Code Examples for org.apache.pdfbox.pdmodel.common.PDRectangle#getHeight()

The following examples show how to use org.apache.pdfbox.pdmodel.common.PDRectangle#getHeight() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static float processYAngle360(PDRectangle mediaBox, SignatureImageParameters signatureImageParameters, float height) {
      float y;

VisualSignatureAlignmentVertical alignmentVertical = signatureImageParameters.getVisualSignatureAlignmentVertical();

      switch (alignmentVertical) {
          case TOP:
          case NONE:
              y = signatureImageParameters.getyAxis();
              break;
          case MIDDLE:
              y = (mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom())) / 2;
              break;
          case BOTTOM:
              y = mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom()) - signatureImageParameters.getyAxis();
              break;
          default:
              throw new IllegalStateException(NOT_SUPPORTED_VERTICAL_ALIGNMENT_ERROR_MESSAGE + alignmentVertical.name());
      }

      return y;
  }
 
Example 2
Source File: PdfBoxPreviewTest.java    From java-image-processing-survival-guide with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<BufferedImage> toImages(PDDocument pdDocument, int startPage, int endPage, int resolution, int imageType) throws Exception {
    final List<BufferedImage> result = new ArrayList<BufferedImage>();
    final List<PDPage> pages = pdDocument.getDocumentCatalog().getAllPages();
    final int pagesSize = pages.size();

    for (int i = startPage - 1; i < endPage && i < pagesSize; i++) {
        PDPage page = pages.get(i);
        PDRectangle cropBox = page.findCropBox();
        float width = cropBox.getWidth();
        float height = cropBox.getHeight();
        int currResolution = calculateResolution(resolution, width, height);
        BufferedImage image = page.convertToImage(imageType, currResolution);

        if (image != null) {
            result.add(image);
        }
    }

    return result;
}
 
Example 3
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static float processYAngle180(PDRectangle mediaBox, SignatureImageParameters signatureImageParameters, float height) {
      float y;

VisualSignatureAlignmentVertical alignmentVertical = signatureImageParameters.getVisualSignatureAlignmentVertical();

      switch (alignmentVertical) {
          case TOP:
          case NONE:
              y = mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom()) - signatureImageParameters.getyAxis();
              break;
          case MIDDLE:
              y = (mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom())) / 2;
              break;
          case BOTTOM:
              y = signatureImageParameters.getyAxis();
              break;
          default:
              throw new IllegalStateException(NOT_SUPPORTED_VERTICAL_ALIGNMENT_ERROR_MESSAGE + alignmentVertical.name());
      }

      return y;
  }
 
Example 4
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static float processYAngle270(PDRectangle mediaBox, SignatureImageParameters signatureImageParameters, float height) {
      float y;

VisualSignatureAlignmentHorizontal alignmentHorizontal = signatureImageParameters.getVisualSignatureAlignmentHorizontal();

      switch (alignmentHorizontal) {
          case LEFT:
          case NONE:
              y = mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom()) - signatureImageParameters.getxAxis();
              break;
          case CENTER:
              y = (mediaBox.getHeight() - zoom(height, signatureImageParameters.getZoom())) / 2;
              break;
          case RIGHT:
              y = signatureImageParameters.getxAxis();
              break;
          default:
              throw new IllegalStateException(NOT_SUPPORTED_HORIZONTAL_ALIGNMENT_ERROR_MESSAGE + alignmentHorizontal.name());
      }

      return y;
  }
 
Example 5
Source File: PDFRenderer.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private void transform(Graphics2D graphics, PDPage page, float scaleX, float scaleY)
{
    graphics.scale(scaleX, scaleY);

    // TODO should we be passing the scale to PageDrawer rather than messing with Graphics?
    int rotationAngle = page.getRotation();
    PDRectangle cropBox = page.getCropBox();

    if (rotationAngle != 0)
    {
        float translateX = 0;
        float translateY = 0;
        switch (rotationAngle)
        {
            case 90:
                translateX = cropBox.getHeight();
                break;
            case 270:
                translateY = cropBox.getWidth();
                break;
            case 180:
                translateX = cropBox.getWidth();
                translateY = cropBox.getHeight();
                break;
            default:
                break;
        }
        graphics.translate(translateX, translateY);
        graphics.rotate(Math.toRadians(rotationAngle));
    }
}
 
Example 6
Source File: PDFPrintable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will find the CropBox with rotation applied, for this page by looking up the hierarchy
 * until it finds them.
 *
 * @return The CropBox at this level in the hierarchy.
 */
static PDRectangle getRotatedCropBox(PDPage page)
{
    PDRectangle cropBox = page.getCropBox();
    int rotationAngle = page.getRotation();
    if (rotationAngle == 90 || rotationAngle == 270)
    {
        return new PDRectangle(cropBox.getLowerLeftY(), cropBox.getLowerLeftX(),
                               cropBox.getHeight(), cropBox.getWidth());
    }
    else
    {
        return cropBox;
    }
}
 
Example 7
Source File: PDFPrintable.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * This will find the MediaBox with rotation applied, for this page by looking up the hierarchy
 * until it finds them.
 *
 * @return The MediaBox at this level in the hierarchy.
 */
static PDRectangle getRotatedMediaBox(PDPage page)
{
    PDRectangle mediaBox = page.getMediaBox();
    int rotationAngle = page.getRotation();
    if (rotationAngle == 90 || rotationAngle == 270)
    {
        return new PDRectangle(mediaBox.getLowerLeftY(), mediaBox.getLowerLeftX(),
                               mediaBox.getHeight(), mediaBox.getWidth());
    }
    else
    {
        return mediaBox;
    }
}
 
Example 8
Source File: PDType3Font.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public float getHeight(int code) throws IOException
{
    PDFontDescriptor desc = getFontDescriptor();
    if (desc != null)
    {
        // the following values are all more or less accurate at least all are average
        // values. Maybe we'll find another way to get those value for every single glyph
        // in the future if needed
        PDRectangle bbox = desc.getFontBoundingBox();
        float retval = 0;
        if (bbox != null)
        {
            retval = bbox.getHeight() / 2;
        }
        if (retval == 0)
        {
            retval = desc.getCapHeight();
        }
        if (retval == 0)
        {
            retval = desc.getAscent();
        }
        if (retval == 0)
        {
            retval = desc.getXHeight();
            if (retval > 0)
            {
                retval -= desc.getDescent();
            }
        }
        return retval;
    }
    return 0;
}
 
Example 9
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * My "not so great" method for calculating the fontsize. It does not work superb, but it
 * handles ok.
 * 
 * @return the calculated font-size
 * @throws IOException If there is an error getting the font information.
 */
private float calculateFontSize(PDFont font, PDRectangle contentRect) throws IOException
{
    float fontSize = defaultAppearance.getFontSize();
    
    // zero is special, it means the text is auto-sized
    if (fontSize == 0)
    {
        if (isMultiLine())
        {
            // Acrobat defaults to 12 for multiline text with size 0
            return DEFAULT_FONT_SIZE;
        }
        else
        {
            float yScalingFactor = FONTSCALE * font.getFontMatrix().getScaleY();
            float xScalingFactor = FONTSCALE * font.getFontMatrix().getScaleX();
            
            // fit width
            float width = font.getStringWidth(value) * font.getFontMatrix().getScaleX();
            float widthBasedFontSize = contentRect.getWidth() / width * xScalingFactor;

            // fit height
            float height = (font.getFontDescriptor().getCapHeight() +
                           -font.getFontDescriptor().getDescent()) * font.getFontMatrix().getScaleY();
            if (height <= 0)
            {
                height = font.getBoundingBox().getHeight() * font.getFontMatrix().getScaleY();
            }

            float heightBasedFontSize = contentRect.getHeight() / height * yScalingFactor;
            
            return Math.min(heightBasedFontSize, widthBasedFontSize);
        }
    }
    return fontSize;
}
 
Example 10
Source File: PageRenderer.java    From PDF4Teachers with Apache License 2.0 5 votes vote down vote up
public void updatePosition(int totalHeight){
    if(totalHeight == -1) totalHeight = (int) getTranslateY();

    PDRectangle pageSize = MainWindow.mainScreen.document.pdfPagesRender.getPageSize(page);
    final double ratio = pageSize.getHeight() / pageSize.getWidth();

    setWidth(MainWindow.mainScreen.getPageWidth());
    setHeight(MainWindow.mainScreen.getPageWidth() * ratio);

    setMaxWidth(MainWindow.mainScreen.getPageWidth());
    setMinWidth(MainWindow.mainScreen.getPageWidth());

    setMaxHeight(MainWindow.mainScreen.getPageWidth() * ratio);
    setMinHeight(MainWindow.mainScreen.getPageWidth() * ratio);

    setTranslateX(30);
    setTranslateY(totalHeight);

    totalHeight = (int) (totalHeight + getHeight() + 30);

    if(MainWindow.mainScreen.document.totalPages > page+1){
        MainWindow.mainScreen.document.pages.get(page + 1).updatePosition(totalHeight);
    }else{
        MainWindow.mainScreen.updateSize(totalHeight);
    }

    if(pageEditPane != null) pageEditPane.updatePosition();

}
 
Example 11
Source File: PDAbstractAppearanceHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get a rectangle enlarged by the differences.
 *
 * <p>
 * Creates a new rectangle with differences added to each side. If there are no valid
 * differences, then the original rectangle is returned.
 *
 * @param rectangle the rectangle.
 * @param differences the differences to apply.
 * @return the padded rectangle.
 */
PDRectangle addRectDifferences(PDRectangle rectangle, float[] differences)
{
    if (differences == null || differences.length != 4)
    {
        return rectangle;
    }
    
    return new PDRectangle(rectangle.getLowerLeftX() - differences[0],
            rectangle.getLowerLeftY() - differences[1],
            rectangle.getWidth() + differences[0] + differences[2],
            rectangle.getHeight() + differences[1] + differences[3]);
}
 
Example 12
Source File: PDAbstractAppearanceHandler.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Get a rectangle with the differences applied to each side.
 *
 * <p>
 * Creates a new rectangle with differences added to each side. If there are no valid
 * differences, then the original rectangle is returned.
 *
 * @param rectangle the rectangle.
 * @param differences the differences to apply.
 * @return the padded rectangle.
 */
PDRectangle applyRectDifferences(PDRectangle rectangle, float[] differences)
{
    if (differences == null || differences.length != 4)
    {
        return rectangle;
    }
    return new PDRectangle(rectangle.getLowerLeftX() + differences[0],
            rectangle.getLowerLeftY() + differences[1],
            rectangle.getWidth() - differences[0] - differences[2],
            rectangle.getHeight() - differences[1] - differences[3]);
}
 
Example 13
Source File: PdfBoxPDFWatermarkWriter.java    From website with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getOrientation(PDPage page) {
	PDRectangle pageSize = page.findMediaBox();
	if (pageSize.getHeight() > pageSize.getWidth()) {
		return PAGE_ORIENTATION_PORTRAIT;
	} else {
		return PAGE_ORIENTATION_LANDSCAPE;
	}
}
 
Example 14
Source File: PdfComparator.java    From pdfcompare with Apache License 2.0 5 votes vote down vote up
public static ImageWithDimension renderPageAsImage(final PDDocument document, final PDFRenderer expectedPdfRenderer, final int pageIndex, Environment environment)
        throws IOException {
    final BufferedImage bufferedImage = expectedPdfRenderer.renderImageWithDPI(pageIndex, environment.getDPI());
    final PDPage page = document.getPage(pageIndex);
    final PDRectangle mediaBox = page.getMediaBox();
    if (page.getRotation() == 90 || page.getRotation() == 270)
        return new ImageWithDimension(bufferedImage, mediaBox.getHeight(), mediaBox.getWidth());
    else
        return new ImageWithDimension(bufferedImage, mediaBox.getWidth(), mediaBox.getHeight());
}
 
Example 15
Source File: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private static void writePageNumbering(PDDocument doc, PDFont font, float fontSize, PageNumbering pageNumbering) throws IOException {
	int totalPages = doc.getNumberOfPages();
	int numberOfPages = pageNumbering.isLastIncluded() ? doc.getNumberOfPages() : doc.getNumberOfPages() - 1;
	for (int pageIndex = pageNumbering.isFirstIncluded() ? 0 : 1; pageIndex < numberOfPages; pageIndex++) {
		String footer = "Page " + (pageIndex + 1) + " of " + totalPages;
		PDPage page = doc.getPage(pageIndex);
		PDRectangle pageSize = page.getMediaBox();
		float stringWidth = font.getStringWidth(footer) * fontSize / 1000f;
		float stringHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() * fontSize / 1000f;

		int rotation = page.getRotation();
		boolean rotate = rotation == 90 || rotation == 270;
		float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
		float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
		float startX = rotate ? pageHeight / 2f : (pageWidth - stringWidth - stringHeight) / 2f;
		float startY = rotate ? (pageWidth - stringWidth) : stringHeight;

		// append the content to the existing stream
		try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {

			// draw rectangle
			contentStream.setNonStrokingColor(255, 255, 255); // gray background
			// Draw a white filled rectangle
			drawRect(contentStream, Color.WHITE, new java.awt.Rectangle((int) startX, (int) startY - 3, (int) stringWidth + 2, (int) stringHeight), true);
			writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, footer);
		}
	}
}
 
Example 16
Source File: ImageExtractor.java    From inception with Apache License 2.0 5 votes vote down vote up
@Override protected void processOperator(Operator operator, List<COSBase> operands)
    throws IOException
{
    String operation = operator.getName();
    if ("Do".equals(operation)) {
        COSName objectName = (COSName) operands.get(0);
        PDXObject xobject = getResources().getXObject(objectName);

        if (xobject instanceof PDImageXObject) {
            PDImageXObject image = (PDImageXObject) xobject;
            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
            PDRectangle pageRect = this.getCurrentPage().getCropBox();
            float w = ctmNew.getScalingFactorX();
            float h = ctmNew.getScalingFactorY();
            float x = ctmNew.getTranslateX();
            float y = pageRect.getHeight() - ctmNew.getTranslateY() - h;
            buffer.add(new ImageOperator(x, y, w, h));
        }
        else if (xobject instanceof PDFormXObject) {
            PDFormXObject form = (PDFormXObject) xobject;
            showForm(form);
        }
    }
    else {
        super.processOperator(operator, operands);
    }
}
 
Example 17
Source File: PdfRenderer.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
@Override
protected void writeString(String text, List<TextPosition> textPositions) throws IOException {
    text = text.toLowerCase();
    int index = text.indexOf(mTextToHighlight);
    if (index != -1) {
        PDPage          currentPage     = getCurrentPage();
        PDRectangle     pageBoundingBox = currentPage.getBBox();
        AffineTransform flip            = new AffineTransform();
        flip.translate(0, pageBoundingBox.getHeight());
        flip.scale(1, -1);
        PDRectangle mediaBox    = currentPage.getMediaBox();
        float       mediaHeight = mediaBox.getHeight();
        float       mediaWidth  = mediaBox.getWidth();
        int         size        = textPositions.size();
        while (index != -1) {
            int last = index + mTextToHighlight.length() - 1;
            for (int i = index; i <= last; i++) {
                TextPosition      pos  = textPositions.get(i);
                PDFont            font = pos.getFont();
                BoundingBox       bbox = font.getBoundingBox();
                Rectangle2D.Float rect = new Rectangle2D.Float(0, bbox.getLowerLeftY(), font.getWidth(pos.getCharacterCodes()[0]), bbox.getHeight());
                AffineTransform   at   = pos.getTextMatrix().createAffineTransform();
                if (font instanceof PDType3Font) {
                    at.concatenate(font.getFontMatrix().createAffineTransform());
                } else {
                    at.scale(1 / 1000.0f, 1 / 1000.0f);
                }
                Shape           shape     = flip.createTransformedShape(at.createTransformedShape(rect));
                AffineTransform transform = mGC.getTransform();
                int             rotation  = currentPage.getRotation();
                if (rotation != 0) {
                    switch (rotation) {
                    case 90:
                        mGC.translate(mediaHeight, 0);
                        break;
                    case 270:
                        mGC.translate(0, mediaWidth);
                        break;
                    case 180:
                        mGC.translate(mediaWidth, mediaHeight);
                        break;
                    default:
                        break;
                    }
                    mGC.rotate(Math.toRadians(rotation));
                }
                mGC.fill(shape);
                if (rotation != 0) {
                    mGC.setTransform(transform);
                }
            }
            index = last < size - 1 ? text.indexOf(mTextToHighlight, last + 1) : -1;
        }
    }
}
 
Example 18
Source File: PDCircleAppearanceHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public void generateNormalAppearance()
{
    float lineWidth = getLineWidth();
    PDAnnotationSquareCircle annotation = (PDAnnotationSquareCircle) getAnnotation();
    PDAppearanceContentStream contentStream  = null;

    try
    {
        contentStream = getNormalAppearanceAsContentStream();
        boolean hasStroke = contentStream.setStrokingColorOnDemand(getColor());
        boolean hasBackground = contentStream
                .setNonStrokingColorOnDemand(annotation.getInteriorColor());

        setOpacity(contentStream, annotation.getConstantOpacity());

        contentStream.setBorderLine(lineWidth, annotation.getBorderStyle(), annotation.getBorder());
        PDBorderEffectDictionary borderEffect = annotation.getBorderEffect();

        if (borderEffect != null && borderEffect.getStyle().equals(PDBorderEffectDictionary.STYLE_CLOUDY))
        {
            CloudyBorder cloudyBorder = new CloudyBorder(contentStream,
                borderEffect.getIntensity(), lineWidth, getRectangle());
            cloudyBorder.createCloudyEllipse(annotation.getRectDifference());
            annotation.setRectangle(cloudyBorder.getRectangle());
            annotation.setRectDifference(cloudyBorder.getRectDifference());
            PDAppearanceStream appearanceStream = annotation.getNormalAppearanceStream();
            appearanceStream.setBBox(cloudyBorder.getBBox());
            appearanceStream.setMatrix(cloudyBorder.getMatrix());
        }
        else
        {
            // Acrobat applies a padding to each side of the bbox so the line is completely within
            // the bbox.

            PDRectangle borderBox = handleBorderBox(annotation, lineWidth);

            // lower left corner
            float x0 = borderBox.getLowerLeftX();
            float y0 = borderBox.getLowerLeftY();
            // upper right corner
            float x1 = borderBox.getUpperRightX();
            float y1 = borderBox.getUpperRightY();
            // mid points
            float xm = x0 + borderBox.getWidth() / 2;
            float ym = y0 + borderBox.getHeight() / 2;
            // see http://spencermortensen.com/articles/bezier-circle/
            // the below number was calculated from sampling content streams
            // generated using Adobe Reader
            float magic = 0.55555417f;
            // control point offsets
            float vOffset = borderBox.getHeight() / 2 * magic;
            float hOffset = borderBox.getWidth() / 2 * magic;

            contentStream.moveTo(xm, y1);
            contentStream.curveTo((xm + hOffset), y1, x1, (ym + vOffset), x1, ym);
            contentStream.curveTo(x1, (ym - vOffset), (xm + hOffset), y0, xm, y0);
            contentStream.curveTo((xm - hOffset), y0, x0, (ym - vOffset), x0, ym);
            contentStream.curveTo(x0, (ym + vOffset), (xm - hOffset), y1, xm, y1);
            contentStream.closePath();
        }

        contentStream.drawShape(lineWidth, hasStroke, hasBackground);
    }
    catch (IOException e)
    {
        LOG.error(e);
    }
    finally{
        IOUtils.closeQuietly(contentStream);
    }
}
 
Example 19
Source File: PDFStreamEngine.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Process the given annotation with the specified appearance stream.
 *
 * @param annotation The annotation containing the appearance stream to process.
 * @param appearance The appearance stream to process.
 * @throws IOException If there is an error reading or parsing the appearance content stream.
 */
protected void processAnnotation(PDAnnotation annotation, PDAppearanceStream appearance)
        throws IOException
{
    PDResources parent = pushResources(appearance);
    Deque<PDGraphicsState> savedStack = saveGraphicsStack();

    PDRectangle bbox = appearance.getBBox();
    PDRectangle rect = annotation.getRectangle();
    Matrix matrix = appearance.getMatrix();

    // zero-sized rectangles are not valid
    if (rect != null && rect.getWidth() > 0 && rect.getHeight() > 0 && bbox != null)
    {
        // transformed appearance box  fixme: may be an arbitrary shape
        Rectangle2D transformedBox = bbox.transform(matrix).getBounds2D();

        // compute a matrix which scales and translates the transformed appearance box to align
        // with the edges of the annotation's rectangle
        Matrix a = Matrix.getTranslateInstance(rect.getLowerLeftX(), rect.getLowerLeftY());
        a.concatenate(Matrix.getScaleInstance((float)(rect.getWidth() / transformedBox.getWidth()),
                (float)(rect.getHeight() / transformedBox.getHeight())));
        a.concatenate(Matrix.getTranslateInstance((float) -transformedBox.getX(),
                (float) -transformedBox.getY()));

        // Matrix shall be concatenated with A to form a matrix AA that maps from the appearance's
        // coordinate system to the annotation's rectangle in default user space
        //
        // HOWEVER only the opposite order works for rotated pages with 
        // filled fields / annotations that have a matrix in the appearance stream, see PDFBOX-3083
        Matrix aa = Matrix.concatenate(a, matrix);

        // make matrix AA the CTM
        getGraphicsState().setCurrentTransformationMatrix(aa);

        // clip to bounding box
        clipToRect(bbox);

        // needed for patterns in appearance streams, e.g. PDFBOX-2182
        initialMatrix = aa.clone();

        processStreamOperators(appearance);
    }
    
    restoreGraphicsStack(savedStack);
    popResources(parent);
}
 
Example 20
Source File: PDAbstractAppearanceHandler.java    From gcs with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Get a padded rectangle.
 * 
 * <p>Creates a new rectangle with padding applied to each side.
 * .
 * @param rectangle the rectangle.
 * @param padding the padding to apply.
 * @return the padded rectangle.
 */
PDRectangle getPaddedRectangle(PDRectangle rectangle, float padding)
{
    return new PDRectangle(rectangle.getLowerLeftX() + padding, rectangle.getLowerLeftY() + padding,
            rectangle.getWidth() - 2 * padding, rectangle.getHeight() - 2 * padding);
}