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

The following examples show how to use org.apache.pdfbox.pdmodel.common.PDRectangle#getWidth() . 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: PDFCreator.java    From Knowage-Server with GNU Affero General Public License v3.0 7 votes vote down vote up
private static void writeFrontpageDetails(PDDocument doc, PDFont font, float fontSize, FrontpageDetails details) throws IOException {
	String name = "Name: " + details.getName();
	String description = "Description: " + details.getDescription();
	String date = "Date: " + DEFAULT_DATE_FORMATTER.format(details.getDate());
	PDPage page = doc.getPage(0);
	PDRectangle pageSize = page.getMediaBox();
	float stringWidth = font.getStringWidth(StringUtilities.findLongest(name, description, date)) * 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 / 3f : (pageWidth - stringWidth - stringHeight) / 3f;
	float startY = rotate ? (pageWidth - stringWidth) / 1f : pageWidth / 0.9f;

	// append the content to the existing stream
	try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true)) {
		// draw rectangle
		writeText(contentStream, new Color(4, 44, 86), font, fontSize, rotate, startX, startY, name, description, date);
	}
}
 
Example 2
Source File: SignatureImageAndPositionProcessor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static float processXAngle180(PDRectangle mediaBox, SignatureImageParameters signatureImageParameters, float width) {
      float x;

VisualSignatureAlignmentHorizontal alignmentHorizontal = signatureImageParameters.getVisualSignatureAlignmentHorizontal();

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

      return x;
  }
 
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 processXAngle90(PDRectangle mediaBox, SignatureImageParameters signatureImageParameters, float width) {
      float x;

VisualSignatureAlignmentVertical alignmentVertical = signatureImageParameters.getVisualSignatureAlignmentVertical();

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

      return x;
  }
 
Example 4
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 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: 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 7
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 8
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Calculate the transform to be used when positioning the overlay. The default implementation
 * centers on the destination. Override this method to do your own, e.g. move to a corner, or
 * rotate.
 *
 * @param page The page that will get the overlay.
 * @param overlayMediaBox The overlay media box.
 * @return The affine transform to be used.
 */
protected AffineTransform calculateAffineTransform(PDPage page, PDRectangle overlayMediaBox)
{
    AffineTransform at = new AffineTransform();
    PDRectangle pageMediaBox = page.getMediaBox();
    float hShift = (pageMediaBox.getWidth() - overlayMediaBox.getWidth()) / 2.0f;
    float vShift = (pageMediaBox.getHeight() - overlayMediaBox.getHeight()) / 2.0f;
    at.translate(hShift, vShift);
    return at;
}
 
Example 9
Source File: PDVisibleSignDesigner.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Each page of document can be different sizes. This method calculates the page size based on
 * the page media box.
 * 
 * @param document
 * @param page The 1-based page number for which the page size should be calculated.
 * @throws IllegalArgumentException if the page argument is lower than 0.
 */
private void calculatePageSize(PDDocument document, int page)
{
    if (page < 1)
    {
        throw new IllegalArgumentException("First page of pdf is 1, not " + page);
    }

    PDPage firstPage = document.getPage(page - 1);
    PDRectangle mediaBox = firstPage.getMediaBox();
    pageHeight(mediaBox.getHeight());
    pageWidth = mediaBox.getWidth();
    imageSizeInPercents = 100;
    rotation = firstPage.getRotation() % 360;
}
 
Example 10
Source File: PDFDomTree.java    From Pdf2Dom with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Creates an element that represents a single page.
 * @return the resulting DOM element
 */
protected Element createPageElement()
{
    String pstyle = "";
    PDRectangle layout = getCurrentMediaBox();
    if (layout != null)
    {
        /*System.out.println("x1 " + layout.getLowerLeftX());
        System.out.println("y1 " + layout.getLowerLeftY());
        System.out.println("x2 " + layout.getUpperRightX());
        System.out.println("y2 " + layout.getUpperRightY());
        System.out.println("rot " + pdpage.findRotation());*/
        
        float w = layout.getWidth();
        float h = layout.getHeight();
        final int rot = pdpage.getRotation();
        if (rot == 90 || rot == 270)
        {
            float x = w; w = h; h = x;
        }
        
        pstyle = "width:" + w + UNIT + ";" + "height:" + h + UNIT + ";";
        pstyle += "overflow:hidden;";
    }
    else
        log.warn("No media box found");
    
    Element el = doc.createElement("div");
    el.setAttribute("id", "page_" + (pagecnt++));
    el.setAttribute("class", "page");
    el.setAttribute("style", pstyle);
    return el;
}
 
Example 11
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 12
Source File: AppearanceGeneratorHelper.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Apply padding to a box.
 * 
 * @param box box
 * @return the padded box.
 */
private PDRectangle applyPadding(PDRectangle box, float padding)
{
    return new PDRectangle(box.getLowerLeftX() + padding, 
                           box.getLowerLeftY() + padding, 
                           box.getWidth() - 2 * padding,
                           box.getHeight() - 2 * padding);
}
 
Example 13
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 14
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 15
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 16
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 17
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 18
Source File: ExtractText.java    From testarea-pdfbox2 with Apache License 2.0 4 votes vote down vote up
/**
     * <a href="https://stackoverflow.com/questions/54822124/pdftextstripperbyarea-and-pdftextstripper-parsing-different-text-output-for-tabl">
     * PDFTextStripperByArea and PDFTextStripper parsing different Text Output for Table with Merged Cell or Table cell with multi-line text content
     * </a>
     * <br/>
     * <a href="https://www4.esc13.net/uploads/webccat/docs/PDFTables_12142005.pdf">
     * PDFTables_12142005.pdf
     * </a>
     * <p>
     * Cannot reproduce the problem, and the OP does not react to clarification requests.
     * </p>
     */
    @Test
    public void testPDFTables_12142005() throws IOException {
        try (   InputStream resource = getClass().getResourceAsStream("PDFTables_12142005.pdf")    )
        {
            PDDocument document =  Loader.loadPDF(resource);

            PDFTextStripper textStripper = new PDFTextStripper();
            textStripper.setSortByPosition(true);
            textStripper.setAddMoreFormatting(false);
            // textStripper.setSpacingTolerance(1.5F);
            //textStripper.setAverageCharTolerance(averageCharToleranceValue);

            textStripper.setStartPage(2);
            textStripper.setEndPage(2);

            textStripper.getCurrentPage();
            String text = textStripper.getText(document).trim();
            System.out.println("PDF text is: " + "\n" + text.trim());

            System.out.println("----------------------------------------------------------------");

            PDFTextStripperByArea stripper = new PDFTextStripperByArea();
            stripper.setSortByPosition(true);
            stripper.setAddMoreFormatting(false);
            // stripper.setSpacingTolerance(1.5F);

            Dimension dimension = new Dimension();
            dimension.setSize(document.getPage(1).getMediaBox().getWidth(),
                    document.getPage(1).getMediaBox().getHeight());
//            Rectangle2D rect = toJavaRect(document.getBleedBox(), dimension);
//            Rectangle2D rect1 = toJavaRect(document.getArtBox(), dimension);
            PDRectangle mediaBox = document.getPage(1).getMediaBox();
            Rectangle2D rect = new Rectangle2D.Float(mediaBox.getLowerLeftX(), mediaBox.getLowerLeftY(), mediaBox.getWidth(), mediaBox.getHeight());
            Rectangle2D rect1 = rect;

            /*
             * Rectangle2D rect = new
             * Rectangle2D.Float(document.getBleedBox().getLowerLeftX(),
             * document.getBleedBox().getLowerLeftY(), document.getBleedBox().getWidth(),
             * document.getBleedBox().getHeight());
             */

            /*
             * Rectangle2D rect1 = new
             * Rectangle2D.Float(document.getArtBox().getLowerLeftX(),
             * document.getArtBox().getLowerLeftY(), document.getArtBox().getWidth(),
             * document.getArtBox().getHeight());
             */

            /*
             * Rectangle2D rect = new
             * Rectangle2D.Float(document.getBleedBox().getLowerLeftX(),
             * document.getBleedBox().getUpperRightY(), document.getBleedBox().getWidth(),
             * document.getBleedBox().getHeight());
             */

            System.out.println("Rectangle bleedBox Content : " + "\n" + rect);
            System.out.println("----------------------------------------------------------------");
            System.out.println("Rectangle artBox Content : " + "\n" + rect1);
            System.out.println("----------------------------------------------------------------");
            stripper.addRegion("Test1", rect);
            stripper.addRegion("Test2", rect1);
            stripper.extractRegions(document.getPage(1));

            System.out.println("Text in the area-BleedBox : " + "\n" + stripper.getTextForRegion("Test1").trim());
            System.out.println("----------------------------------------------------------------");
            System.out.println("Text in the area1-ArtBox : " + "\n" + stripper.getTextForRegion("Test2").trim());
            System.out.println("----------------------------------------------------------------");

            StringBuilder artPlusBleedBox = new StringBuilder();
            artPlusBleedBox.append(stripper.getTextForRegion("Test2").trim());
            artPlusBleedBox.append("\r\n");
            artPlusBleedBox.append(stripper.getTextForRegion("Test1").trim());

            System.out.println("Whole Page Text : " + artPlusBleedBox);
            System.out.println("----------------------------------------------------------------");
            text = new String(text.trim().getBytes(), "UTF-8");
            String text2 = new String(artPlusBleedBox.toString().trim().getBytes(), "UTF-8");
            System.out.println(" Matches equals with Both Content : " + text.equals(artPlusBleedBox.toString()));
            System.out.println(" String Matches equals with Both Content : " + text.equalsIgnoreCase(text2));
        }
    }
 
Example 19
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 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);
}