Example usage for java.awt.geom AffineTransform translate

List of usage examples for java.awt.geom AffineTransform translate

Introduction

In this page you can find the example usage for java.awt.geom AffineTransform translate.

Prototype

public void translate(double tx, double ty) 

Source Link

Document

Concatenates this transform with a translation transformation.

Usage

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.PlotInstanceLegendCreator.java

/**
 * Creates a continuous legend item for one item in dimensionSet, i.e. dimensionSet must be a
 * set containing exactly one value.//from  w w  w.  j  a  v  a2 s  .  c o m
 * 
 * @param dateFormat
 *            format used to format minValue and maxValue as dates, or null if they should be
 *            displayed numerically instead of as dates
 * @throws ChartPlottimeException
 */
private LegendItem createContinuousLegendItem(PlotInstance plotInstance, Set<PlotDimension> dimensionSet,
        double minValue, double maxValue, DateFormat dateFormat) {
    PlotConfiguration plotConfiguration = plotInstance.getCurrentPlotConfigurationClone();
    PlotDimension dimension = dimensionSet.iterator().next();
    DefaultDimensionConfig dimensionConfig = (DefaultDimensionConfig) plotConfiguration
            .getDimensionConfig(dimension);
    DimensionConfigData dimensionConfigData = plotInstance.getPlotData()
            .getDimensionConfigData(dimensionConfig);
    // String label = dimensionConfig.getLabel();
    // if(label == null) {
    // label = I18N.getGUILabel("plotter.unnamed_value_label");
    // }
    String label = "";

    if (dimension == PlotDimension.COLOR) {
        ColorProvider colorProvider = dimensionConfigData.getColorProvider();
        if (!colorProvider.supportsNumericalValues()) {
            throw new RuntimeException(
                    "Color provider for continuous legend item does not support numerical values.");
        }

        // shape dimensions
        final int width = 50;
        final int height = 10;

        // create item paint

        // first disable logarithmic scale on color provider ( -> linear gradient in legend)
        // ContinuousColorProvider continuousColorProvider = null;
        // if (dimensionConfig.isLogarithmic() && colorProvider instanceof
        // ContinuousColorProvider) {
        // continuousColorProvider = (ContinuousColorProvider)colorProvider;
        // continuousColorProvider.setLogarithmic(false);
        // }

        // calculate gradient
        float fractions[] = new float[width];
        Color colors[] = new Color[width];
        for (int i = 0; i < width; ++i) {

            float fraction = i / (width - 1.0f);
            double fractionValue;
            if (colorProvider instanceof ContinuousColorProvider
                    && ((ContinuousColorProvider) colorProvider).isColorMinMaxValueDifferentFromOriginal(
                            ((ContinuousColorProvider) colorProvider).getMinValue(),
                            ((ContinuousColorProvider) colorProvider).getMaxValue())) {
                fractionValue = ((ContinuousColorProvider) colorProvider).getMinValue()
                        + fraction * (((ContinuousColorProvider) colorProvider).getMaxValue()
                                - ((ContinuousColorProvider) colorProvider).getMinValue());
            } else {
                fractionValue = minValue + fraction * (maxValue - minValue);
            }
            colors[i] = colorProvider.getColorForValue(fractionValue);
            fractions[i] = fraction;
        }
        LinearGradientPaint shapeFillPaint = new LinearGradientPaint(new Point(0, 0), new Point(width, 0),
                fractions, colors, CycleMethod.REPEAT);

        // reset color provider to logarithmic if necessary
        // if (continuousColorProvider != null && dimensionConfig.isLogarithmic()) {
        // continuousColorProvider.setLogarithmic(true);
        // }

        // create item shape
        Rectangle itemShape = new Rectangle(width, height);

        if (colorProvider instanceof ContinuousColorProvider) {
            return createFlankedShapeLegendItem(label, ((ContinuousColorProvider) colorProvider).getMinValue(),
                    ((ContinuousColorProvider) colorProvider).getMaxValue(), itemShape, shapeFillPaint, true,
                    dateFormat);
        } else {
            return createFlankedShapeLegendItem(label, minValue, maxValue, itemShape, shapeFillPaint, true,
                    dateFormat);
        }
    } else if (dimension == PlotDimension.SHAPE) {
        // shape provider probably never supports numerical values
        return null;
    } else if (dimension == PlotDimension.SIZE) {
        SizeProvider sizeProvider = dimensionConfigData.getSizeProvider();

        if (!sizeProvider.supportsNumericalValues()) {
            throw new RuntimeException(
                    "Size provider for continuous legend item does not support numerical values.");
        }

        double minScalingFactor = sizeProvider.getMinScalingFactor();
        double maxScalingFactor = sizeProvider.getMaxScalingFactor();
        ContinuousSizeProvider legendSizeProvider = new ContinuousSizeProvider(minScalingFactor,
                maxScalingFactor, MIN_LEGEND_ITEM_SCALING_FACTOR, MAX_LEGEND_ITEM_SCALING_FACTOR, false);

        int legendItemCount = 4;
        Area composedShape = new Area();
        Shape originalShape = UNDEFINED_SHAPE;
        if (dimensionSet.contains(PlotDimension.SIZE) && dimensionSet.size() == 1) {
            originalShape = UNDEFINED_SHAPE_AND_COLOR;
        }
        double maxHeight = originalShape.getBounds().getHeight() * MAX_LEGEND_ITEM_SCALING_FACTOR;
        for (int i = 0; i < legendItemCount; ++i) {
            double fraction = minScalingFactor
                    + ((double) i / legendItemCount * (maxScalingFactor - minScalingFactor));
            double legendScalingFactor = legendSizeProvider.getScalingFactorForValue(fraction);

            double composedWidth = composedShape.getBounds().getWidth();

            AffineTransform t = new AffineTransform();
            t.scale(legendScalingFactor, legendScalingFactor);
            Shape shape = t.createTransformedShape(originalShape);

            t = new AffineTransform();
            double shapeWidth = shape.getBounds().getWidth();
            double shapeHeight = shape.getBounds().getHeight();
            t.translate(composedWidth + shapeWidth * .1, (maxHeight - shapeHeight) / 2.0);
            t.translate(-shape.getBounds().getMinX(), -shape.getBounds().getMinY());
            shape = t.createTransformedShape(shape);
            composedShape.add(new Area(shape));
        }

        return createFlankedShapeLegendItem(label, minValue, maxValue, composedShape, UNDEFINED_COLOR_PAINT,
                false, dateFormat);

    } else {
        throw new RuntimeException("Unsupported dimension. Execution path should never reach this line.");
    }
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Labels the specified non-self-loop edge with the specified label.
 * Uses the font specified by this instance's 
 * <code>EdgeFontFunction</code>.  (If the font is unspecified, the existing
 * font for the graphics context is used.)  Positions the 
 * label between the endpoints according to the coefficient returned
 * by this instance's edge label closeness function.
 *//* w ww .j  ava2  s  . c o  m*/
protected void labelEdge(Graphics2D g2d, Edge e, String label, int x1, int x2, int y1, int y2) {
    int distX = x2 - x1;
    int distY = y2 - y1;
    double totalLength = Math.sqrt(distX * distX + distY * distY);

    double closeness = edgeLabelClosenessFunction.getNumber(e).doubleValue();

    int posX = (int) (x1 + (closeness) * distX);
    int posY = (int) (y1 + (closeness) * distY);

    int xDisplacement = (int) (LABEL_OFFSET * (distY / totalLength));
    int yDisplacement = (int) (LABEL_OFFSET * (-distX / totalLength));

    Component component = prepareRenderer(graphLabelRenderer, label, isPicked(e), e);

    Dimension d = component.getPreferredSize();

    Shape edgeShape = edgeShapeFunction.getShape(e);

    double parallelOffset = 1;

    parallelOffset += parallelEdgeIndexFunction.getIndex(e);

    if (edgeShape instanceof Ellipse2D) {
        parallelOffset += edgeShape.getBounds().getHeight();
        parallelOffset = -parallelOffset;
    }

    parallelOffset *= d.height;

    AffineTransform old = g2d.getTransform();
    AffineTransform xform = new AffineTransform(old);
    xform.translate(posX + xDisplacement, posY + yDisplacement);
    double dx = x2 - x1;
    double dy = y2 - y1;
    if (graphLabelRenderer.isRotateEdgeLabels()) {
        double theta = Math.atan2(dy, dx);
        if (dx < 0) {
            theta += Math.PI;
        }
        xform.rotate(theta);
    }
    if (dx < 0) {
        parallelOffset = -parallelOffset;
    }

    xform.translate(-d.width / 2, -(d.height / 2 - parallelOffset));
    g2d.setTransform(xform);
    rendererPane.paintComponent(g2d, component, screenDevice, 0, 0, d.width, d.height, true);
    g2d.setTransform(old);
}

From source file:edu.uci.ics.jung.visualization.PluggableRenderer.java

/**
 * Draws the edge <code>e</code>, whose endpoints are at <code>(x1,y1)</code>
 * and <code>(x2,y2)</code>, on the graphics context <code>g</code>.
 * The <code>Shape</code> provided by the <code>EdgeShapeFunction</code> instance
 * is scaled in the x-direction so that its width is equal to the distance between
 * <code>(x1,y1)</code> and <code>(x2,y2)</code>.
 *///from   w  w w .ja v  a2s  .c  om
protected void drawSimpleEdge(Graphics2D g, Edge e, int x1, int y1, int x2, int y2) {
    Pair endpoints = e.getEndpoints();
    Vertex v1 = (Vertex) endpoints.getFirst();
    Vertex v2 = (Vertex) endpoints.getSecond();
    boolean isLoop = v1.equals(v2);
    Shape s2 = vertexShapeFunction.getShape(v2);
    Shape edgeShape = edgeShapeFunction.getShape(e);

    boolean edgeHit = true;
    boolean arrowHit = true;
    Rectangle deviceRectangle = null;
    if (screenDevice != null) {
        Dimension d = screenDevice.getSize();
        if (d.width <= 0 || d.height <= 0) {
            d = screenDevice.getPreferredSize();
        }
        deviceRectangle = new Rectangle(0, 0, d.width, d.height);
    }

    AffineTransform xform = AffineTransform.getTranslateInstance(x1, y1);

    if (isLoop) {
        // this is a self-loop. scale it is larger than the vertex
        // it decorates and translate it so that its nadir is
        // at the center of the vertex.
        Rectangle2D s2Bounds = s2.getBounds2D();
        xform.scale(s2Bounds.getWidth(), s2Bounds.getHeight());
        xform.translate(0, -edgeShape.getBounds2D().getWidth() / 2);
    } else {
        // this is a normal edge. Rotate it to the angle between
        // vertex endpoints, then scale it to the distance between
        // the vertices
        float dx = x2 - x1;
        float dy = y2 - y1;
        float thetaRadians = (float) Math.atan2(dy, dx);
        xform.rotate(thetaRadians);
        float dist = (float) Math.sqrt(dx * dx + dy * dy);
        xform.scale(dist, 1.0);
    }

    edgeShape = xform.createTransformedShape(edgeShape);

    edgeHit = viewTransformer.transform(edgeShape).intersects(deviceRectangle);

    if (edgeHit == true) {

        Paint oldPaint = g.getPaint();

        // get Paints for filling and drawing
        // (filling is done first so that drawing and label use same Paint)
        Paint fill_paint = edgePaintFunction.getFillPaint(e);
        if (fill_paint != null) {
            g.setPaint(fill_paint);
            g.fill(edgeShape);
        }
        Paint draw_paint = edgePaintFunction.getDrawPaint(e);
        if (draw_paint != null) {
            g.setPaint(draw_paint);
            g.draw(edgeShape);
        }

        float scalex = (float) g.getTransform().getScaleX();
        float scaley = (float) g.getTransform().getScaleY();
        // see if arrows are too small to bother drawing
        if (scalex < .3 || scaley < .3)
            return;

        if (edgeArrowPredicate.evaluate(e)) {

            Shape destVertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getSecond());
            AffineTransform xf = AffineTransform.getTranslateInstance(x2, y2);
            destVertexShape = xf.createTransformedShape(destVertexShape);

            arrowHit = viewTransformer.transform(destVertexShape).intersects(deviceRectangle);
            if (arrowHit) {

                AffineTransform at;
                if (edgeShape instanceof GeneralPath)
                    at = getArrowTransform((GeneralPath) edgeShape, destVertexShape);
                else
                    at = getArrowTransform(new GeneralPath(edgeShape), destVertexShape);
                if (at == null)
                    return;
                Shape arrow = edgeArrowFunction.getArrow(e);
                arrow = at.createTransformedShape(arrow);
                // note that arrows implicitly use the edge's draw paint
                g.fill(arrow);
            }
            if (e instanceof UndirectedEdge) {
                Shape vertexShape = vertexShapeFunction.getShape((Vertex) e.getEndpoints().getFirst());
                xf = AffineTransform.getTranslateInstance(x1, y1);
                vertexShape = xf.createTransformedShape(vertexShape);

                arrowHit = viewTransformer.transform(vertexShape).intersects(deviceRectangle);

                if (arrowHit) {
                    AffineTransform at;
                    if (edgeShape instanceof GeneralPath)
                        at = getReverseArrowTransform((GeneralPath) edgeShape, vertexShape, !isLoop);
                    else
                        at = getReverseArrowTransform(new GeneralPath(edgeShape), vertexShape, !isLoop);
                    if (at == null)
                        return;
                    Shape arrow = edgeArrowFunction.getArrow(e);
                    arrow = at.createTransformedShape(arrow);
                    g.fill(arrow);
                }
            }
        }
        // use existing paint for text if no draw paint specified
        if (draw_paint == null)
            g.setPaint(oldPaint);
        String label = edgeStringer.getLabel(e);
        if (label != null) {
            labelEdge(g, e, label, x1, x2, y1, y2);
        }

        // restore old paint
        g.setPaint(oldPaint);
    }
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

protected void paintPageError(Graphics2D grx) {
    AffineTransform origTransform = grx.getTransform();

    AffineTransform transform = new AffineTransform();
    transform.translate(1, 1);
    transform.scale(realZoom, realZoom);
    grx.transform(transform);//w w  w .j a  v a  2 s .c  om

    try {
        drawPageError(grx);
    } finally {
        grx.setTransform(origTransform);
    }
}

From source file:org.apache.fop.render.intermediate.IFRenderer.java

/** {@inheritDoc} */
protected void renderBlockViewport(BlockViewport bv, List children) {
    //Essentially the same code as in the super class but optimized for the IF

    //This is the content-rect
    Dimension dim = new Dimension(bv.getIPD(), bv.getBPD());
    viewportDimensionStack.push(dim);/*  w  w  w. jav  a 2  s .  c  o  m*/

    // save positions
    int saveIP = currentIPPosition;
    int saveBP = currentBPPosition;

    CTM ctm = bv.getCTM();
    int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
    int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();

    if (bv.getPositioning() == Block.ABSOLUTE || bv.getPositioning() == Block.FIXED) {

        //For FIXED, we need to break out of the current viewports to the
        //one established by the page. We save the state stack for restoration
        //after the block-container has been painted. See below.
        List breakOutList = null;
        if (bv.getPositioning() == Block.FIXED) {
            breakOutList = breakOutOfStateStack();
        }

        AffineTransform positionTransform = new AffineTransform();
        positionTransform.translate(bv.getXOffset(), bv.getYOffset());

        //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
        positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);

        //Free transformation for the block-container viewport
        String transf;
        transf = bv.getForeignAttributeValue(FOX_TRANSFORM);
        if (transf != null) {
            AffineTransform freeTransform = AWTTransformProducer.createAffineTransform(transf);
            positionTransform.concatenate(freeTransform);
        }

        saveGraphicsState();
        //Viewport position
        concatenateTransformationMatrixMpt(positionTransform, false);

        //Background and borders
        float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd());
        float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter());
        drawBackAndBorders(bv, 0, 0, (dim.width + bpwidth) / 1000f, (dim.height + bpheight) / 1000f);

        //Shift to content rectangle after border painting
        AffineTransform contentRectTransform = new AffineTransform();
        contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
        concatenateTransformationMatrixMpt(contentRectTransform, false);

        //saveGraphicsState();
        //Set up coordinate system for content rectangle
        AffineTransform contentTransform = ctm.toAffineTransform();
        //concatenateTransformationMatrixMpt(contentTransform);
        startViewport(contentTransform, bv.getClipRectangle());

        currentIPPosition = 0;
        currentBPPosition = 0;
        renderBlocks(bv, children);

        endViewport();
        //restoreGraphicsState();
        restoreGraphicsState();

        if (breakOutList != null) {
            restoreStateStackAfterBreakOut(breakOutList);
        }

        currentIPPosition = saveIP;
        currentBPPosition = saveBP;
    } else {

        currentBPPosition += bv.getSpaceBefore();

        //borders and background in the old coordinate system
        handleBlockTraits(bv);

        //Advance to start of content area
        currentIPPosition += bv.getStartIndent();

        CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
        ctm = tempctm.multiply(ctm);

        //Now adjust for border/padding
        currentBPPosition += borderPaddingBefore;

        startVParea(ctm, bv.getClipRectangle());
        currentIPPosition = 0;
        currentBPPosition = 0;
        renderBlocks(bv, children);
        endVParea();

        currentIPPosition = saveIP;
        currentBPPosition = saveBP;

        currentBPPosition += bv.getAllocBPD();
    }
    viewportDimensionStack.pop();
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/**
 * {@inheritDoc}//from w w w  .ja v a 2  s . c  o m
 */
protected void renderBlockViewport(BlockViewport bv, List children) {
    // clip and position viewport if necessary

    // save positions
    int saveIP = currentIPPosition;
    int saveBP = currentBPPosition;

    CTM ctm = bv.getCTM();
    int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
    int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
    //This is the content-rect
    float width = bv.getIPD() / 1000f;
    float height = bv.getBPD() / 1000f;

    if (bv.getPositioning() == Block.ABSOLUTE || bv.getPositioning() == Block.FIXED) {

        //For FIXED, we need to break out of the current viewports to the
        //one established by the page. We save the state stack for restoration
        //after the block-container has been painted. See below.
        List breakOutList = null;
        if (bv.getPositioning() == Block.FIXED) {
            breakOutList = breakOutOfStateStack();
        }

        AffineTransform positionTransform = new AffineTransform();
        positionTransform.translate(bv.getXOffset(), bv.getYOffset());

        //"left/"top" (bv.getX/YOffset()) specify the position of the content rectangle
        positionTransform.translate(-borderPaddingStart, -borderPaddingBefore);

        saveGraphicsState();
        //Viewport position
        concatenateTransformationMatrix(UnitConv.mptToPt(positionTransform));

        //Background and borders
        float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
        float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
        drawBackAndBorders(bv, 0, 0, width + bpwidth, height + bpheight);

        //Shift to content rectangle after border painting
        AffineTransform contentRectTransform = new AffineTransform();
        contentRectTransform.translate(borderPaddingStart, borderPaddingBefore);
        concatenateTransformationMatrix(UnitConv.mptToPt(contentRectTransform));

        //Clipping
        if (bv.getClip()) {
            clipRect(0f, 0f, width, height);
        }

        saveGraphicsState();
        //Set up coordinate system for content rectangle
        AffineTransform contentTransform = ctm.toAffineTransform();
        concatenateTransformationMatrix(UnitConv.mptToPt(contentTransform));

        currentIPPosition = 0;
        currentBPPosition = 0;
        renderBlocks(bv, children);

        restoreGraphicsState();
        restoreGraphicsState();

        if (breakOutList != null) {
            restoreStateStackAfterBreakOut(breakOutList);
        }

        currentIPPosition = saveIP;
        currentBPPosition = saveBP;
    } else {

        currentBPPosition += bv.getSpaceBefore();

        //borders and background in the old coordinate system
        handleBlockTraits(bv);

        //Advance to start of content area
        currentIPPosition += bv.getStartIndent();

        CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
        ctm = tempctm.multiply(ctm);

        //Now adjust for border/padding
        currentBPPosition += borderPaddingBefore;

        Rectangle2D clippingRect = null;
        if (bv.getClip()) {
            clippingRect = new Rectangle(currentIPPosition, currentBPPosition, bv.getIPD(), bv.getBPD());
        }

        startVParea(ctm, clippingRect);
        currentIPPosition = 0;
        currentBPPosition = 0;
        renderBlocks(bv, children);
        endVParea();

        currentIPPosition = saveIP;
        currentBPPosition = saveBP;

        currentBPPosition += (bv.getAllocBPD());
    }
    //currentFontName = saveFontName;
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/** {@inheritDoc} */
protected void renderReferenceArea(Block block) {
    //TODO This is the same code as in AbstractPathOrientedRenderer
    //So there's some optimization potential but not otherwise PCLRenderer is a little
    //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer
    //between PrintRenderer and AbstractPathOrientedRenderer is necessary.

    // save position and offset
    int saveIP = currentIPPosition;
    int saveBP = currentBPPosition;

    //Establish a new coordinate system
    AffineTransform at = new AffineTransform();
    at.translate(currentIPPosition, currentBPPosition);
    at.translate(block.getXOffset(), block.getYOffset());
    at.translate(0, block.getSpaceBefore());

    if (!at.isIdentity()) {
        saveGraphicsState();//from  ww  w  .j  ava2 s.  com
        concatenateTransformationMatrix(UnitConv.mptToPt(at));
    }

    currentIPPosition = 0;
    currentBPPosition = 0;
    handleBlockTraits(block);

    List children = block.getChildAreas();
    if (children != null) {
        renderBlocks(block, children);
    }

    if (!at.isIdentity()) {
        restoreGraphicsState();
    }

    // stacked and relative blocks effect stacking
    currentIPPosition = saveIP;
    currentBPPosition = saveBP;
}

From source file:org.apache.fop.render.pcl.PCLRenderer.java

/** {@inheritDoc} */
protected void renderFlow(NormalFlow flow) {
    //TODO This is the same code as in AbstractPathOrientedRenderer
    //So there's some optimization potential but not otherwise PCLRenderer is a little
    //difficult to derive from AbstractPathOrientedRenderer. Maybe an additional layer
    //between PrintRenderer and AbstractPathOrientedRenderer is necessary.

    // save position and offset
    int saveIP = currentIPPosition;
    int saveBP = currentBPPosition;

    //Establish a new coordinate system
    AffineTransform at = new AffineTransform();
    at.translate(currentIPPosition, currentBPPosition);

    if (!at.isIdentity()) {
        saveGraphicsState();//from w  ww  .  j a  va 2s.c  om
        concatenateTransformationMatrix(UnitConv.mptToPt(at));
    }

    currentIPPosition = 0;
    currentBPPosition = 0;
    super.renderFlow(flow);

    if (!at.isIdentity()) {
        restoreGraphicsState();
    }

    // stacked and relative blocks effect stacking
    currentIPPosition = saveIP;
    currentBPPosition = saveBP;
}

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   ww w .  ja v  a2 s.c  om*/
 * @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");
}

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

private void rotate(int rotation, PDRectangle viewBox, AffineTransform atdoc) {
    float x = viewBox.getWidth() + viewBox.getLowerLeftX();
    float y = viewBox.getHeight() + viewBox.getLowerLeftY();
    switch (rotation) {
    case 90:/*from w ww .jav a 2 s. co  m*/
        atdoc.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        atdoc.translate(0, viewBox.getWidth());
        atdoc.rotate(-Math.PI / 2.0);
        atdoc.scale(viewBox.getWidth() / viewBox.getHeight(), viewBox.getHeight() / viewBox.getWidth());
        break;
    case 180:
        atdoc.translate(x, y);
        atdoc.rotate(-Math.PI);
        atdoc.translate(-viewBox.getLowerLeftX(), -viewBox.getLowerLeftY());
        break;
    case 270:
        atdoc.translate(viewBox.getLowerLeftX(), y);
        atdoc.rotate(Math.toRadians(270 + 180));
        atdoc.translate(-x, -y);
        break;
    default:
        //no additional transformations necessary
        break;
    }
}