Example usage for java.awt Rectangle getWidth

List of usage examples for java.awt Rectangle getWidth

Introduction

In this page you can find the example usage for java.awt Rectangle getWidth.

Prototype

public double getWidth() 

Source Link

Document

Returns the width of the bounding Rectangle in double precision.

Usage

From source file:SciTK.Plot.java

/**
 * Exports a JFreeChart to a PS file using Adobe XML graphics library.
 * /*  ww w  . j  a  v  a  2  s  .  com*/
 * @param chart JFreeChart to export
 * @param bounds the dimensions of the viewport
 * @param psFile the output file.
 * @param mode the file write mode ("ps","eps")
 * @throws IOException if writing the file fails.
 */
protected void exportChartAsPS(JFreeChart chart, Rectangle bounds, File psFile, String mode)
        throws IOException {
    // see http://xmlgraphics.apache.org/commons/postscript.html#creating-eps

    // set up file:
    OutputStream outputStream = new FileOutputStream(psFile);

    AbstractPSDocumentGraphics2D g2d;
    if (mode == "ps")
        g2d = new PSDocumentGraphics2D(false);
    else
        g2d = new EPSDocumentGraphics2D(false);

    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

    //Set up the document size
    g2d.setupDocument(outputStream, (int) bounds.getWidth(), (int) bounds.getHeight());
    //out is the OutputStream to write the EPS to

    // draw the chart to g2d:
    chart.draw(g2d, bounds);

    // write and close file:    
    g2d.finish(); //Wrap up and finalize the EPS file
    outputStream.flush();
    outputStream.close();
}

From source file:edu.umn.cs.spatialHadoop.core.OGCESRIShape.java

@Override
public void draw(Graphics g, Rectangle fileMBR, int imageWidth, int imageHeight, double scale) {
    OGCGeometry geom = this.geom;
    Color shape_color = g.getColor();
    if (geom instanceof OGCGeometryCollection) {
        OGCGeometryCollection geom_coll = (OGCGeometryCollection) geom;
        for (int i = 0; i < geom_coll.numGeometries(); i++) {
            OGCGeometry sub_geom = geom_coll.geometryN(i);
            // Recursive call to draw each geometry
            new OGCESRIShape(sub_geom).draw(g, fileMBR, imageWidth, imageHeight, scale);
        }//from   w  ww .  j  a  v a2s.c  om
    } else if (geom.getEsriGeometry() instanceof MultiPath) {
        MultiPath path = (MultiPath) geom.getEsriGeometry();
        double sub_geom_alpha = path.calculateLength2D() * scale;
        int color_alpha = sub_geom_alpha > 1.0 ? 255 : (int) Math.round(sub_geom_alpha * 255);

        if (color_alpha == 0)
            return;

        int[] xpoints = new int[path.getPointCount()];
        int[] ypoints = new int[path.getPointCount()];

        for (int i = 0; i < path.getPointCount(); i++) {
            double px = path.getPoint(i).getX();
            double py = path.getPoint(i).getY();

            // Transform a point in the polygon to image coordinates
            xpoints[i] = (int) Math.round((px - fileMBR.x1) * imageWidth / fileMBR.getWidth());
            ypoints[i] = (int) Math.round((py - fileMBR.y1) * imageHeight / fileMBR.getHeight());
        }

        // Draw the polygon
        g.setColor(new Color((shape_color.getRGB() & 0x00FFFFFF) | (color_alpha << 24), true));
        if (path instanceof Polygon)
            g.drawPolygon(xpoints, ypoints, path.getPointCount());
        else if (path instanceof Polyline)
            g.drawPolyline(xpoints, ypoints, path.getPointCount());
    }
}

From source file:edu.stanford.epadd.launcher.Splash.java

public Splash() {
    final SplashScreen splash = (System.getProperty("nobrowseropen") == null) ? SplashScreen.getSplashScreen()
            : null;//from  www . jav  a2 s .  c o  m
    if (splash == null) {
        System.out.println("SplashScreen.getSplashScreen() returned null");
        return;
    }
    Rectangle r = splash.getBounds();
    g = splash.createGraphics();
    if (g == null) {
        System.out.println("splash.createGraphics() returned null");
        return;
    }

    /* code to prevent text from appearing too pixelated - https://stackoverflow.com/questions/31536952/how-to-fix-text-quality-in-java-graphics */
    Map<?, ?> desktopHints = (Map<?, ?>) Toolkit.getDefaultToolkit()
            .getDesktopProperty("awt.font.desktophints");
    if (desktopHints != null) {
        g.setRenderingHints(desktopHints);
    }
    System.out.println("splash url = " + splash.getImageURL() + " w=" + r.getWidth() + " h=" + r.getHeight()
            + " size=" + r.getSize() + " loc=" + r.getLocation());
    //      setVisible(true);
    //      toFront();
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

public Rectangle2D computeSizeData(AnnotationObject a) {
    // compute bbox
    theGlycanRenderer.getGraphicOptions().setScale(theOptions.SCALE_GLYCANS * theDocument.getScale(a));
    Rectangle bbox = theGlycanRenderer.computeBoundingBoxes(a.getStructures(), false, false,
            new PositionManager(), new BBoxManager(), false);

    // compute text bbox        
    DecimalFormat mz_df = new DecimalFormat("0.0");
    String mz_text = mz_df.format(a.getPeakPoint().getX());
    Dimension mz_dim = textBounds(mz_text, theOptions.ANNOTATION_MZ_FONT, theOptions.ANNOTATION_MZ_SIZE);

    // update bbox
    double width = Math.max(bbox.getWidth(), mz_dim.getWidth());
    double height = bbox.getHeight() + theOptions.ANNOTATION_MARGIN + theOptions.ANNOTATION_MZ_SIZE;
    return new Rectangle2D.Double(0, 0, screenToDataX(width), screenToDataY(height));
}

From source file:com.t3.macro.api.views.TokenView.java

/**
 * Returns a set of the parts of a token that can be seen by this token.
 * @param target the token of which we want to check what this token can see
 * @return the set of visible token parts
 *///from   w w w  .ja  v  a 2  s . c  o  m
public EnumSet<TokenPart> getVisibleTokenParts(TokenView target) {
    if (!token.getHasSight())
        return EnumSet.noneOf(TokenPart.class);

    ZoneRenderer zr = TabletopTool.getFrame().getZoneRenderer(token.getZone());
    Zone zone = zr.getZone();
    Area tokensVisibleArea = zr.getZoneView().getVisibleArea(token);
    if (tokensVisibleArea == null)
        return EnumSet.noneOf(TokenPart.class);
    if (target == null)
        throw new NullPointerException();
    if (!target.isVisible() || (target.token.isVisibleOnlyToOwner() && !AppUtil.playerOwns(target.token))) {
        return EnumSet.noneOf(TokenPart.class);
    }
    Grid grid = zone.getGrid();

    Rectangle bounds = target.token.getFootprint(grid).getBounds(grid,
            grid.convert(new ZonePoint(target.token.getX(), target.token.getY())));
    if (!target.token.isSnapToGrid())
        bounds = target.token.getBounds(zone);

    EnumSet<TokenPart> ret = EnumSet.noneOf(TokenPart.class);

    int x = (int) bounds.getX();
    int y = (int) bounds.getY();
    int w = (int) bounds.getWidth();
    int h = (int) bounds.getHeight();

    int halfX = x + (w) / 2;
    int halfY = y + (h) / 2;
    if (tokensVisibleArea.intersects(bounds)) {
        if (tokensVisibleArea.contains(new Point(x, y)))
            ret.add(TokenPart.TOP_LEFT);
        if (tokensVisibleArea.contains(new Point(x, y + h)))
            if (tokensVisibleArea.contains(new Point(x + w, y)))
                ret.add(TokenPart.TOP_RIGHT);
        if (tokensVisibleArea.contains(new Point(x + w, y + h)))
            ret.add(TokenPart.BOTTOM_LEFT);
        if (tokensVisibleArea.contains(new Point(halfX, halfY)))
            ret.add(TokenPart.BOTTOM_RIGHT);
    }
    return ret;
}

From source file:Creator.WidgetPanel.java

public String createWidget(WidgetLink wl, Rectangle rect, int[] io_id) {

    if (widgetList.containsKey(wl.getWidgetCodeName())) {
        WidgetCode wc = widgetList.get(wl.getWidgetCodeName());
        Point per = wl.getPositionPercentage();

        int xPos = rect.x + (int) (per.getX() * rect.getWidth() / 100.0);
        int yPos = rect.y + (int) (per.getY() * rect.getHeight() / 100.0);

        String code = wc.getFullWidgetText();

        code = code.replace("`%IO_ID%`", String.valueOf(io_id[0])).replace("`%XPOS%`", String.valueOf(xPos))
                .replace("`%YPOS%`", String.valueOf(yPos));

        for (int i = 1; i < io_id.length; i++) {
            code = code.replace("`%IO_ID" + String.valueOf(i + 1) + "%`", String.valueOf(io_id[i]));
        }// w  w  w . j av a 2 s. c om

        for (Map.Entry<String, String> entry : wl.getVariables().entrySet()) {

            code = code.replace(entry.getKey(), entry.getValue());
        }

        return code;
    } else {
        System.out.println("Could not find a link for the widget named: " + wl.getWidgetCodeName());
        return "";
    }
}

From source file:knop.psfj.BeadImage.java

/**
 * Gets the enlarged frame.//w  w w  . j  a  v a2s .c  o m
 *
 * @param r the r
 * @return the enlarged frame
 */
public Rectangle getEnlargedFrame(Rectangle r) {
    Rectangle rn = new Rectangle();

    int f = frameSize;

    if (frameSize * frameSize >= imageWidth * imageHeight * 0.8) {
        rn.setLocation(0, 0);
        rn.setSize(imageWidth, imageHeight);
        return rn;
    }

    int x = MathUtils.round(r.getX() + r.getWidth() / 2 - f / 2);

    int y = MathUtils.round(r.getY() + r.getHeight() / 2 - f / 2);

    x -= 1;
    y -= 1;

    int w = f;
    int h = f;
    rn.setLocation(x, y);
    rn.setSize(w, h);

    return rn;
}

From source file:com.joliciel.jochre.graphics.SegmenterImpl.java

void removeOversizedShapes(List<Shape> shapes) {
    LOG.debug("########## removeOversizedShapes #########");
    Mean shapeHeightMean = new Mean();
    Mean shapeWidthMean = new Mean();

    for (Shape shape : shapes) {
        shapeHeightMean.increment(shape.getHeight());
        shapeWidthMean.increment(shape.getWidth());
    }/*  w ww  .j  a v a2s .c  om*/

    double heightMean = shapeHeightMean.getResult();
    double widthMean = shapeWidthMean.getResult();
    LOG.debug("heightMean: " + heightMean);
    LOG.debug("widthMean: " + widthMean);

    shapeHeightMean = new Mean();
    shapeWidthMean = new Mean();
    StandardDeviation shapeHeightStdDev = new StandardDeviation();
    for (Shape shape : shapes) {
        if (shape.getHeight() > heightMean && shape.getHeight() < (heightMean * 2.0)
                && shape.getWidth() > widthMean && shape.getWidth() < (widthMean * 2.0)) {
            shapeHeightMean.increment(shape.getHeight());
            shapeHeightStdDev.increment(shape.getHeight());
            shapeWidthMean.increment(shape.getWidth());
        }
    }

    heightMean = shapeHeightMean.getResult();
    widthMean = shapeWidthMean.getResult();
    LOG.debug("average shape heightMean: " + heightMean);
    LOG.debug("average shape widthMean: " + widthMean);

    double minHeightBigShape = heightMean * 6;
    double minWidthWideShape = widthMean * 6;
    double minHeightWideShape = heightMean * 1.5;
    double minHeightTallShape = heightMean * 2.5;
    double maxWidthTallShape = widthMean / 2;
    LOG.debug("minHeightBigShape: " + minHeightBigShape);
    LOG.debug("minWidthWideShape: " + minWidthWideShape);
    LOG.debug("minHeightWideShape: " + minHeightWideShape);
    LOG.debug("minHeightTallShape: " + minHeightTallShape);
    LOG.debug("maxWidthTallShape: " + maxWidthTallShape);

    List<Shape> largeShapes = new ArrayList<Shape>();
    List<Shape> horizontalRules = new ArrayList<Shape>();
    for (Shape shape : shapes) {
        if (shape.getHeight() > minHeightBigShape) {
            LOG.debug("Removing " + shape + " (height)");
            largeShapes.add(shape);
        } else if (shape.getWidth() > minWidthWideShape && shape.getHeight() > minHeightWideShape) {
            // we don't want to remove horizontal bars, but we do want to remove other shapes.
            // why not? I suppose horizontal bars are easily represented as characters?
            LOG.debug("Removing " + shape + " (width)");
            largeShapes.add(shape);
        } else if (shape.getWidth() > minWidthWideShape) {
            // ok, we will remove horizontal rules after all
            LOG.debug("Removing " + shape + " (horizontal rule)");
            largeShapes.add(shape);
            horizontalRules.add(shape);
        } else if (shape.getWidth() <= maxWidthTallShape && shape.getHeight() > minHeightTallShape) {
            LOG.debug("Removing " + shape + " (narrow)");
            largeShapes.add(shape);
        }
    }

    // Only want to remove enclosed shapes if the large shape isn't a frame/grid
    // A) first reduce the shape by 5 percent and see it's cardinality reduces vastly (in which case it's a frame)
    // if so, don't remove enclosed shapes
    // B) next, detect white rectangles within the shape - if they're big enough, don't remove enclosed shapes      LOG.debug("Are large shapes frames or illustrations?");
    double maxFrameCardinalityRatio = 0.5;
    double minFrameWhiteAreaSizeRatio = 0.9;
    List<Shape> illustrations = new ArrayList<Shape>(largeShapes);
    for (Shape largeShape : largeShapes) {
        LOG.debug(largeShape.toString());
        int xOrigin = largeShape.getStartingPoint()[0] - largeShape.getLeft();
        int yOrigin = largeShape.getStartingPoint()[1] - largeShape.getTop();
        Shape dummyShape = graphicsService.getDot(sourceImage, xOrigin, yOrigin);
        // We want to fill up a mirror of the contiguous pixels within this shape,
        // which is what we'll use for further analysis to know
        // if it's a frame or not.
        WritableImageGrid mirror = graphicsService.getEmptyMirror(largeShape);
        this.findContiguousPixels(largeShape, mirror, dummyShape, xOrigin, yOrigin,
                sourceImage.getSeparationThreshold());

        int adjustedLeft = (int) Math.round((double) mirror.getWidth() * 0.05);
        int adjustedRight = (int) Math.round((double) mirror.getWidth() * 0.95);
        int adjustedTop = (int) Math.round((double) mirror.getHeight() * 0.05);
        int adjustedBottom = (int) Math.round((double) mirror.getHeight() * 0.95);

        int cardinality = 0;
        int innerCardinality = 0;
        for (int x = 0; x < mirror.getWidth(); x++) {
            for (int y = 0; y < mirror.getHeight(); y++) {
                if (mirror.getPixel(x, y) > 0) {
                    cardinality++;
                    if (x >= adjustedLeft && x <= adjustedRight && y >= adjustedTop && y <= adjustedBottom)
                        innerCardinality++;
                }
            }
        }

        LOG.debug("cardinality: " + cardinality);
        LOG.debug("innerCardinality: " + innerCardinality);
        double ratio = (double) innerCardinality / (double) cardinality;
        LOG.debug("ratio: " + ratio);
        if (ratio <= maxFrameCardinalityRatio) {
            LOG.debug("maxFrameCardinalityRatio: " + maxFrameCardinalityRatio);
            LOG.debug("Frame by cardinality! Removing from illustrations");
            illustrations.remove(largeShape);
        } else {
            // Now, it could still be a grid
            // to find this out we need to detect white areas inside the shape.
            WhiteAreaFinder whiteAreaFinder = new WhiteAreaFinder();
            double minWhiteAreaWidth = widthMean * 10;
            double minWhiteAreaHeight = heightMean * 4;
            List<Rectangle> whiteAreas = whiteAreaFinder.getWhiteAreas(mirror, 0, 0, 0, mirror.getWidth() - 1,
                    mirror.getHeight() - 1, minWhiteAreaWidth, minWhiteAreaHeight);
            int whiteAreaSize = 0;
            for (Rectangle whiteArea : whiteAreas) {
                whiteAreaSize += (whiteArea.getWidth() * whiteArea.getHeight());
            }

            int totalSize = mirror.getWidth() * mirror.getHeight();
            LOG.debug("whiteAreaSize: " + whiteAreaSize);
            LOG.debug("totalSize: " + totalSize);

            double sizeRatio = (double) whiteAreaSize / (double) totalSize;
            LOG.debug("sizeRatio: " + sizeRatio);

            if (sizeRatio >= minFrameWhiteAreaSizeRatio) {
                LOG.debug("minFrameWhiteAreaSizeRatio: " + minFrameWhiteAreaSizeRatio);
                LOG.debug("Frame by white area size! Removing from illustrations");
                illustrations.remove(largeShape);
            }

        }
    }

    for (Shape largeShape : illustrations) {
        // Add this to large shapes if it's not a "frame"
        // large shapes are used for paragraph detection
        sourceImage.getLargeShapes().add(largeShape);
    }

    // remove shapes that are enclosed inside illustrations
    List<Shape> enclosedShapesToDelete = new ArrayList<Shape>();
    int extension = 5;
    for (Shape shape : shapes) {
        for (Shape shapeToDelete : illustrations) {
            if (shape.getLeft() >= shapeToDelete.getLeft() - extension
                    && shape.getRight() <= shapeToDelete.getRight() + extension
                    && shape.getTop() >= shapeToDelete.getTop() - extension
                    && shape.getBottom() <= shapeToDelete.getBottom() + extension) {
                LOG.debug("Enclosed shape: " + shape);
                LOG.debug(" enclosed by " + shapeToDelete);
                enclosedShapesToDelete.add(shape);
            }
        }
    }

    shapes.removeAll(largeShapes);
    shapes.removeAll(enclosedShapesToDelete);

    // remove shapes that are practically touching horizontal rules (probably segments of the rule that got split)
    extension = 3;
    List<Shape> listToTestAgainst = horizontalRules;
    for (int i = 0; i < 3; i++) {
        List<Shape> horizontalRuleSegments = new ArrayList<Shape>();
        for (Shape horizontalRule : listToTestAgainst) {
            for (Shape shape : shapes) {
                if ((shape.getLeft() <= horizontalRule.getRight() + extension
                        || shape.getRight() >= horizontalRule.getLeft() - extension)
                        && shape.getTop() >= horizontalRule.getTop() - extension
                        && shape.getBottom() <= horizontalRule.getBottom() + extension) {
                    LOG.debug("Horizontal rule segment: " + shape);
                    LOG.debug(" touching " + horizontalRule);
                    horizontalRuleSegments.add(shape);
                    enclosedShapesToDelete.add(shape);
                }
            }
        }
        shapes.removeAll(horizontalRuleSegments);
        listToTestAgainst = horizontalRuleSegments;
        if (listToTestAgainst.size() == 0)
            break;
    }

}

From source file:net.sqs2.omr.session.logic.PageImageRenderer.java

private static void drawFormAreas(int pageIndex, float densityThreshold, FormMaster master,
        PageTaskResult pageTaskResult, Graphics2D g, MarkRecognitionConfig markRecognizationConfig,
        DeskewedImageSource pageSource, int focusedColumnIndex, Rectangle scope) {
    int formAreaIndexInPage = 0;

    int minX = Integer.MAX_VALUE;
    int minY = Integer.MAX_VALUE;
    int maxX = Integer.MIN_VALUE;
    int maxY = Integer.MIN_VALUE;

    for (FormArea formArea : master.getFormAreaListByPageIndex(pageIndex)) {
        FormAreaResult result = (FormAreaResult) pageTaskResult.getPageAreaResultList()
                .get(formAreaIndexInPage);
        if (formArea.isMarkArea()) {
            if (focusedColumnIndex == formArea.getQuestionIndex()) {

                Rectangle rect = formArea.getRect();

                Point2D p1 = pageSource.getPoint((int) rect.getX(), (int) rect.getY());
                Point2D p2 = pageSource.getPoint((int) (rect.getX() + rect.getWidth()),
                        (int) (rect.getY() + rect.getHeight()));

                minX = Math.min(minX, (int) p1.getX());
                minY = Math.min(minY, (int) p1.getY());
                maxX = Math.max(maxX, (int) p2.getX());
                maxY = Math.max(maxY, (int) p2.getY());

                if (result.getDensity() < densityThreshold) {
                    g.setColor(FOCUSED_MARKED_COLOR);
                } else {
                    g.setColor(FOCUSED_NO_MARKED_COLOR);
                }/*from  w ww .  ja va 2s . c  om*/

            } else {
                if (result.getDensity() < densityThreshold) {
                    g.setColor(MARKED_COLOR);
                } else {
                    g.setColor(NO_MARKED_COLOR);
                }
            }

            g.fillPolygon(pageSource.createRectPolygon(
                    getExtendedRectangle(formArea.getRect(), markRecognizationConfig.getHorizontalMargin(),
                            markRecognizationConfig.getVerticalMargin())));
            g.drawPolygon(pageSource.createRectPolygon(
                    getExtendedRectangle(formArea.getRect(), markRecognizationConfig.getHorizontalMargin() + 3,
                            markRecognizationConfig.getVerticalMargin() + 3)));

        } else {
            g.setColor(TEXTAREA_COLOR);
            g.fillPolygon(pageSource.createRectPolygon(formArea.getRect()));
        }
        formAreaIndexInPage++;
    }

    if (scope != null) {
        int borderMarginX = 20;
        int borderMarginY = 3;
        int margin = 40;

        int x = minX - borderMarginX;
        int y = minY - borderMarginY;
        int width = maxX - minX + borderMarginX * 2;
        int height = maxY - minY + borderMarginY * 2;

        scope.x = minX - margin;
        scope.y = minY - margin;
        scope.width = maxX - minX + margin * 2;
        scope.height = maxY - minY + margin * 2;

        Stroke stroke = new BasicStroke(4.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 2.0f,
                new float[] { 4.0f, 8.0f }, 0.0f);
        g.setStroke(stroke);
        g.setColor(FOCUSED_SCOPE_COLOR);
        g.drawRoundRect(x, y, width, height, 20, 20);
    }

}

From source file:org.apache.fop.render.pdf.pdfbox.PDFBoxAdapter.java

/**
 * Creates a stream (from FOP's PDF library) from a PDF page parsed with PDFBox.
 * @param sourceDoc the source PDF the given page to be copied belongs to
 * @param page the page to transform into a stream
 * @param key value to use as key for the stream
 * @param atdoc adjustment for stream//from  w w w . ja v a  2  s. com
 * @param fontinfo fonts
 * @param pos rectangle
 * @return the stream
 * @throws IOException if an I/O error occurs
 */
public String createStreamFromPDFBoxPage(PDDocument sourceDoc, PDPage page, String key, AffineTransform atdoc,
        FontInfo fontinfo, Rectangle pos) throws IOException {
    handleAnnotations(sourceDoc, page, atdoc);
    if (pageNumbers.containsKey(targetPage.getPageIndex())) {
        pageNumbers.get(targetPage.getPageIndex()).set(0, targetPage.makeReference());
    }
    PDResources sourcePageResources = page.getResources();
    PDStream pdStream = getContents(page);

    COSDictionary fonts = (COSDictionary) sourcePageResources.getCOSObject().getDictionaryObject(COSName.FONT);
    COSDictionary fontsBackup = null;
    UniqueName uniqueName = new UniqueName(key, sourcePageResources);
    String newStream = null;
    if (fonts != null && pdfDoc.isMergeFontsEnabled()) {
        fontsBackup = new COSDictionary(fonts);
        MergeFontsPDFWriter m = new MergeFontsPDFWriter(fonts, fontinfo, uniqueName, parentFonts, currentMCID);
        newStream = m.writeText(pdStream);
        //            if (newStream != null) {
        //                for (Object f : fonts.keySet().toArray()) {
        //                    COSDictionary fontdata = (COSDictionary)fonts.getDictionaryObject((COSName)f);
        //                    if (getUniqueFontName(fontdata) != null) {
        //                        fonts.removeItem((COSName)f);
        //                    }
        //                }
        //            }
    }
    if (newStream == null) {
        PDFWriter writer = new PDFWriter(uniqueName, currentMCID);
        newStream = writer.writeText(pdStream);
        currentMCID = writer.getCurrentMCID();

    }
    pdStream = new PDStream(sourceDoc, new ByteArrayInputStream(newStream.getBytes("ISO-8859-1")));
    mergeXObj(sourcePageResources.getCOSObject(), fontinfo, uniqueName);
    PDFDictionary pageResources = (PDFDictionary) cloneForNewDocument(sourcePageResources.getCOSObject());

    PDFDictionary fontDict = (PDFDictionary) pageResources.get("Font");
    if (fontDict != null && pdfDoc.isMergeFontsEnabled()) {
        for (Map.Entry<String, Typeface> fontEntry : fontinfo.getUsedFonts().entrySet()) {
            Typeface font = fontEntry.getValue();
            if (font instanceof FOPPDFFont) {
                FOPPDFFont pdfFont = (FOPPDFFont) font;
                if (pdfFont.getRef() == null) {
                    pdfFont.setRef(new PDFDictionary());
                    pdfDoc.assignObjectNumber(pdfFont.getRef());
                }
                fontDict.put(fontEntry.getKey(), pdfFont.getRef());
            }
        }
    }
    updateXObj(sourcePageResources.getCOSObject(), pageResources);
    if (fontsBackup != null) {
        sourcePageResources.getCOSObject().setItem(COSName.FONT, fontsBackup);
    }

    COSStream originalPageContents = pdStream.getCOSObject();

    bindOptionalContent(sourceDoc);

    PDFStream pageStream;
    Set filter;
    //        if (originalPageContents instanceof COSStreamArray) {
    //            COSStreamArray array = (COSStreamArray)originalPageContents;
    //            pageStream = new PDFStream();
    //            InputStream in = array.getUnfilteredStream();
    //            OutputStream out = pageStream.getBufferOutputStream();
    //            IOUtils.copyLarge(in, out);
    //            filter = FILTER_FILTER;
    //        } else {
    pageStream = (PDFStream) cloneForNewDocument(originalPageContents);
    filter = Collections.EMPTY_SET;
    //        }
    if (pageStream == null) {
        pageStream = new PDFStream();
    }
    if (originalPageContents != null) {
        transferDict(originalPageContents, pageStream, filter);
    }

    transferPageDict(fonts, uniqueName, sourcePageResources);

    PDRectangle mediaBox = page.getMediaBox();
    PDRectangle cropBox = page.getCropBox();
    PDRectangle viewBox = cropBox != null ? cropBox : mediaBox;

    //Handle the /Rotation entry on the page dict
    int rotation = PDFUtil.getNormalizedRotation(page);

    //Transform to FOP's user space
    float w = (float) pos.getWidth() / 1000f;
    float h = (float) pos.getHeight() / 1000f;
    if (rotation == 90 || rotation == 270) {
        float tmp = w;
        w = h;
        h = tmp;
    }
    atdoc.setTransform(AffineTransform.getScaleInstance(w / viewBox.getWidth(), h / viewBox.getHeight()));
    atdoc.translate(0, viewBox.getHeight());
    atdoc.rotate(-Math.PI);
    atdoc.scale(-1, 1);
    atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());

    rotate(rotation, viewBox, atdoc);

    StringBuilder boxStr = new StringBuilder();
    boxStr.append(PDFNumber.doubleOut(mediaBox.getLowerLeftX())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getLowerLeftY())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getWidth())).append(' ')
            .append(PDFNumber.doubleOut(mediaBox.getHeight())).append(" re W n\n");
    return boxStr.toString() + IOUtils.toString(pdStream.createInputStream(null), "ISO-8859-1");
}