You are viewing a plain text version of this content. The canonical link for it is here.
Posted to fop-commits@xmlgraphics.apache.org by ac...@apache.org on 2007/12/12 13:24:16 UTC

svn commit: r603590 [2/5] - in /xmlgraphics/fop/trunk: lib/ src/java/org/apache/fop/render/afp/ src/java/org/apache/fop/render/afp/modca/ src/java/org/apache/fop/render/afp/modca/goca/ src/java/org/apache/fop/render/ps/

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRenderer.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRenderer.java?rev=603590&r1=603589&r2=603590&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRenderer.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRenderer.java Wed Dec 12 04:24:10 2007
@@ -124,23 +124,28 @@
  * handle all types of inline area, text, image etc and draws various lines and
  * rectangles.
  * </p>
- *
- * Note: There are specific extensions that have been added to the
- * FO. They are specific to their location within the FO and have to be
- * processed accordingly (ie. at the start or end of the page).
- *
+ * 
+ * Note: There are specific extensions that have been added to the FO. They are
+ * specific to their location within the FO and have to be processed accordingly
+ * (ie. at the start or end of the page).
+ * 
  */
 public class AFPRenderer extends AbstractPathOrientedRenderer {
 
     /**
-     * The default afp renderer output resolution
+     * 2400 dpi renderer resolution
      */
-    private static final int DEFAULT_DPI_RESOLUTION = 240;
+    protected static final int DPI_240_RESOLUTION = 240;
+
+    /**
+     * 14400 dpi renderer resolution
+     */
+    protected static final int DPI_1440_RESOLUTION = 1440;
 
     /**
      * The afp factor for calculating resolutions (e.g. 72000/240 = 300)
      */
-    private static final int DPI_CONVERSION_FACTOR = 72000;
+    protected static final int DPI_CONVERSION_FACTOR = 72000;
 
     /**
      * The afp data stream object responsible for generating afp data
@@ -148,46 +153,11 @@
     private AFPDataStream afpDataStream = null;
 
     /**
-     * The map of afp root extensions
-     */
-    // UNUSED
-    // private HashMap rootExtensionMap = null;
-    /**
      * The map of page segments
      */
-    private HashMap pageSegmentsMap = null;
-
-    /**
-     * The fonts on the current page
-     */
-    private HashMap currentPageFonts = null;
-
-    /**
-     * The current color object
-     */
-    private Color currentColor = null;
-
-    /**
-     * The page font number counter, used to determine the next font reference
-     */
-    private int pageFontCounter = 0;
-
-    /**
-     * The current font family
-     */
-    // UNUSED
-    // private String currentFontFamily = "";
-    /**
-     * The current font size
-     */
-    private int currentFontSize = 0;
+    private Map pageSegmentsMap = null;
 
     /**
-     * The Options to be set on the AFPRenderer
-     */
-    // UNUSED
-    // private Map afpOptions = null;
-    /**
      * The page width
      */
     private int pageWidth = 0;
@@ -198,11 +168,6 @@
     private int pageHeight = 0;
 
     /**
-     * The current page sequence id
-     */
-    // UNUSED
-    // private String pageSequenceId = null;
-    /**
      * The portrait rotation
      */
     private int portraitRotation = 0;
@@ -213,21 +178,6 @@
     private int landscapeRotation = 270;
 
     /**
-     * The line cache, avoids drawing duplicate lines in tables.
-     */
-    // UNUSED
-    // private HashSet lineCache = null;
-    /**
-     * The current x position for line drawing
-     */
-    // UNUSED
-    // private float x;
-    /**
-     * The current y position for line drawing
-     */
-    // UNUSED
-    // private float y;
-    /**
      * The map of saved incomplete pages
      */
     private Map pages = null;
@@ -245,7 +195,10 @@
     /**
      * The output resolution
      */
-    private int resolution = DEFAULT_DPI_RESOLUTION;
+    private int resolution = DPI_240_RESOLUTION;
+
+    /** drawing state */
+    protected AFPState currentState = null;
 
     /**
      * Constructor for AFPRenderer.
@@ -256,20 +209,22 @@
 
     /**
      * Set up the font info
-     *
-     * @param inFontInfo  font info to set up
+     * 
+     * @param inFontInfo
+     *            font info to set up
      */
     public void setupFontInfo(FontInfo inFontInfo) {
         this.fontInfo = inFontInfo;
         int num = 1;
         if (this.fontList != null && this.fontList.size() > 0) {
             for (Iterator it = this.fontList.iterator(); it.hasNext();) {
-                AFPFontInfo afi = (AFPFontInfo)it.next();
-                AFPFont bf = (AFPFont)afi.getAFPFont();
-                for (Iterator it2 = afi.getFontTriplets().iterator(); it2.hasNext();) {
-                    FontTriplet ft = (FontTriplet)it2.next();
-                    this.fontInfo.addFontProperties("F" + num, ft.getName()
-                                                    , ft.getStyle(), ft.getWeight());
+                AFPFontInfo afi = (AFPFontInfo) it.next();
+                AFPFont bf = (AFPFont) afi.getAFPFont();
+                for (Iterator it2 = afi.getFontTriplets().iterator(); it2
+                        .hasNext();) {
+                    FontTriplet ft = (FontTriplet) it2.next();
+                    this.fontInfo.addFontProperties("F" + num, ft.getName(), ft
+                            .getStyle(), ft.getWeight());
                     this.fontInfo.addMetrics("F" + num, bf);
                     num++;
                 }
@@ -278,33 +233,36 @@
             log.warn("No AFP fonts configured - using default setup");
         }
         if (this.fontInfo.fontLookup("sans-serif", "normal", 400) == null) {
-            CharacterSet cs  = new FopCharacterSet("T1V10500", "Cp500", "CZH200  ",
-                    1, new Helvetica());
+            CharacterSet cs = new FopCharacterSet("T1V10500", "Cp500",
+                    "CZH200  ", 1, new Helvetica());
             AFPFont bf = new OutlineFont("Helvetica", cs);
-            this.fontInfo.addFontProperties("F" + num, "sans-serif", "normal", 400);
+            this.fontInfo.addFontProperties("F" + num, "sans-serif", "normal",
+                    400);
             this.fontInfo.addMetrics("F" + num, bf);
             num++;
         }
         if (this.fontInfo.fontLookup("serif", "normal", 400) == null) {
-            CharacterSet cs  = new FopCharacterSet("T1V10500", "Cp500", "CZN200  ",
-                    1, new TimesRoman());
+            CharacterSet cs = new FopCharacterSet("T1V10500", "Cp500",
+                    "CZN200  ", 1, new TimesRoman());
             AFPFont bf = new OutlineFont("Helvetica", cs);
             this.fontInfo.addFontProperties("F" + num, "serif", "normal", 400);
             this.fontInfo.addMetrics("F" + num, bf);
             num++;
         }
         if (this.fontInfo.fontLookup("monospace", "normal", 400) == null) {
-            CharacterSet cs  = new FopCharacterSet("T1V10500", "Cp500", "CZ4200  ",
-                    1, new Courier());
+            CharacterSet cs = new FopCharacterSet("T1V10500", "Cp500",
+                    "CZ4200  ", 1, new Courier());
             AFPFont bf = new OutlineFont("Helvetica", cs);
-            this.fontInfo.addFontProperties("F" + num, "monospace", "normal", 400);
+            this.fontInfo.addFontProperties("F" + num, "monospace", "normal",
+                    400);
             this.fontInfo.addMetrics("F" + num, bf);
             num++;
         }
         if (this.fontInfo.fontLookup("any", "normal", 400) == null) {
-            FontTriplet ft = this.fontInfo.fontLookup("sans-serif", "normal", 400);
-            this.fontInfo.addFontProperties(
-                    this.fontInfo.getInternalFontKey(ft), "any", "normal", 400);
+            FontTriplet ft = this.fontInfo.fontLookup("sans-serif", "normal",
+                    400);
+            this.fontInfo.addFontProperties(this.fontInfo
+                    .getInternalFontKey(ft), "any", "normal", 400);
         }
     }
 
@@ -319,57 +277,49 @@
      * {@inheritDoc}
      */
     public void startRenderer(OutputStream outputStream) throws IOException {
-        currentPageFonts = new HashMap();
-        currentColor = new Color(255, 255, 255);
-        afpDataStream = new AFPDataStream();
-        afpDataStream.setPortraitRotation(portraitRotation);
-        afpDataStream.setLandscapeRotation(landscapeRotation);
-        afpDataStream.startDocument(outputStream);
+        this.currentState = new AFPState();
+        this.afpDataStream = new AFPDataStream();
+        this.afpDataStream.setPortraitRotation(portraitRotation);
+        this.afpDataStream.setLandscapeRotation(landscapeRotation);
+        this.afpDataStream.startDocument(outputStream);
     }
 
     /**
      * {@inheritDoc}
      */
     public void stopRenderer() throws IOException {
-        afpDataStream.endDocument();
+        this.afpDataStream.endDocument();
     }
 
     /**
      * {@inheritDoc}
      */
     public boolean supportsOutOfOrder() {
-        //return false;
+        // return false;
         return true;
     }
 
     /**
-     * Prepare a page for rendering. This is called if the renderer supports
-     * out of order rendering. The renderer should prepare the page so that a
-     * page further on in the set of pages can be rendered. The body of the
-     * page should not be rendered. The page will be rendered at a later time
-     * by the call to render page.
-     *
+     * Prepare a page for rendering. This is called if the renderer supports out
+     * of order rendering. The renderer should prepare the page so that a page
+     * further on in the set of pages can be rendered. The body of the page
+     * should not be rendered. The page will be rendered at a later time by the
+     * call to render page.
+     * 
      * {@inheritDoc}
      */
     public void preparePage(PageViewport page) {
-        // initializeRootExtensions(page);
 
-        // this.currentFontFamily = "";
-        this.currentFontSize = 0;
-        this.pageFontCounter = 0;
-        this.currentPageFonts.clear();
-        // this.lineCache = new HashSet();
+        this.currentState.reset();
 
         Rectangle2D bounds = page.getViewArea();
 
         this.pageWidth = mpts2units(bounds.getWidth());
         this.pageHeight = mpts2units(bounds.getHeight());
 
-        // renderPageGroupExtensions(page);
-
         final int pageRotation = 0;
         this.afpDataStream.startPage(pageWidth, pageHeight, pageRotation,
-                getResolution(), getResolution());
+                this.resolution, this.resolution);
 
         renderPageObjectExtensions(page);
 
@@ -407,12 +357,15 @@
     }
 
     /**
-     * Renders a region viewport. <p>
-     *
-     * The region may clip the area and it establishes a position from where
-     * the region is placed.</p>
-     *
-     * @param port  The region viewport to be rendered
+     * Renders a region viewport.
+     * <p>
+     * 
+     * The region may clip the area and it establishes a position from where the
+     * region is placed.
+     * </p>
+     * 
+     * @param port
+     *            The region viewport to be rendered
      */
     public void renderRegionViewport(RegionViewport port) {
         if (port != null) {
@@ -427,11 +380,9 @@
             handleRegionTraits(port);
 
             /*
-            _afpDataStream.startOverlay(mpts2units(view.getX())
-                , mpts2units(view.getY())
-                , mpts2units(view.getWidth())
-                , mpts2units(view.getHeight())
-                , rotation);
+             * _afpDataStream.startOverlay(mpts2units(view.getX()) ,
+             * mpts2units(view.getY()) , mpts2units(view.getWidth()) ,
+             * mpts2units(view.getHeight()) , rotation);
              */
 
             pushViewPortPos(new ViewPortPos(view, regionReference.getCTM()));
@@ -442,7 +393,7 @@
                 renderRegion(regionReference);
             }
             /*
-            _afpDataStream.endOverlay();
+             * _afpDataStream.endOverlay();
              */
             popViewPortPos();
         }
@@ -457,18 +408,17 @@
         // save positions
         int saveIP = currentIPPosition;
         int saveBP = currentBPPosition;
-        //String saveFontName = currentFontName;
+        // String saveFontName = currentFontName;
 
         CTM ctm = bv.getCTM();
         int borderPaddingStart = bv.getBorderAndPaddingWidthStart();
         int borderPaddingBefore = bv.getBorderAndPaddingWidthBefore();
         float x, y;
-        x = (float)(bv.getXOffset() + containingIPPosition) / 1000f;
-        y = (float)(bv.getYOffset() + containingBPPosition) / 1000f;
-        //This is the content-rect
-        float width = (float)bv.getIPD() / 1000f;
-        float height = (float)bv.getBPD() / 1000f;
-
+        x = (float) (bv.getXOffset() + containingIPPosition) / 1000f;
+        y = (float) (bv.getYOffset() + containingBPPosition) / 1000f;
+        // This is the content-rect
+        float width = (float) bv.getIPD() / 1000f;
+        float height = (float) bv.getBPD() / 1000f;
 
         if (bv.getPositioning() == Block.ABSOLUTE
                 || bv.getPositioning() == Block.FIXED) {
@@ -476,9 +426,10 @@
             currentIPPosition = bv.getXOffset();
             currentBPPosition = bv.getYOffset();
 
-            //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.
+            // 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();
@@ -487,19 +438,21 @@
             CTM tempctm = new CTM(containingIPPosition, containingBPPosition);
             ctm = tempctm.multiply(ctm);
 
-            //Adjust for spaces (from margin or indirectly by start-indent etc.
+            // Adjust for spaces (from margin or indirectly by start-indent etc.
             x += bv.getSpaceStart() / 1000f;
             currentIPPosition += bv.getSpaceStart();
 
             y += bv.getSpaceBefore() / 1000f;
             currentBPPosition += bv.getSpaceBefore();
 
-            float bpwidth = (borderPaddingStart + bv.getBorderAndPaddingWidthEnd()) / 1000f;
-            float bpheight = (borderPaddingBefore + bv.getBorderAndPaddingWidthAfter()) / 1000f;
+            float bpwidth = (borderPaddingStart + bv
+                    .getBorderAndPaddingWidthEnd()) / 1000f;
+            float bpheight = (borderPaddingBefore + bv
+                    .getBorderAndPaddingWidthAfter()) / 1000f;
 
             drawBackAndBorders(bv, x, y, width + bpwidth, height + bpheight);
 
-            //Now adjust for border/padding
+            // Now adjust for border/padding
             currentIPPosition += borderPaddingStart;
             currentBPPosition += borderPaddingBefore;
 
@@ -512,7 +465,7 @@
             currentIPPosition = 0;
             currentBPPosition = 0;
             renderBlocks(bv, children);
-            //endVParea();
+            // endVParea();
             popViewPortPos();
 
             if (breakOutList != null) {
@@ -525,35 +478,35 @@
 
             currentBPPosition += bv.getSpaceBefore();
 
-            //borders and background in the old coordinate system
+            // borders and background in the old coordinate system
             handleBlockTraits(bv);
 
-            //Advance to start of content area
+            // Advance to start of content area
             currentIPPosition += bv.getStartIndent();
 
             CTM tempctm = new CTM(containingIPPosition, currentBPPosition);
             ctm = tempctm.multiply(ctm);
 
-            //Now adjust for border/padding
+            // Now adjust for border/padding
             currentBPPosition += borderPaddingBefore;
 
             Rectangle2D clippingRect = null;
             clippingRect = new Rectangle(currentIPPosition, currentBPPosition,
                     bv.getIPD(), bv.getBPD());
 
-            //startVParea(ctm, clippingRect);
+            // startVParea(ctm, clippingRect);
             pushViewPortPos(new ViewPortPos(clippingRect, ctm));
 
             currentIPPosition = 0;
             currentBPPosition = 0;
             renderBlocks(bv, children);
-            //endVParea();
+            // endVParea();
             popViewPortPos();
 
             currentIPPosition = saveIP;
             currentBPPosition = saveBP;
 
-            currentBPPosition += (int)(bv.getAllocBPD());
+            currentBPPosition += (int) (bv.getAllocBPD());
         }
         // currentFontName = saveFontName;
     }
@@ -563,13 +516,7 @@
      */
     public void renderPage(PageViewport pageViewport) {
 
-        // initializeRootExtensions(page);
-
-        // this.currentFontFamily = "";
-        this.currentFontSize = 0;
-        this.pageFontCounter = 0;
-        this.currentPageFonts.clear();
-        // this.lineCache = new HashSet();
+        currentState.reset();
 
         Rectangle2D bounds = pageViewport.getViewArea();
 
@@ -578,14 +525,14 @@
 
         if (pages != null && pages.containsKey(pageViewport)) {
 
-            this.afpDataStream.restorePage((PageObject) pages.remove(pageViewport));
+            this.afpDataStream.restorePage((PageObject) pages
+                    .remove(pageViewport));
 
         } else {
-            // renderPageGroupExtensions(page);
 
             final int pageRotation = 0;
             this.afpDataStream.startPage(pageWidth, pageHeight, pageRotation,
-                    getResolution(), getResolution());
+                    this.resolution, this.resolution);
 
             renderPageObjectExtensions(pageViewport);
 
@@ -595,16 +542,7 @@
 
         renderPageAreas(pageViewport.getPage());
 
-        Iterator i = currentPageFonts.values().iterator();
-        while (i.hasNext()) {
-            AFPFontAttributes afpFontAttributes = (AFPFontAttributes) i.next();
-
-            afpDataStream.createFont(
-                (byte)afpFontAttributes.getFontReference(),
-                afpFontAttributes.getFont(),
-                afpFontAttributes.getPointSize());
-
-        }
+        this.afpDataStream.addFontsToCurrentPage(currentState.getPageFonts());
 
         try {
             afpDataStream.endPage();
@@ -656,22 +594,12 @@
      */
     public void fillRect(float x, float y, float width, float height) {
         /*
-        afpDataStream.createShading(
-            pts2units(x),
-            pts2units(y),
-            pts2units(width),
-            pts2units(height),
-            currentColor.getRed(),
-            currentColor.getGreen(),
-            currentColor.getBlue());
+         * afpDataStream.createShading( pts2units(x), pts2units(y),
+         * pts2units(width), pts2units(height), currentColor.getRed(),
+         * currentColor.getGreen(), currentColor.getBlue());
          */
-        afpDataStream.createLine(
-            pts2units(x),
-            pts2units(y),
-            pts2units(x + width),
-            pts2units(y),
-            pts2units(height),
-            currentColor);
+        afpDataStream.createLine(pts2units(x), pts2units(y), pts2units(x
+                + width), pts2units(y), pts2units(height), currentState.getColor());
     }
 
     /**
@@ -686,195 +614,124 @@
             return;
         }
         switch (style) {
-            case Constants.EN_DOUBLE:
-                if (horz) {
-                    float h3 = h / 3;
-                    float ym1 = y1;
-                    float ym2 = ym1 + h3 + h3;
-                    afpDataStream.createLine(
-                        pts2units(x1),
-                        pts2units(ym1),
-                        pts2units(x2),
-                        pts2units(ym1),
-                        pts2units(h3),
-                        col
-                    );
-                    afpDataStream.createLine(
-                        pts2units(x1),
-                        pts2units(ym2),
-                        pts2units(x2),
-                        pts2units(ym2),
-                        pts2units(h3),
-                        col
-                    );
-                } else {
-                    float w3 = w / 3;
-                    float xm1 = x1;
-                    float xm2 = xm1 + w3 + w3;
-                    afpDataStream.createLine(
-                        pts2units(xm1),
-                        pts2units(y1),
-                        pts2units(xm1),
-                        pts2units(y2),
-                        pts2units(w3),
-                        col
-                    );
-                    afpDataStream.createLine(
-                        pts2units(xm2),
-                        pts2units(y1),
-                        pts2units(xm2),
-                        pts2units(y2),
-                        pts2units(w3),
-                        col
-                    );
+        case Constants.EN_DOUBLE:
+            if (horz) {
+                float h3 = h / 3;
+                float ym1 = y1;
+                float ym2 = ym1 + h3 + h3;
+                afpDataStream.createLine(pts2units(x1), pts2units(ym1),
+                        pts2units(x2), pts2units(ym1), pts2units(h3), col);
+                afpDataStream.createLine(pts2units(x1), pts2units(ym2),
+                        pts2units(x2), pts2units(ym2), pts2units(h3), col);
+            } else {
+                float w3 = w / 3;
+                float xm1 = x1;
+                float xm2 = xm1 + w3 + w3;
+                afpDataStream.createLine(pts2units(xm1), pts2units(y1),
+                        pts2units(xm1), pts2units(y2), pts2units(w3), col);
+                afpDataStream.createLine(pts2units(xm2), pts2units(y1),
+                        pts2units(xm2), pts2units(y2), pts2units(w3), col);
+            }
+            break;
+        case Constants.EN_DASHED:
+            if (horz) {
+                float w2 = 2 * h;
+                while (x1 + w2 < x2) {
+                    afpDataStream.createLine(pts2units(x1), pts2units(y1),
+                            pts2units(x1 + w2), pts2units(y1), pts2units(h),
+                            col);
+                    x1 += 2 * w2;
                 }
-                break;
-            case Constants.EN_DASHED:
-                if (horz) {
-                    float w2 = 2 * h;
-                    while (x1 + w2 < x2) {
-                        afpDataStream.createLine(
-                            pts2units(x1),
-                            pts2units(y1),
-                            pts2units(x1 + w2),
-                            pts2units(y1),
-                            pts2units(h),
-                            col
-                        );
-                        x1 += 2 * w2;
-                    }
-                } else {
-                    float h2 = 2 * w;
-                    while (y1 + h2 < y2) {
-                        afpDataStream.createLine(
-                            pts2units(x1),
-                            pts2units(y1),
-                            pts2units(x1),
-                            pts2units(y1 + h2),
-                            pts2units(w),
-                            col
-                        );
-                        y1 += 2 * h2;
-                    }
+            } else {
+                float h2 = 2 * w;
+                while (y1 + h2 < y2) {
+                    afpDataStream.createLine(pts2units(x1), pts2units(y1),
+                            pts2units(x1), pts2units(y1 + h2), pts2units(w),
+                            col);
+                    y1 += 2 * h2;
                 }
-                break;
-            case Constants.EN_DOTTED:
-                if (horz) {
-                    while (x1 + h < x2) {
-                        afpDataStream.createLine(
-                            pts2units(x1),
-                            pts2units(y1),
-                            pts2units(x1 + h),
-                            pts2units(y1),
-                            pts2units(h),
-                            col
-                        );
-                        x1 += 2 * h;
-                    }
-                } else {
-                    while (y1 + w < y2) {
-                        afpDataStream.createLine(
-                            pts2units(x1),
-                            pts2units(y1),
-                            pts2units(x1),
-                            pts2units(y1 + w),
-                            pts2units(w),
-                            col
-                        );
-                        y1 += 2 * w;
-                    }
+            }
+            break;
+        case Constants.EN_DOTTED:
+            if (horz) {
+                while (x1 + h < x2) {
+                    afpDataStream
+                            .createLine(pts2units(x1), pts2units(y1),
+                                    pts2units(x1 + h), pts2units(y1),
+                                    pts2units(h), col);
+                    x1 += 2 * h;
                 }
-                break;
-            case Constants.EN_GROOVE:
-            case Constants.EN_RIDGE:
-            {
-                float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
-                if (horz) {
-                    Color uppercol = lightenColor(col, -colFactor);
-                    Color lowercol = lightenColor(col, colFactor);
-                    float h3 = h / 3;
-                    float ym1 = y1;
-                    afpDataStream.createLine(
-                        pts2units(x1),
-                        pts2units(ym1),
-                        pts2units(x2),
-                        pts2units(ym1),
-                        pts2units(h3),
-                        uppercol
-                    );
-                    afpDataStream.createLine(
-                        pts2units(x1),
-                        pts2units(ym1 + h3),
-                        pts2units(x2),
-                        pts2units(ym1 + h3),
-                        pts2units(h3),
-                        col
-                    );
-                    afpDataStream.createLine(
-                        pts2units(x1),
-                        pts2units(ym1 + h3 + h3),
-                        pts2units(x2),
-                        pts2units(ym1 + h3 + h3),
-                        pts2units(h3),
-                        lowercol
-                    );
-                } else {
-                    Color leftcol = lightenColor(col, -colFactor);
-                    Color rightcol = lightenColor(col, colFactor);
-                    float w3 = w / 3;
-                    float xm1 = x1 + (w3 / 2);
-                    afpDataStream.createLine(
-                        pts2units(xm1),
-                        pts2units(y1),
-                        pts2units(xm1),
-                        pts2units(y2),
-                        pts2units(w3),
-                        leftcol
-                    );
-                    afpDataStream.createLine(
-                        pts2units(xm1 + w3),
-                        pts2units(y1),
-                        pts2units(xm1 + w3),
-                        pts2units(y2),
-                        pts2units(w3),
-                        col
-                    );
-                    afpDataStream.createLine(
-                        pts2units(xm1 + w3 + w3),
-                        pts2units(y1),
-                        pts2units(xm1 + w3 + w3),
-                        pts2units(y2),
-                        pts2units(w3),
-                        rightcol
-                    );
+            } else {
+                while (y1 + w < y2) {
+                    afpDataStream
+                            .createLine(pts2units(x1), pts2units(y1),
+                                    pts2units(x1), pts2units(y1 + w),
+                                    pts2units(w), col);
+                    y1 += 2 * w;
                 }
-                break;
             }
-            case Constants.EN_HIDDEN:
-                break;
-            case Constants.EN_INSET:
-            case Constants.EN_OUTSET:
-            default:
-                afpDataStream.createLine(
-                    pts2units(x1),
-                    pts2units(y1),
-                    pts2units(horz ? x2 : x1),
-                    pts2units(horz ? y1 : y2),
-                    pts2units(Math.abs(horz ? (y2 - y1) : (x2 - x1))),
-                    col
-                );
+            break;
+        case Constants.EN_GROOVE:
+        case Constants.EN_RIDGE: {
+            float colFactor = (style == EN_GROOVE ? 0.4f : -0.4f);
+            if (horz) {
+                Color uppercol = lightenColor(col, -colFactor);
+                Color lowercol = lightenColor(col, colFactor);
+                float h3 = h / 3;
+                float ym1 = y1;
+                afpDataStream.createLine(pts2units(x1), pts2units(ym1),
+                        pts2units(x2), pts2units(ym1), pts2units(h3), uppercol);
+                afpDataStream.createLine(pts2units(x1), pts2units(ym1 + h3),
+                        pts2units(x2), pts2units(ym1 + h3), pts2units(h3), col);
+                afpDataStream.createLine(pts2units(x1),
+                        pts2units(ym1 + h3 + h3), pts2units(x2), pts2units(ym1
+                                + h3 + h3), pts2units(h3), lowercol);
+            } else {
+                Color leftcol = lightenColor(col, -colFactor);
+                Color rightcol = lightenColor(col, colFactor);
+                float w3 = w / 3;
+                float xm1 = x1 + (w3 / 2);
+                afpDataStream.createLine(pts2units(xm1), pts2units(y1),
+                        pts2units(xm1), pts2units(y2), pts2units(w3), leftcol);
+                afpDataStream.createLine(pts2units(xm1 + w3), pts2units(y1),
+                        pts2units(xm1 + w3), pts2units(y2), pts2units(w3), col);
+                afpDataStream.createLine(pts2units(xm1 + w3 + w3),
+                        pts2units(y1), pts2units(xm1 + w3 + w3), pts2units(y2),
+                        pts2units(w3), rightcol);
+            }
+            break;
+        }
+        case Constants.EN_HIDDEN:
+            break;
+        case Constants.EN_INSET:
+        case Constants.EN_OUTSET:
+        default:
+            afpDataStream.createLine(pts2units(x1), pts2units(y1),
+                    pts2units(horz ? x2 : x1), pts2units(horz ? y1 : y2),
+                    pts2units(Math.abs(horz ? (y2 - y1) : (x2 - x1))), col);
         }
     }
 
     /**
      * {@inheritDoc}
      */
-    protected RendererContext createRendererContext(int x, int y, int width, int height,
-            Map foreignAttributes) {
+    protected RendererContext createRendererContext(int x, int y, int width,
+            int height, Map foreignAttributes) {
         RendererContext context;
-        context = super.createRendererContext(x, y, width, height, foreignAttributes);
+        context = super.createRendererContext(x, y, width, height,
+                foreignAttributes);
         context.setProperty(AFPRendererContextConstants.AFP_GRAYSCALE,
                 new Boolean(!this.colorImages));
+        context.setProperty(AFPRendererContextConstants.AFP_FONT_INFO,
+                this.fontInfo);
+        context.setProperty(AFPRendererContextConstants.AFP_RESOLUTION,
+                new Integer(this.resolution));
+        context.setProperty(AFPRendererContextConstants.AFP_BITS_PER_PIXEL,
+                new Integer(this.bitsPerPixel));
+        context.setProperty(AFPRendererContextConstants.AFP_DATASTREAM,
+                this.afpDataStream);
+        context.setProperty(AFPRendererContextConstants.AFP_STATE,
+                this.currentState);
         return context;
     }
 
@@ -911,71 +768,65 @@
                 renderDocument(doc, ns, pos, foreignAttributes);
             } else if (MimeConstants.MIME_EPS.equals(mime)) {
                 log.warn("EPS images are not supported by this renderer");
-            /*
-            } else if (MimeConstants.MIME_JPEG.equals(mime)) {
-                if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
-                    return;
-                }
-                fact.releaseImage(url, userAgent);
-
-                int x = mpts2units(pos.getX() + currentIPPosition);
-                int y = mpts2units(pos.getY() + currentBPPosition);
-                int w = mpts2units(pos.getWidth());
-                int h = mpts2units(pos.getHeight());
-                ImageObject io = _afpDataStream.getImageObject();
-                io.setImageViewport(x, y, w, h);
-                io.setImageParameters(
-                    (int)(fopimage.getHorizontalResolution() * 10),
-                    (int)(fopimage.getVerticalResolution() * 10),
-                    fopimage.getWidth(),
-                    fopimage.getHeight()
-                );
-                io.setImageIDESize((byte)fopimage.getBitsPerPixel());
-                io.setImageEncoding((byte)0x83);
-                io.setImageData(fopimage.getRessourceBytes());
-            */
+                /*
+                 * } else if (MimeConstants.MIME_JPEG.equals(mime)) { if
+                 * (!fopimage.load(FopImage.ORIGINAL_DATA)) { return; }
+                 * fact.releaseImage(url, userAgent);
+                 * 
+                 * int x = mpts2units(pos.getX() + currentIPPosition); int y =
+                 * mpts2units(pos.getY() + currentBPPosition); int w =
+                 * mpts2units(pos.getWidth()); int h =
+                 * mpts2units(pos.getHeight()); ImageObject io =
+                 * _afpDataStream.getImageObject(); io.setImageViewport(x, y, w,
+                 * h); io.setImageParameters(
+                 * (int)(fopimage.getHorizontalResolution() * 10),
+                 * (int)(fopimage.getVerticalResolution() * 10),
+                 * fopimage.getWidth(), fopimage.getHeight() );
+                 * io.setImageIDESize((byte)fopimage.getBitsPerPixel());
+                 * io.setImageEncoding((byte)0x83);
+                 * io.setImageData(fopimage.getRessourceBytes());
+                 */
             } else if (MimeConstants.MIME_TIFF.equals(mime)
-                        && fopimage instanceof TIFFImage) {
+                    && fopimage instanceof TIFFImage) {
                 TIFFImage tiffImage = (TIFFImage) fopimage;
                 int x = mpts2units(pos.getX() + currentIPPosition);
                 int y = mpts2units(pos.getY() + currentBPPosition);
                 int w = mpts2units(pos.getWidth());
                 int h = mpts2units(pos.getHeight());
-                ImageObject io = afpDataStream.getImageObject(x, y, w, h,
-                        getResolution(), getResolution());
+                int res = getResolution();
+                ImageObject io = afpDataStream.getImageObject(x, y, w, h, res,
+                        res);
                 io.setImageParameters(
-                    (int)(fopimage.getHorizontalResolution() * 10),
-                    (int)(fopimage.getVerticalResolution() * 10),
-                    fopimage.getWidth(),
-                    fopimage.getHeight()
-                );
+                        (int) (fopimage.getHorizontalResolution() * 10),
+                        (int) (fopimage.getVerticalResolution() * 10), fopimage
+                                .getWidth(), fopimage.getHeight());
                 if (tiffImage.getStripCount() == 1) {
                     int comp = tiffImage.getCompression();
                     if (comp == 3) {
                         if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
                             return;
                         }
-                        io.setImageEncoding((byte)0x81);
+                        io.setImageEncoding((byte) 0x81);
                         io.setImageData(fopimage.getRessourceBytes());
                     } else if (comp == 4) {
                         if (!fopimage.load(FopImage.ORIGINAL_DATA)) {
                             return;
                         }
-                        io.setImageEncoding((byte)0x82);
+                        io.setImageEncoding((byte) 0x82);
                         io.setImageData(fopimage.getRessourceBytes());
                     } else {
                         if (!fopimage.load(FopImage.BITMAP)) {
                             return;
                         }
-                        convertToGrayScaleImage(io, fopimage.getBitmaps(), 
-                                fopimage.getWidth(), fopimage.getHeight());
+                        convertToGrayScaleImage(io, fopimage.getBitmaps(),
+                                fopimage.getWidth(), fopimage.getHeight(), this.bitsPerPixel);
                     }
                 } else {
                     if (!fopimage.load(FopImage.BITMAP)) {
                         return;
                     }
-                    convertToGrayScaleImage(io, fopimage.getBitmaps(),
-                            fopimage.getWidth(), fopimage.getHeight());
+                    convertToGrayScaleImage(io, fopimage.getBitmaps(), fopimage
+                            .getWidth(), fopimage.getHeight(), this.bitsPerPixel);
                 }
             } else {
                 if (!fopimage.load(FopImage.BITMAP)) {
@@ -987,20 +838,19 @@
                 int y = mpts2units(pos.getY() + currentBPPosition);
                 int w = mpts2units(pos.getWidth());
                 int h = mpts2units(pos.getHeight());
-                ImageObject io = afpDataStream.getImageObject(x, y, w, h,
-                        getResolution(), getResolution());
+                int res = getResolution();
+                ImageObject io = afpDataStream.getImageObject(x, y, w, h, res,
+                        res);
                 io.setImageParameters(
-                    (int)(fopimage.getHorizontalResolution() * 10),
-                    (int)(fopimage.getVerticalResolution() * 10),
-                    fopimage.getWidth(),
-                    fopimage.getHeight()
-                );
+                        (int) (fopimage.getHorizontalResolution() * 10),
+                        (int) (fopimage.getVerticalResolution() * 10), fopimage
+                                .getWidth(), fopimage.getHeight());
                 if (colorImages) {
-                    io.setImageIDESize((byte)24);
+                    io.setImageIDESize((byte) 24);
                     io.setImageData(fopimage.getBitmaps());
                 } else {
-                    convertToGrayScaleImage(io, fopimage.getBitmaps(),
-                            fopimage.getWidth(), fopimage.getHeight());
+                    convertToGrayScaleImage(io, fopimage.getBitmaps(), fopimage
+                            .getWidth(), fopimage.getHeight(), this.bitsPerPixel);
                 }
             }
         }
@@ -1008,13 +858,18 @@
 
     /**
      * Writes a BufferedImage to an OutputStream as raw sRGB bitmaps.
-     * @param img the BufferedImage
-     * @param out the OutputStream
-     * @throws IOException In case of an I/O error.
-     */
-    public static void writeImage(BufferedImage img, OutputStream out) throws IOException {
-        int w  = img.getWidth();
-        int h  = img.getHeight();
+     * 
+     * @param img
+     *            the BufferedImage
+     * @param out
+     *            the OutputStream
+     * @throws IOException
+     *             In case of an I/O error.
+     */
+    public static void writeImage(BufferedImage img, OutputStream out)
+            throws IOException {
+        int w = img.getWidth();
+        int h = img.getHeight();
         int[] tmpMap = img.getRGB(0, 0, w, h, null, 0, w);
         for (int i = 0; i < h; i++) {
             for (int j = 0; j < w; j++) {
@@ -1022,21 +877,28 @@
                 int r = (p >> 16) & 0xFF;
                 int g = (p >> 8) & 0xFF;
                 int b = (p) & 0xFF;
-                out.write((byte)(r & 0xFF));
-                out.write((byte)(g & 0xFF));
-                out.write((byte)(b & 0xFF));
+                out.write((byte) (r & 0xFF));
+                out.write((byte) (g & 0xFF));
+                out.write((byte) (b & 0xFF));
             }
         }
     }
 
     /**
      * Draws a BufferedImage to AFP.
-     * @param bi the BufferedImage
-     * @param imageResolution the resolution of the BufferedImage
-     * @param x the x coordinate (in mpt)
-     * @param y the y coordinate (in mpt)
-     * @param w the width of the viewport (in mpt)
-     * @param h the height of the viewport (in mpt)
+     * 
+     * @param bi
+     *            the BufferedImage
+     * @param imageResolution
+     *            the resolution of the BufferedImage
+     * @param x
+     *            the x coordinate (in mpt)
+     * @param y
+     *            the y coordinate (in mpt)
+     * @param w
+     *            the width of the viewport (in mpt)
+     * @param h
+     *            the height of the viewport (in mpt)
      */
     public void drawBufferedImage(BufferedImage bi, int imageResolution, int x,
             int y, int w, int h) {
@@ -1044,46 +906,46 @@
         int afpy = mpts2units(y);
         int afpw = mpts2units(w);
         int afph = mpts2units(h);
+        int afpres = getResolution();
         ByteArrayOutputStream baout = new ByteArrayOutputStream();
         try {
-            //Serialize image
+            // Serialize image
             writeImage(bi, baout);
             byte[] buf = baout.toByteArray();
 
-            //Generate image
-            ImageObject io = afpDataStream.getImageObject(afpx, afpy, afpw, afph,
-                    getResolution(), getResolution());
-            io.setImageParameters(
-                imageResolution, imageResolution,
-                bi.getWidth(),
-                bi.getHeight()
-            );
+            // Generate image
+            ImageObject io = afpDataStream.getImageObject(afpx, afpy, afpw,
+                    afph, afpres, afpres);
+            io.setImageParameters(imageResolution, imageResolution,
+                    bi.getWidth(), bi.getHeight());
             if (colorImages) {
                 io.setImageIDESize((byte)24);
                 io.setImageData(buf);
             } else {
-                //TODO Teach it how to handle grayscale BufferedImages directly
-                //because this is pretty inefficient
-                convertToGrayScaleImage(io, buf, bi.getWidth(), bi.getHeight());
+                // TODO Teach it how to handle grayscale BufferedImages directly
+                // because this is pretty inefficient
+                convertToGrayScaleImage(io, buf, bi.getWidth(), bi.getHeight(), this.bitsPerPixel);
             }
         } catch (IOException ioe) {
-            log.error("Error while serializing bitmap: " + ioe.getMessage(), ioe);
+            log.error("Error while serializing bitmap: " + ioe.getMessage(),
+                    ioe);
         }
     }
 
     /**
-     * Establishes a new foreground or fill color.
-     * {@inheritDoc}
+     * Establishes a new foreground or fill color. {@inheritDoc}
      */
     public void updateColor(Color col, boolean fill) {
         if (fill) {
-            currentColor = col;
+            currentState.setColor(col);
         }
     }
 
     /**
      * Restores the state stack after a break out.
-     * @param breakOutList the state stack to restore.
+     * 
+     * @param breakOutList
+     *            the state stack to restore.
      */
     public void restoreStateStackAfterBreakOut(List breakOutList) {
 
@@ -1091,6 +953,7 @@
 
     /**
      * Breaks out of the state stack to handle fixed block-containers.
+     * 
      * @return the saved state stack to recreate later
      */
     public List breakOutOfStateStack() {
@@ -1131,76 +994,58 @@
     public void renderText(TextArea text) {
         renderInlineAreaBackAndBorders(text);
 
-        String name = getInternalFontNameForArea(text);
-        currentFontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
-        AFPFont tf = (AFPFont) fontInfo.getFonts().get(name);
+        String internalFontName = getInternalFontNameForArea(text);
+        this.currentState.setFontName(internalFontName);
+        int currentFontSize = ((Integer) text.getTrait(Trait.FONT_SIZE)).intValue();
+        this.currentState.setFontSize(currentFontSize); 
+        AFPFont font = (AFPFont) fontInfo.getFonts().get(internalFontName);
 
         Color col = (Color) text.getTrait(Trait.COLOR);
 
-        int vsci = mpts2units(tf.getWidth(' ', currentFontSize) / 1000
-                                + text.getTextWordSpaceAdjust()
-                                + text.getTextLetterSpaceAdjust());
+        int vsci = mpts2units(font.getWidth(' ', currentFontSize) / 1000
+                + text.getTextWordSpaceAdjust()
+                + text.getTextLetterSpaceAdjust());
 
         // word.getOffset() = only height of text itself
         // currentBlockIPPosition: 0 for beginning of line; nonzero
-        //  where previous line area failed to take up entire allocated space
+        // where previous line area failed to take up entire allocated space
         int rx = currentIPPosition + text.getBorderAndPaddingWidthStart();
-        int bl = currentBPPosition + text.getOffset() + text.getBaselineOffset();
+        int bl = currentBPPosition + text.getOffset()
+                + text.getBaselineOffset();
 
         // Set letterSpacing
-        //float ls = fs.getLetterSpacing() / this.currentFontSize;
+        // float ls = fs.getLetterSpacing() / this.currentFontSize;
 
         String worddata = text.getText();
 
-        // Create an AFPFontAttributes object from the current font details
-        AFPFontAttributes afpFontAttributes = new AFPFontAttributes(name, tf, currentFontSize);
-
-        if (!currentPageFonts.containsKey(afpFontAttributes.getFontKey())) {
-            // Font not found on current page, so add the new one
-            pageFontCounter++;
-            afpFontAttributes.setFontReference(pageFontCounter);
-            currentPageFonts.put(
-               afpFontAttributes.getFontKey(),
-               afpFontAttributes);
-
-        } else {
-            // Use the previously stored font attributes
-            afpFontAttributes = (AFPFontAttributes) currentPageFonts.get(
-                    afpFontAttributes.getFontKey());
-        }
+        AFPPageFonts pageFonts = this.currentState.getPageFonts();
+        AFPFontAttributes afpFontAttributes = pageFonts.registerFont(
+                internalFontName, font, currentFontSize);
 
         // Try and get the encoding to use for the font
         String encoding = null;
 
         try {
-            encoding = tf.getCharacterSet(currentFontSize).getEncoding();
+            encoding = font.getCharacterSet(currentFontSize).getEncoding();
         } catch (Throwable ex) {
             encoding = AFPConstants.EBCIDIC_ENCODING;
-            log.warn(
-                "renderText():: Error getting encoding for font "
-                + " - using default encoding "
-                + encoding);
+            log.warn("renderText():: Error getting encoding for font "
+                    + " - using default encoding " + encoding);
         }
 
         try {
-            afpDataStream.createText(
-                afpFontAttributes.getFontReference(),
-                mpts2units(rx),
-                mpts2units(bl),
-                col,
-                vsci,
-                mpts2units(text.getTextLetterSpaceAdjust()),
-                worddata.getBytes(encoding));
+            afpDataStream.createText(afpFontAttributes.getFontReference(),
+                    mpts2units(rx), pts2units(bl), col, vsci, mpts2units(text
+                            .getTextLetterSpaceAdjust()), worddata
+                            .getBytes(encoding));
         } catch (UnsupportedEncodingException usee) {
-            log.error(
-                "renderText:: Font "
-                + afpFontAttributes.getFontKey()
-                + " caused UnsupportedEncodingException");
+            log.error("renderText:: Font " + afpFontAttributes.getFontKey()
+                    + " caused UnsupportedEncodingException");
         }
 
         super.renderText(text);
 
-        renderTextDecoration(tf, currentFontSize, text, bl, rx);
+        renderTextDecoration(font, currentFontSize, text, bl, rx);
     }
 
     /**
@@ -1238,88 +1083,41 @@
     }
 
     /**
-     * Render leader area.
-     * This renders a leader area which is an area with a rule.
-     * @param area the leader area to render
+     * Render leader area. This renders a leader area which is an area with a
+     * rule.
+     * 
+     * @param area
+     *            the leader area to render
      */
     public void renderLeader(Leader area) {
         renderInlineAreaBackAndBorders(area);
 
         int style = area.getRuleStyle();
-        float startx = (currentIPPosition + area.getBorderAndPaddingWidthStart()) / 1000f;
+        float startx = (currentIPPosition + area
+                .getBorderAndPaddingWidthStart()) / 1000f;
         float starty = (currentBPPosition + area.getOffset()) / 1000f;
-        float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart()
-                        + area.getIPD()) / 1000f;
+        float endx = (currentIPPosition + area.getBorderAndPaddingWidthStart() + area
+                .getIPD()) / 1000f;
         float ruleThickness = area.getRuleThickness() / 1000f;
-        Color col = (Color)area.getTrait(Trait.COLOR);
+        Color col = (Color) area.getTrait(Trait.COLOR);
 
         switch (style) {
-            case EN_SOLID:
-            case EN_DASHED:
-            case EN_DOUBLE:
-            case EN_DOTTED:
-            case EN_GROOVE:
-            case EN_RIDGE:
-                drawBorderLine(startx, starty, endx, starty + ruleThickness,
-                        true, true, style, col);
-                break;
-            default:
-                throw new UnsupportedOperationException("rule style not supported");
+        case EN_SOLID:
+        case EN_DASHED:
+        case EN_DOUBLE:
+        case EN_DOTTED:
+        case EN_GROOVE:
+        case EN_RIDGE:
+            drawBorderLine(startx, starty, endx, starty + ruleThickness, true,
+                    true, style, col);
+            break;
+        default:
+            throw new UnsupportedOperationException("rule style not supported");
         }
         super.renderLeader(area);
     }
 
     /**
-     * Sets the AFPRenderer options
-     * @param options   the <code>Map</code> containing the options
-     */
-// UNUSED
-//     public void setOptions(Map options) {
-//    
-//         this.afpOptions = options;
-//    
-//     }
-    /**
-     * Determines the orientation from the string representation, this method
-     * guarantees to return a value of either 0, 90, 180 or 270.
-     *
-     * @return the orientation
-     */
-// UNUSED
-//     private int getOrientation(String orientationString) {
-//
-//        int orientation = 0;
-//        if (orientationString != null && orientationString.length() > 0) {
-//            try {
-//                orientation = Integer.parseInt(orientationString);
-//            } catch (NumberFormatException nfe) {
-//                log.error("Cannot use orientation of " + orientation
-//                        + " defaulting to zero.");
-//                orientation = 0;
-//            }
-//        } else {
-//            orientation = 0;
-//        }
-//        switch (orientation) {
-//        case 0:
-//            break;
-//        case 90:
-//            break;
-//        case 180:
-//            break;
-//        case 270:
-//            break;
-//        default:
-//            log.error("Cannot use orientation of " + orientation
-//                    + " defaulting to zero.");
-//            orientation = 0;
-//            break;
-//        }
-//
-//        return orientation;
-//
-//    }
-    /**
      * Sets the rotation to be used for portrait pages, valid values are 0
      * (default), 90, 180, 270.
      * 
@@ -1328,14 +1126,13 @@
      */
     public void setPortraitRotation(int rotation) {
 
-        if (rotation == 0
-            || rotation == 90
-            || rotation == 180
-            || rotation == 270) {
+        if (rotation == 0 || rotation == 90 || rotation == 180
+                || rotation == 270) {
             portraitRotation = rotation;
         } else {
-            throw new IllegalArgumentException("The portrait rotation must be one"
-                + " of the values 0, 90, 180, 270");
+            throw new IllegalArgumentException(
+                    "The portrait rotation must be one"
+                            + " of the values 0, 90, 180, 270");
 
         }
 
@@ -1344,20 +1141,19 @@
     /**
      * Sets the rotation to be used for landsacpe pages, valid values are 0, 90,
      * 180, 270 (default).
-     *  
+     * 
      * @param rotation
      *            The rotation in degrees.
      */
     public void setLandscapeRotation(int rotation) {
 
-        if (rotation == 0
-            || rotation == 90
-            || rotation == 180
-            || rotation == 270) {
+        if (rotation == 0 || rotation == 90 || rotation == 180
+                || rotation == 270) {
             landscapeRotation = rotation;
         } else {
-            throw new IllegalArgumentException("The landscape rotation must be one"
-                + " of the values 0, 90, 180, 270");
+            throw new IllegalArgumentException(
+                    "The landscape rotation must be one"
+                            + " of the values 0, 90, 180, 270");
         }
 
     }
@@ -1365,7 +1161,7 @@
     /**
      * Get the MIME type of the renderer.
      * 
-     * @return   The MIME type of the renderer
+     * @return The MIME type of the renderer
      */
     public String getMimeType() {
         return MimeConstants.MIME_AFP;
@@ -1375,7 +1171,8 @@
      * Method to render the page extension.
      * <p>
      * 
-     * @param pageViewport the page object
+     * @param pageViewport
+     *            the page object
      */
     private void renderPageObjectExtensions(PageViewport pageViewport) {
 
@@ -1386,7 +1183,7 @@
             // the s-p-m
             Iterator i = pageViewport.getExtensionAttachments().iterator();
             while (i.hasNext()) {
-                ExtensionAttachment attachment = (ExtensionAttachment)i.next();
+                ExtensionAttachment attachment = (ExtensionAttachment) i.next();
                 if (AFPPageSetup.CATEGORY.equals(attachment.getCategory())) {
                     AFPPageSetup aps = (AFPPageSetup) attachment;
                     String element = aps.getElementName();
@@ -1425,7 +1222,9 @@
 
     /**
      * Converts FOP mpt measurement to afp measurement units
-     * @param mpt the millipoints value
+     * 
+     * @param mpt
+     *            the millipoints value
      */
     private int mpts2units(int mpt) {
         return mpts2units((double) mpt);
@@ -1433,7 +1232,9 @@
 
     /**
      * Converts FOP pt measurement to afp measurement units
-     * @param mpt the millipoints value
+     * 
+     * @param mpt
+     *            the millipoints value
      */
     private int pts2units(float mpt) {
         return mpts2units(mpt * 1000d);
@@ -1447,17 +1248,27 @@
      * @return afp measurement unit value
      */
     private int mpts2units(double mpt) {
-        return (int)Math.round(mpt / (DPI_CONVERSION_FACTOR / getResolution()));
+        return (int) Math
+                .round(mpt / (DPI_CONVERSION_FACTOR / getResolution()));
     }
 
     /**
-     * Converts a byte array containing 24 bit RGB image data to a grayscale image.
-     * @param io the target image object
-     * @param raw the buffer containing the RGB image data
-     * @param width the width of the image in pixels
-     * @param height the height of the image in pixels
+     * Converts a byte array containing 24 bit RGB image data to a grayscale
+     * image.
+     * 
+     * @param io
+     *            the target image object
+     * @param raw
+     *            the buffer containing the RGB image data
+     * @param width
+     *            the width of the image in pixels
+     * @param height
+     *            the height of the image in pixels
+     * @param bitsPerPixel
+     *            the number of bits to use per pixel
      */
-    private void convertToGrayScaleImage(ImageObject io, byte[] raw, int width, int height) {
+    protected static void convertToGrayScaleImage(ImageObject io, byte[] raw, int width,
+            int height, int bitsPerPixel) {
         int pixelsPerByte = 8 / bitsPerPixel;
         int bytewidth = (width / pixelsPerByte);
         if ((width % pixelsPerByte) != 0) {
@@ -1469,26 +1280,26 @@
             ib = 0;
             int i = 3 * y * width;
             for (int x = 0; x < width; x++, i += 3) {
-                
+
                 // see http://www.jguru.com/faq/view.jsp?EID=221919
-                double greyVal = 0.212671d * ((int) raw[i] & 0xff)
-                    + 0.715160d * ((int) raw[i + 1] & 0xff)
-                    + 0.072169d * ((int) raw[i + 2] & 0xff);
+                double greyVal = 0.212671d * ((int) raw[i] & 0xff) + 0.715160d
+                        * ((int) raw[i + 1] & 0xff) + 0.072169d
+                        * ((int) raw[i + 2] & 0xff);
                 switch (bitsPerPixel) {
-                    case 1:
-                        if (greyVal < 128) {
-                            ib |= (byte) (1 << (7 - (x % 8)));
-                        }
-                        break;
-                    case 4:
-                        greyVal /= 16;
-                        ib |= (byte) ((byte) greyVal << ((1 - (x % 2)) * 4));
-                        break;
-                    case 8:
-                        ib = (byte) greyVal;
-                        break;
-                    default:
-                        throw new UnsupportedOperationException(
+                case 1:
+                    if (greyVal < 128) {
+                        ib |= (byte) (1 << (7 - (x % 8)));
+                    }
+                    break;
+                case 4:
+                    greyVal /= 16;
+                    ib |= (byte) ((byte) greyVal << ((1 - (x % 2)) * 4));
+                    break;
+                case 8:
+                    ib = (byte) greyVal;
+                    break;
+                default:
+                    throw new UnsupportedOperationException(
                             "Unsupported bits per pixel: " + bitsPerPixel);
                 }
 
@@ -1502,7 +1313,7 @@
         io.setImageIDESize((byte) bitsPerPixel);
         io.setImageData(bw);
     }
-    
+
     private final class ViewPortPos {
         private int x = 0;
 
@@ -1611,7 +1422,8 @@
     private void popViewPortPos() {
         viewPortPositions.remove(viewPortPositions.size() - 1);
         if (viewPortPositions.size() > 0) {
-            ViewPortPos vpp = (ViewPortPos)viewPortPositions.get(viewPortPositions.size() - 1);
+            ViewPortPos vpp = (ViewPortPos) viewPortPositions
+                    .get(viewPortPositions.size() - 1);
             afpDataStream.setOffsets(vpp.x, vpp.y, vpp.rot);
         }
     }
@@ -1625,9 +1437,9 @@
     public void setBitsPerPixel(int bitsPerPixel) {
         this.bitsPerPixel = bitsPerPixel;
         switch (bitsPerPixel) {
-            case 1:
-            case 4:
-            case 8:
+        case 1:
+        case 4:
+        case 8:
             break;
         default:
             log.warn("Invalid bits_per_pixel value, must be 1, 4 or 8.");
@@ -1647,20 +1459,36 @@
     }
 
     /**
+     * Returns the AFPDataStream
+     * 
+     * @return the AFPDataStream
+     */
+    public AFPDataStream getAFPDataStream() {
+        return afpDataStream;
+    }
+
+    /**
      * Sets the output/device resolution
      * 
      * @param resolution
      *            the output resolution (dpi)
      */
     public void setResolution(int resolution) {
-        if (log.isDebugEnabled()) {
-            log.debug("renderer-resolution set to: " + resolution + "dpi");
+        if (resolution == DPI_240_RESOLUTION
+                || resolution == DPI_1440_RESOLUTION) {
+            this.resolution = resolution;
+            if (log.isDebugEnabled()) {
+                log.debug("renderer-resolution set to: " + resolution + " dpi");
+            }
+        } else {
+            log.error("invalid resolution, can only be " + DPI_240_RESOLUTION
+                    + " or " + DPI_1440_RESOLUTION + " dpi");
         }
-        this.resolution = resolution;
     }
-    
+
     /**
      * Returns the output/device resolution.
+     * 
      * @return the resolution in dpi
      */
     public int getResolution() {

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java?rev=603590&r1=603589&r2=603590&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java Wed Dec 12 04:24:10 2007
@@ -239,7 +239,8 @@
             
             Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false);
             if (rendererResolutionCfg != null) {
-                afpRenderer.setResolution(rendererResolutionCfg.getValueAsInteger(240));
+                afpRenderer.setResolution(rendererResolutionCfg.getValueAsInteger(
+                        AFPRenderer.DPI_240_RESOLUTION));
             }
         }
     }

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContextConstants.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContextConstants.java?rev=603590&r1=603589&r2=603590&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContextConstants.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPRendererContextConstants.java Wed Dec 12 04:24:10 2007
@@ -1,35 +1,49 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* $Id$ */
-
-package org.apache.fop.render.afp;
-
-import org.apache.fop.render.RendererContextConstants;
-
-/**
- * Defines a number of standard constants (keys) for use by the RendererContext class.
- */
-public interface AFPRendererContextConstants extends RendererContextConstants {
-
-    /**
-     * Key for a Boolean value that enables grayscale processing instead of color 
-     * processing.
-     */
-    String AFP_GRAYSCALE = "afpGrayscale";
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.afp;
+
+import org.apache.fop.render.RendererContextConstants;
+
+/**
+ * Defines a number of standard constants (keys) for use by the RendererContext class.
+ */
+public interface AFPRendererContextConstants extends RendererContextConstants {
+
+    /**
+     * Key for a Boolean value that enables grayscale processing instead of color 
+     * processing.
+     */
+    String AFP_GRAYSCALE = "afpGrayscale";
+
+    /** The font information for the AFP renderer. */
+    String AFP_FONT_INFO = "afpFontInfo";
+
+    /** The afp resolution. */
+    String AFP_RESOLUTION = "afpResolution";
+
+    /** The afp datastream */
+    String AFP_DATASTREAM = "afpDataStream";
+
+    /** The afp state */
+    String AFP_STATE = "afpPageState";
+
+    /** The afp bits per pixel */
+    String AFP_BITS_PER_PIXEL = "afpBitsPerPixel";
+}

Modified: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java?rev=603590&r1=603589&r2=603590&view=diff
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java (original)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPSVGHandler.java Wed Dec 12 04:24:10 2007
@@ -15,13 +15,27 @@
  * limitations under the License.
  */
 
-/* $Id$ */
+/* $Id: $ */
 
 package org.apache.fop.render.afp;
 
 // FOP
+import java.awt.geom.AffineTransform;
+import java.io.IOException;
+
+import org.apache.avalon.framework.configuration.Configuration;
+import org.apache.batik.bridge.BridgeContext;
+import org.apache.batik.bridge.GVTBuilder;
+import org.apache.batik.dom.svg.SVGDOMImplementation;
+import org.apache.batik.gvt.GraphicsNode;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
 import org.apache.fop.render.AbstractGenericSVGHandler;
 import org.apache.fop.render.Renderer;
+import org.apache.fop.render.RendererContext;
+import org.apache.fop.render.afp.modca.AFPDataStream;
+import org.apache.fop.svg.SVGUserAgent;
+import org.w3c.dom.Document;
 
 /**
  * AFP XML handler for SVG. Uses Apache Batik for SVG processing.
@@ -30,10 +44,126 @@
  */
 public class AFPSVGHandler extends AbstractGenericSVGHandler {
 
+    /** logging instance */
+    private static Log log = LogFactory.getLog(AFPSVGHandler.class);
+
+    /** {@inheritDoc} */
+    public void handleXML(RendererContext context, 
+                Document doc, String ns) throws Exception {
+        AFPInfo afpi = getAFPInfo(context);
+
+        if (SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns)) {
+            renderSVGDocument(context, doc, afpi);
+        }
+    }
+
+    /**
+     * Get the afp information from the render context.
+     *
+     * @param context the renderer context
+     * @return the afp information retrieved from the context
+     */
+    public static AFPInfo getAFPInfo(RendererContext context) {
+        AFPInfo afpi = new AFPInfo();
+        afpi.width = ((Integer)context.getProperty(WIDTH)).intValue();
+        afpi.height = ((Integer)context.getProperty(HEIGHT)).intValue();
+        afpi.currentXPosition = ((Integer)context.getProperty(XPOS)).intValue();
+        afpi.currentYPosition = ((Integer)context.getProperty(YPOS)).intValue();
+        afpi.cfg = (Configuration)context.getProperty(HANDLER_CONFIGURATION);
+        afpi.fontInfo = (org.apache.fop.fonts.FontInfo)context.getProperty(
+                AFPRendererContextConstants.AFP_FONT_INFO);
+        afpi.resolution = ((Integer)context.getProperty(
+                AFPRendererContextConstants.AFP_RESOLUTION)).intValue();
+        afpi.afpState = (AFPState)context.getProperty(
+                AFPRendererContextConstants.AFP_STATE);
+        afpi.afpDataStream = (AFPDataStream)context.getProperty(
+                AFPRendererContextConstants.AFP_DATASTREAM);
+        afpi.grayscale = ((Boolean)context.getProperty(
+                AFPRendererContextConstants.AFP_GRAYSCALE)).booleanValue();
+        afpi.bitsPerPixel = ((Integer)context.getProperty(
+                AFPRendererContextConstants.AFP_BITS_PER_PIXEL)).intValue();
+        return afpi;
+    }
+
+    /**
+     * Render the SVG document.
+     * @param context the renderer context
+     * @param doc the SVG document
+     * @param afpInfo the AFPInfo renderer parameters
+     * @throws IOException In case of an I/O error while painting the image
+     */
+    protected void renderSVGDocument(final RendererContext context,
+            final Document doc, AFPInfo afpInfo) throws IOException {
+        
+        final boolean textAsShapes = false;
+        AFPGraphics2D graphics = new AFPGraphics2D(textAsShapes);
+        graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
+        graphics.setAFPInfo(afpInfo);
+        
+        GVTBuilder builder = new GVTBuilder();
+
+        boolean strokeText = false;
+        Configuration cfg = afpInfo.cfg;
+        if (cfg != null) {
+            strokeText = cfg.getChild("stroke-text", true).getValueAsBoolean(strokeText);
+        }
+        
+        final float uaResolution = context.getUserAgent().getSourceResolution();
+        SVGUserAgent svgUserAgent = new SVGUserAgent(25.4f / uaResolution, new AffineTransform());
+
+        BridgeContext ctx = new BridgeContext(svgUserAgent);
+        AFPTextHandler afpTextHandler = null;
+        //Controls whether text painted by Batik is generated using text or path operations
+        if (!strokeText) {
+            afpTextHandler = new AFPTextHandler(graphics);
+            graphics.setCustomTextHandler(afpTextHandler);
+            AFPTextPainter textPainter = new AFPTextPainter(afpTextHandler);
+            ctx.setTextPainter(textPainter);            
+            AFPTextElementBridge tBridge = new AFPTextElementBridge(textPainter);
+            ctx.putBridge(tBridge);
+        }
+
+        GraphicsNode root;
+        try {
+            root = builder.build(ctx, doc);
+        } catch (Exception e) {
+            log.error("SVG graphic could not be built: "
+                                   + e.getMessage(), e);
+            return;
+        }
+        log.debug("Generating SVG at " 
+                + afpInfo.resolution + "dpi.");
+
+        int res = afpInfo.resolution;
+        
+        double w = ctx.getDocumentSize().getWidth() * 1000f;
+        double h = ctx.getDocumentSize().getHeight() * 1000f;
+        
+        // convert to afp inches
+        double sx = ((afpInfo.width / w) * res) / 72f;
+        double sy = ((afpInfo.height / h) * res) / 72f;
+        double xOffset = (afpInfo.currentXPosition * res) / 72000f;
+        double yOffset = ((afpInfo.height - afpInfo.currentYPosition) * res) / 72000f;
+
+        // Transformation matrix that establishes the local coordinate system for the SVG graphic
+        // in relation to the current coordinate system (note: y axis is inverted)
+        AffineTransform trans = new AffineTransform(sx, 0, 0, -sy, xOffset, yOffset);
+        graphics.setTransform(trans);
+        try {
+            root.paint(graphics);
+        } catch (Exception e) {
+            log.error("SVG graphic could not be rendered: " + e.getMessage(), e);
+        }
+    }
+    
     /** {@inheritDoc} */
     public boolean supportsRenderer(Renderer renderer) {
         return (renderer instanceof AFPRenderer);
     }
     
+    /** {@inheritDoc} */
+    public String getNamespace() {
+        return SVGDOMImplementation.SVG_NAMESPACE_URI;
+    }
 }
 

Added: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPState.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPState.java?rev=603590&view=auto
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPState.java (added)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPState.java Wed Dec 12 04:24:10 2007
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id: $ */
+
+package org.apache.fop.render.afp;
+
+import java.awt.Color;
+import java.util.Arrays;
+
+/**
+ * This keeps information about the current state when writing to pdf.
+ */
+public class AFPState {
+    /**
+     * The current color
+     */
+    private Color color = null;
+
+    /**
+     * The current background color
+     */
+    private Color backColor = null;
+
+    /**
+     * The current font name
+     */
+    private String fontName = null;
+
+    /**
+     * The current font size
+     */
+    private int fontSize = 0;
+
+    /**
+     * The current line width
+     */
+    private float lineWidth = 0;
+
+    /**
+     * The dash array for the current basic stroke (line type)
+     */
+    private float[] dashArray = null;
+
+    /**
+     * The current fill status
+     */
+    private boolean filled = false;
+    
+    /**
+     * The fonts on the current page
+     */
+    private AFPPageFonts pageFonts = null;
+
+    /**
+     * Set the current color.
+     * Check if the new color is a change and then set the current color.
+     *
+     * @param col the color to set
+     * @return true if the color has changed
+     */
+    protected boolean setColor(Color col) {
+        if (!col.equals(this.color)) {
+            this.color = col;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Sets if the current painted shape is to be filled
+     * @param fill true if the current painted shape is to be filled
+     * @return true if the fill value has changed
+     */
+    protected boolean setFill(boolean fill) {
+        if (fill != this.filled) {
+            this.filled = fill;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Get the color.
+     * @return the color
+     */
+    protected Color getColor() {
+        if (this.color == null) {
+            this.color = Color.black;
+        }
+        return this.color;
+    }
+
+    /**
+     * Set the current line width.
+     * @param width the line width in points
+     * @return true if the line width has changed
+     */
+    protected boolean setLineWidth(float width) {
+        if (this.lineWidth != width) {
+            this.lineWidth = width;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Sets the dash array (line type) for the current basic stroke
+     * @param dash the line dash array
+     * @return true if the dash array has changed
+     */
+    public boolean setDashArray(float[] dash) {
+        if (!Arrays.equals(dash, this.dashArray)) {
+            this.dashArray = dash;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Gets the current line width
+     * @return the current line width
+     */
+    protected float getLineWidth() {
+        return lineWidth;
+    }
+
+    /**
+     * Get the background color.
+     * @return the background color
+     */
+    protected Color getBackColor() {
+        if (this.backColor == null) {
+            this.backColor = Color.white;
+        }
+        return backColor;
+    }
+
+    /**
+     * Set the current background color.
+     * Check if the new background color is a change and then set the current background color.
+     *
+     * @param col the background color to set
+     * @return true if the color has changed
+     */
+    protected boolean setBackColor(Color col) {
+        if (!col.equals(this.backColor)) {
+            this.backColor = col;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Set the current font name
+     * @param internalFontName the internal font name
+     * @return true if the font name has changed
+     */
+    protected boolean setFontName(String internalFontName) {
+        if (!internalFontName.equals(this.fontName)) {
+            this.fontName = internalFontName;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Gets the current font name
+     * @return the current font name
+     */
+    protected String getFontName() {
+        return this.fontName;
+    }
+    
+    /**
+     * Gets the current font size
+     * @return the current font size
+     */
+    protected int getFontSize() {
+        return this.fontSize;
+    }
+
+    /**
+     * Set the current font size.
+     * Check if the font size is a change and then set the current font size.
+     *
+     * @param size the font size to set
+     * @return true if the font size has changed
+     */
+    protected boolean setFontSize(int size) {
+        if (size != this.fontSize) {
+            this.fontSize = size;
+            return true;
+        }
+        return false;
+    }
+
+    /**
+     * Gets the current page fonts
+     * @return the current page fonts
+     */
+    protected AFPPageFonts getPageFonts() {
+        if (this.pageFonts == null) {
+            this.pageFonts = new AFPPageFonts();
+        }
+        return this.pageFonts;
+    }
+
+    /**
+     * Resets the current state
+     */    
+    protected void reset() {
+        this.color = null;
+        this.backColor = null;
+        this.fontName = null;         
+        this.fontSize = 0;         
+        this.lineWidth = 0;
+        this.dashArray = null;
+        this.filled = false;
+        if (this.pageFonts != null) {
+            this.pageFonts.clear();
+        }
+    }
+}
\ No newline at end of file

Added: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextElementBridge.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextElementBridge.java?rev=603590&view=auto
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextElementBridge.java (added)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextElementBridge.java Wed Dec 12 04:24:10 2007
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id: PSTextElementBridge.java 426576 2006-07-28 15:44:37Z jeremias $ */
+
+package org.apache.fop.render.afp;
+
+import org.apache.batik.bridge.SVGTextElementBridge;
+import org.apache.batik.bridge.BridgeContext;
+import org.apache.batik.gvt.GraphicsNode;
+import org.apache.batik.gvt.TextNode;
+import org.apache.batik.gvt.TextPainter;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * Bridge class for the &lt;text> element.
+ * This bridge will use the direct text painter if the text
+ * for the element is simple.
+ */
+public class AFPTextElementBridge extends SVGTextElementBridge {
+    
+    private AFPTextPainter textPainter;
+
+    /**
+     * Constructs a new bridge for the &lt;text> element.
+     * @param textPainter the text painter to use
+     */
+    public AFPTextElementBridge(AFPTextPainter textPainter) {
+        this.textPainter = textPainter;
+    }
+
+    /**
+     * Create a text element bridge.
+     * This set the text painter on the node if the text is simple.
+     * @param ctx the bridge context
+     * @param e the svg element
+     * @return the text graphics node created by the super class
+     */
+    public GraphicsNode createGraphicsNode(BridgeContext ctx, Element e) {
+        GraphicsNode node = super.createGraphicsNode(ctx, e);
+        if (node != null && isSimple(ctx, e, node)) {
+            ((TextNode)node).setTextPainter(getTextPainter());
+        }
+        return node;
+    }
+
+    private TextPainter getTextPainter() {
+        return this.textPainter;
+    }
+
+    /**
+     * Check if text element contains simple text.
+     * This checks the children of the text element to determine
+     * if the text is simple. The text is simple if it can be rendered
+     * with basic text drawing algorithms. This means there are no
+     * alternate characters, the font is known and there are no effects
+     * applied to the text.
+     *
+     * @param ctx the bridge context
+     * @param element the svg text element
+     * @param node the graphics node
+     * @return true if this text is simple of false if it cannot be
+     *         easily rendered using normal drawString on the PDFGraphics2D
+     */
+    private boolean isSimple(BridgeContext ctx, Element element, GraphicsNode node) {
+        for (Node n = element.getFirstChild();
+                n != null;
+                n = n.getNextSibling()) {
+
+            switch (n.getNodeType()) {
+            case Node.ELEMENT_NODE:
+
+                if (n.getLocalName().equals(SVG_TSPAN_TAG)
+                        || n.getLocalName().equals(SVG_ALT_GLYPH_TAG)) {
+                    return false;
+                } else if (n.getLocalName().equals(SVG_TEXT_PATH_TAG)) {
+                    return false;
+                } else if (n.getLocalName().equals(SVG_TREF_TAG)) {
+                    return false;
+                }
+                break;
+            case Node.TEXT_NODE:
+            case Node.CDATA_SECTION_NODE:
+            default:
+            }
+        }
+
+        /*if (CSSUtilities.convertFilter(element, node, ctx) != null) {
+            return false;
+        }*/
+
+        return true;
+    }
+}
+

Added: xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextHandler.java
URL: http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextHandler.java?rev=603590&view=auto
==============================================================================
--- xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextHandler.java (added)
+++ xmlgraphics/fop/trunk/src/java/org/apache/fop/render/afp/AFPTextHandler.java Wed Dec 12 04:24:10 2007
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.render.afp;
+
+import java.awt.Color;
+import java.io.IOException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.fop.fonts.Font;
+import org.apache.fop.fonts.FontInfo;
+import org.apache.fop.render.afp.fonts.AFPFont;
+import org.apache.fop.render.afp.modca.GraphicsObject;
+
+import org.apache.xmlgraphics.java2d.TextHandler;
+
+/**
+ * Specialized TextHandler implementation that the AFPGraphics2D class delegates to to paint text
+ * using AFP GOCA text operations.
+ */
+public class AFPTextHandler implements TextHandler {
+
+    /** logging instance */
+    private static Log log = LogFactory.getLog(AFPTextHandler.class);
+
+    private AFPGraphics2D g2d = null;
+        
+    /** Overriding FontState */
+    protected Font overrideFont = null;
+
+    /** current state */
+    private AFPState afpState = null;
+
+    /**
+     * Main constructor.
+     * @param g2d the PSGraphics2D instance this instances is used by
+     */
+    public AFPTextHandler(AFPGraphics2D g2d) {
+        this.g2d = g2d;
+        this.afpState = g2d.getAFPInfo().getState();
+    }
+    
+    /**
+     * Return the font information associated with this object
+     * @return the FontInfo object
+     */
+    public FontInfo getFontInfo() {
+        return g2d.getAFPInfo().getFontInfo();
+    }
+    
+    /**
+     * Add a text string to the current data object of the AFP datastream.
+     * The text is painted using text operations.
+     * {@inheritDoc} 
+     */
+    public void drawString(String str, float x, float y) throws IOException {
+        log.debug("drawString() str=" + str + ", x=" + x + ", y=" + y);
+        GraphicsObject graphicsObj = g2d.getGraphicsObject();
+        Color col = g2d.getColor();
+        if (afpState.setColor(col)) {
+            graphicsObj.setColor(col);
+        }
+        if (overrideFont != null) {
+            FontInfo fontInfo = getFontInfo();
+            AFPPageFonts pageFonts = this.afpState.getPageFonts();
+            String internalFontName = overrideFont.getFontName();
+            int fontSize = overrideFont.getFontSize();
+            if (afpState.setFontName(internalFontName) || afpState.setFontSize(fontSize)) {
+                AFPFont font = (AFPFont)fontInfo.getFonts().get(internalFontName);
+                AFPFontAttributes afpFontAttributes = pageFonts.registerFont(
+                        internalFontName,
+                        font,
+                        fontSize
+                );
+                int fontReference = afpFontAttributes.getFontReference();
+                graphicsObj.setCharacterSet(fontReference);                
+            }
+        }
+        graphicsObj.addString(str, (int)Math.round(x), (int)Math.round(y));
+    }
+    
+    /**
+     * Sets the overriding font.
+     * @param overrideFont Overriding Font to set
+     */
+    public void setOverrideFont(Font overrideFont) {
+        this.overrideFont = overrideFont;       
+    }    
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: fop-commits-unsubscribe@xmlgraphics.apache.org
For additional commands, e-mail: fop-commits-help@xmlgraphics.apache.org