Package org.apache.xmlgraphics.ps

Examples of org.apache.xmlgraphics.ps.PSGenerator


    /** {@inheritDoc} */
    public void handleImage(RenderingContext context, Image image, Rectangle pos)
                throws IOException {
        PSRenderingContext psContext = (PSRenderingContext)context;
        PSGenerator gen = psContext.getGenerator();
        ImageXMLDOM imageSVG = (ImageXMLDOM)image;

        //Controls whether text painted by Batik is generated using text or path operations
        boolean strokeText = false;
        //TODO Configure text stroking

        SVGUserAgent ua
             = new SVGUserAgent(context.getUserAgent(), new AffineTransform());

        PSGraphics2D graphics = new PSGraphics2D(strokeText, gen);
        graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

        BridgeContext ctx = new PSBridgeContext(ua,
                (strokeText ? null : psContext.getFontInfo()),
                context.getUserAgent().getFactory().getImageManager(),
                context.getUserAgent().getImageSessionContext());

        //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
        //to it.
        Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument());

        GraphicsNode root;
        try {
            GVTBuilder builder = new GVTBuilder();
            root = builder.build(ctx, clonedDoc);
        } catch (Exception e) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                    context.getUserAgent().getEventBroadcaster());
            eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI());
            return;
        }
        // get the 'width' and 'height' attributes of the SVG document
        float w = (float)ctx.getDocumentSize().getWidth() * 1000f;
        float h = (float)ctx.getDocumentSize().getHeight() * 1000f;

        float sx = pos.width / w;
        float sy = pos.height / h;

        ctx = null;

        gen.commentln("%FOPBeginSVG");
        gen.saveGraphicsState();
        final boolean clip = false;
        if (clip) {
            /*
             * Clip to the svg area.
             * Note: To have the svg overlay (under) a text area then use
             * an fo:block-container
             */
            gen.writeln("newpath");
            gen.defineRect(pos.getMinX() / 1000f, pos.getMinY() / 1000f,
                    pos.width / 1000f, pos.height / 1000f);
            gen.writeln("clip");
        }

        // transform so that the coordinates (0,0) is from the top left
        // and positive is down and to the right. (0,0) is where the
        // viewBox puts it.
        gen.concatMatrix(sx, 0, 0, sy, pos.getMinX() / 1000f, pos.getMinY() / 1000f);

        AffineTransform transform = new AffineTransform();
        // scale to viewbox
        transform.translate(pos.getMinX(), pos.getMinY());
        gen.getCurrentState().concatMatrix(transform);
        try {
            root.paint(graphics);
        } catch (Exception e) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                    context.getUserAgent().getEventBroadcaster());
            eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI());
        }

        gen.restoreGraphicsState();
        gen.commentln("%FOPEndSVG");
    }
View Full Code Here


        logTextRun(runaci, layout);
        CharSequence chars = collectCharacters(runaci);
        runaci.first(); //Reset ACI

        final PSGraphics2D ps = (PSGraphics2D)g2d;
        final PSGenerator gen = ps.getPSGenerator();
        ps.preparePainting();

        if (DEBUG) {
            log.debug("Text: " + chars);
            gen.commentln("%Text: " + chars);
        }

        GeneralPath debugShapes = null;
        if (DEBUG) {
            debugShapes = new GeneralPath();
        }

        TextUtil textUtil = new TextUtil(gen);
        textUtil.setupFonts(runaci);
        if (!textUtil.hasFonts()) {
            //Draw using Java2D when no native fonts are available
            textRun.getLayout().draw(g2d);
            return;
        }

        gen.saveGraphicsState();
        gen.concatMatrix(g2d.getTransform());
        Shape imclip = g2d.getClip();
        clip(ps, imclip);

        gen.writeln("BT"); //beginTextObject()

        AffineTransform localTransform = new AffineTransform();
        Point2D prevPos = null;
        GVTGlyphVector gv = layout.getGlyphVector();
        PSTextRun psRun = new PSTextRun(); //Used to split a text run into smaller runs
        for (int index = 0, c = gv.getNumGlyphs(); index < c; index++) {
            char ch = chars.charAt(index);
            boolean visibleChar = gv.isGlyphVisible(index)
                || (CharUtilities.isAnySpace(ch) && !CharUtilities.isZeroWidthSpace(ch));
            logCharacter(ch, layout, index, visibleChar);
            if (!visibleChar) {
                continue;
            }
            Point2D glyphPos = gv.getGlyphPosition(index);

            AffineTransform glyphTransform = gv.getGlyphTransform(index);
            if (log.isTraceEnabled()) {
                log.trace("pos " + glyphPos + ", transform " + glyphTransform);
            }
            if (DEBUG) {
                Shape sh = gv.getGlyphLogicalBounds(index);
                if (sh == null) {
                    sh = new Ellipse2D.Double(glyphPos.getX(), glyphPos.getY(), 2, 2);
                }
                debugShapes.append(sh, false);
            }

            //Exact position of the glyph
            localTransform.setToIdentity();
            localTransform.translate(glyphPos.getX(), glyphPos.getY());
            if (glyphTransform != null) {
                localTransform.concatenate(glyphTransform);
            }
            localTransform.scale(1, -1);

            boolean flushCurrentRun = false;
            //Try to optimize by combining characters using the same font and on the same line.
            if (glyphTransform != null) {
                //Happens for text-on-a-path
                flushCurrentRun = true;
            }
            if (psRun.getRunLength() >= 128) {
                //Don't let a run get too long
                flushCurrentRun = true;
            }

            //Note the position of the glyph relative to the previous one
            Point2D relPos;
            if (prevPos == null) {
                relPos = new Point2D.Double(0, 0);
            } else {
                relPos = new Point2D.Double(
                        glyphPos.getX() - prevPos.getX(),
                        glyphPos.getY() - prevPos.getY());
            }
            if (psRun.vertChanges == 0
                    && psRun.getHorizRunLength() > 2
                    && relPos.getY() != 0) {
                //new line
                flushCurrentRun = true;
            }

            //Select the actual character to paint
            char paintChar = (CharUtilities.isAnySpace(ch) ? ' ' : ch);

            //Select (sub)font for character
            Font f = textUtil.selectFontForChar(paintChar);
            char mapped = f.mapChar(ch);
            boolean fontChanging = textUtil.isFontChanging(f, mapped);
            if (fontChanging) {
                flushCurrentRun = true;
            }

            if (flushCurrentRun) {
                //Paint the current run and reset for the next run
                psRun.paint(ps, textUtil, tpi);
                psRun.reset();
            }

            //Track current run
            psRun.addCharacter(paintChar, relPos);
            psRun.noteStartingTransformation(localTransform);

            //Change font if necessary
            if (fontChanging) {
                textUtil.setCurrentFont(f, mapped);
            }

            //Update last position
            prevPos = glyphPos;
        }
        psRun.paint(ps, textUtil, tpi);
        gen.writeln("ET"); //endTextObject()
        gen.restoreGraphicsState();

        if (DEBUG) {
            //Paint debug shapes
            g2d.setStroke(new BasicStroke(0));
            g2d.setColor(Color.LIGHT_GRAY);
View Full Code Here

            }
        }

        private void paintXYShow(PSGraphics2D g2d, TextUtil textUtil, Paint paint,
                boolean x, boolean y) throws IOException {
            PSGenerator gen = textUtil.gen;
            char firstChar = this.currentChars.charAt(0);
            //Font only has to be setup up before the first character
            Font f = textUtil.selectFontForChar(firstChar);
            char mapped = f.mapChar(firstChar);
            textUtil.selectFont(f, mapped);
            textUtil.setCurrentFont(f, mapped);
            applyColor(paint, gen);

            FontMetrics metrics = f.getFontMetrics();
            boolean multiByte = metrics instanceof MultiByteFont
                    || metrics instanceof LazyFont
                            && ((LazyFont) metrics).getRealFont() instanceof MultiByteFont;
            StringBuffer sb = new StringBuffer();
            sb.append(multiByte ? '<' : '(');
            for (int i = 0, c = this.currentChars.length(); i < c; i++) {
                char ch = this.currentChars.charAt(i);
                mapped = f.mapChar(ch);
                if (multiByte) {
                    sb.append(HexEncoder.encode(mapped));
                } else {
                    char codepoint = (char) (mapped % 256);
                    PSGenerator.escapeChar(codepoint, sb);
                }
            }
            sb.append(multiByte ? '>' : ')');
            if (x || y) {
                sb.append("\n[");
                int idx = 0;
                Iterator iter = this.relativePositions.iterator();
                while (iter.hasNext()) {
                    Point2D pt = (Point2D)iter.next();
                    if (idx > 0) {
                        if (x) {
                            sb.append(format(gen, pt.getX()));
                        }
                        if (y) {
                            if (x) {
                                sb.append(' ');
                            }
                            sb.append(format(gen, -pt.getY()));
                        }
                        if (idx % 8 == 0) {
                            sb.append('\n');
                        } else {
                            sb.append(' ');
                        }
                    }
                    idx++;
                }
                if (x) {
                    sb.append('0');
                }
                if (y) {
                    if (x) {
                        sb.append(' ');
                    }
                    sb.append('0');
                }
                sb.append(']');
            }
            sb.append(' ');
            if (x) {
                sb.append('x');
            }
            if (y) {
                sb.append('y');
            }
            sb.append("show"); // --> xshow, yshow or xyshow
            gen.writeln(sb.toString());
        }
View Full Code Here

            }
        }

        private void paintStrokedGlyphs(PSGraphics2D g2d, TextUtil textUtil,
                Paint strokePaint, Stroke stroke) throws IOException {
            PSGenerator gen = textUtil.gen;

            applyColor(strokePaint, gen);
            PSGraphics2D.applyStroke(stroke, gen);

            Font f = null;
            Iterator iter = this.relativePositions.iterator();
            iter.next();
            Point2D pos = new Point2D.Double(0, 0);
            gen.writeln("0 0 M");
            for (int i = 0, c = this.currentChars.length(); i < c; i++) {
                char ch = this.currentChars.charAt(0);
                if (i == 0) {
                    //Font only has to be setup up before the first character
                    f = textUtil.selectFontForChar(ch);
                }
                char mapped = f.mapChar(ch);
                if (i == 0) {
                    textUtil.selectFont(f, mapped);
                    textUtil.setCurrentFont(f, mapped);
                }
                //add glyph outlines to current path
                mapped = f.mapChar(this.currentChars.charAt(i));
                FontMetrics metrics = f.getFontMetrics();
                boolean multiByte = metrics instanceof MultiByteFont
                        || metrics instanceof LazyFont
                                && ((LazyFont) metrics).getRealFont() instanceof MultiByteFont;
                if (multiByte) {
                    gen.write('<');
                    gen.write(HexEncoder.encode(mapped));
                    gen.write('>');
                } else {
                    char codepoint = (char)(mapped % 256);
                    gen.write("(" + codepoint + ")");
                }
                gen.writeln(" false charpath");

                if (iter.hasNext()) {
                    //Position for the next character
                    Point2D pt = (Point2D)iter.next();
                    pos.setLocation(pos.getX() + pt.getX(), pos.getY() - pt.getY());
                    gen.writeln(gen.formatDouble5(pos.getX()) + " "
                            + gen.formatDouble5(pos.getY()) + " M");
                }
            }
            gen.writeln("stroke"); //paints all accumulated glyph outlines
        }
View Full Code Here

    private static final ImageFlavor[] FLAVORS = new ImageFlavor[] {ImageFlavor.RAW_PNG};

    /** {@inheritDoc} */
    public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException {
        PSRenderingContext psContext = (PSRenderingContext) context;
        PSGenerator gen = psContext.getGenerator();
        ImageRawPNG png = (ImageRawPNG) image;

        float x = (float) pos.getX() / 1000f;
        float y = (float) pos.getY() / 1000f;
        float w = (float) pos.getWidth() / 1000f;
View Full Code Here

    /** {@inheritDoc} */
    public void generateForm(RenderingContext context, Image image, PSImageFormResource form)
            throws IOException {
        PSRenderingContext psContext = (PSRenderingContext) context;
        PSGenerator gen = psContext.getGenerator();
        ImageRawPNG png = (ImageRawPNG) image;
        ImageInfo info = image.getInfo();
        String imageDescription = info.getMimeType() + " " + info.getOriginalURI();

        ImageEncoder encoder = new ImageEncoderPNG(png);
View Full Code Here

    public void process(InputStream in, OutputStream out,
            int pageCount, Rectangle2D documentBoundingBox)
                    throws DSCException, IOException {
        DSCParser parser = new DSCParser(in);

        PSGenerator gen = new PSGenerator(out);
        parser.addListener(new DefaultNestedDocumentHandler(gen));
        parser.addListener(new IncludeResourceListener(gen));

        //Skip DSC header
        DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser);
        header.generate(gen);

        parser.setFilter(new DSCFilter() {
            private final Set filtered = new java.util.HashSet();
            {
                //We rewrite those as part of the processing
                filtered.add(DSCConstants.PAGES);
                filtered.add(DSCConstants.BBOX);
                filtered.add(DSCConstants.HIRES_BBOX);
                filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES);
                filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES);
            }
            public boolean accept(DSCEvent event) {
                if (event.isDSCComment()) {
                    //Filter %%Pages which we add manually from a parameter
                    return !(filtered.contains(event.asDSCComment().getName()));
                } else {
                    return true;
                }
            }
        });

        //Get PostScript language level (may be missing)
        while (true) {
            DSCEvent event = parser.nextEvent();
            if (event == null) {
                reportInvalidDSC();
            }
            if (DSCTools.headerCommentsEndHere(event)) {
                //Set number of pages
                DSCCommentPages pages = new DSCCommentPages(pageCount);
                pages.generate(gen);
                new DSCCommentBoundingBox(documentBoundingBox).generate(gen);
                new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen);

                PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts());
                registerSuppliedForms(resTracker, globalFormResources);

                //Supplied Resources
                DSCCommentDocumentSuppliedResources supplied
                    = new DSCCommentDocumentSuppliedResources(
                            resTracker.getDocumentSuppliedResources());
                supplied.generate(gen);

                //Needed Resources
                DSCCommentDocumentNeededResources needed
                    = new DSCCommentDocumentNeededResources(
                            resTracker.getDocumentNeededResources());
                needed.generate(gen);

                //Write original comment that ends the header comments
                event.generate(gen);
                break;
            }
            if (event.isDSCComment()) {
                DSCComment comment = event.asDSCComment();
                if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) {
                    DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment;
                    gen.setPSLevel(level.getLanguageLevel());
                }
            }
            event.generate(gen);
        }

        //Skip to the FOPFontSetup
        PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen);
        if (fontSetupPlaceholder == null) {
            throw new DSCException("Didn't find %FOPFontSetup comment in stream");
        }
        PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts(), eventProducer);
        generateForms(globalFormResources, gen);

        //Skip the prolog and to the first page
        DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen);
        if (pageOrTrailer == null) {
            throw new DSCException("Page expected, but none found");
        }

        //Process individual pages (and skip as necessary)
        while (true) {
            DSCCommentPage page = (DSCCommentPage)pageOrTrailer;
            page.generate(gen);
            pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen);
            if (pageOrTrailer == null) {
                reportInvalidDSC();
            } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) {
                pageOrTrailer.generate(gen);
                break;
            }
        }

        //Write the rest
        while (parser.hasNext()) {
            DSCEvent event = parser.nextEvent();
            event.generate(gen);
        }
        gen.flush();
    }
View Full Code Here

        //Color and Font state
        g2d.establishColor(g2d.getColor());
        establishCurrentFont();

        PSGenerator gen = getPSGenerator();
        gen.saveGraphicsState();

        //Clip
        Shape imclip = g2d.getClip();
        g2d.writeClip(imclip);

        //Prepare correct transformation
        AffineTransform trans = g2d.getTransform();
        gen.concatMatrix(trans);
        gen.writeln(gen.formatDouble(x) + " "
                  + gen.formatDouble(y) + " moveto ");
        gen.writeln("1 -1 scale");

        StringBuffer sb = new StringBuffer("(");
        escapeText(s, sb);
        sb.append(") t ");

        gen.writeln(sb.toString());

        gen.restoreGraphicsState();
    }
View Full Code Here

    }

    private void establishCurrentFont() throws IOException {
        if ((currentFontName != this.font.getFontName())
                || (currentFontSize != this.font.getFontSize())) {
            PSGenerator gen = getPSGenerator();
            gen.writeln("/" + this.font.getFontTriplet().getName() + " "
                    + gen.formatDouble(font.getFontSize() / 1000f) + " F");
            currentFontName = this.font.getFontName();
            currentFontSize = this.font.getFontSize();
        }
    }
View Full Code Here

    protected void renderSVGDocument(RendererContext context,
            Document doc) {
        PSInfo psInfo = getPSInfo(context);
        int xOffset = psInfo.currentXPosition;
        int yOffset = psInfo.currentYPosition;
        PSGenerator gen = psInfo.psGenerator;

        boolean paintAsBitmap = false;
        if (context != null) {
            Map foreign = (Map)context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES);
            paintAsBitmap = ImageHandlerUtil.isConversionModeBitmap(foreign);
        }
        if (paintAsBitmap) {
            try {
                super.renderSVGDocument(context, doc);
            } catch (IOException ioe) {
                SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                        context.getUserAgent().getEventBroadcaster());
                eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc));
            }
            return;
        }

        //Controls whether text painted by Batik is generated using text or path operations
        boolean strokeText = false;
        Configuration cfg = psInfo.getHandlerConfiguration();
        if (cfg != null) {
            strokeText = cfg.getChild("stroke-text", true).getValueAsBoolean(strokeText);
        }

        SVGUserAgent ua
             = new SVGUserAgent(context.getUserAgent(), new AffineTransform());

        PSGraphics2D graphics = new PSGraphics2D(strokeText, gen);
        graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());

        BridgeContext ctx = new PSBridgeContext(ua,
                (strokeText ? null : psInfo.fontInfo),
                context.getUserAgent().getFactory().getImageManager(),
                context.getUserAgent().getImageSessionContext());

        //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine)
        //to it.
        Document clonedDoc = BatikUtil.cloneSVGDocument(doc);

        GraphicsNode root;
        try {
            GVTBuilder builder = new GVTBuilder();
            root = builder.build(ctx, clonedDoc);
        } catch (Exception e) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                    context.getUserAgent().getEventBroadcaster());
            eventProducer.svgNotBuilt(this, e, getDocumentURI(doc));
            return;
        }
        // get the 'width' and 'height' attributes of the SVG document
        float w = (float)ctx.getDocumentSize().getWidth() * 1000f;
        float h = (float)ctx.getDocumentSize().getHeight() * 1000f;

        float sx = psInfo.getWidth() / w;
        float sy = psInfo.getHeight() / h;

        ctx = null;

        try {
            gen.commentln("%FOPBeginSVG");
            gen.saveGraphicsState();
            /*
             * Clip to the svg area.
             * Note: To have the svg overlay (under) a text area then use
             * an fo:block-container
             */
            gen.writeln("newpath");
            gen.defineRect(xOffset / 1000f, yOffset / 1000f,
                    psInfo.getWidth() / 1000f, psInfo.getHeight() / 1000f);
            gen.writeln("clip");

            // transform so that the coordinates (0,0) is from the top left
            // and positive is down and to the right. (0,0) is where the
            // viewBox puts it.
            gen.concatMatrix(sx, 0, 0, sy, xOffset / 1000f, yOffset / 1000f);

            /*
            SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
            AffineTransform at = ViewBox.getPreserveAspectRatioTransform(svg,
                    psInfo.getWidth() / 1000f, psInfo.getHeight() / 1000f, ctx);
            if (!at.isIdentity()) {
                double[] vals = new double[6];
                at.getMatrix(vals);
                gen.concatMatrix(vals);
            }*/

            AffineTransform transform = new AffineTransform();
            // scale to viewbox
            transform.translate(xOffset, yOffset);
            gen.getCurrentState().concatMatrix(transform);
            try {
                root.paint(graphics);
            } catch (Exception e) {
                SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                        context.getUserAgent().getEventBroadcaster());
                eventProducer.svgRenderingError(this, e, getDocumentURI(doc));
            }

            gen.restoreGraphicsState();
            gen.commentln("%FOPEndSVG");
        } catch (IOException ioe) {
            SVGEventProducer eventProducer = SVGEventProducer.Provider.get(
                    context.getUserAgent().getEventBroadcaster());
            eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc));
        }
View Full Code Here

TOP

Related Classes of org.apache.xmlgraphics.ps.PSGenerator

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.