aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/apache/fop/render/svg/SVGRenderer.java
blob: 0a9e1d34e5175b6e70d42ffb55257b2bb7fc3646 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
/*
 * $Id$
 * Copyright (C) 2001 The Apache Software Foundation. All rights reserved.
 * For details on use and redistribution please refer to the
 * LICENSE file included with these sources.
 */

package org.apache.fop.render.svg;

import org.apache.fop.layout.*;
import org.apache.fop.layout.inline.*;
import org.apache.fop.datatypes.IDReferences;
import org.apache.fop.datatypes.ColorType;
import org.apache.fop.image.*;
import org.apache.fop.svg.SVGArea;
import org.apache.fop.svg.SVGUtilities;

import org.w3c.dom.Node;
import org.w3c.dom.ProcessingInstruction;
import org.w3c.dom.svg.SVGSVGElement;
import org.w3c.dom.svg.SVGDocument;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.DOMImplementation;

import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.dom.svg.SVGOMElement;
import org.apache.batik.dom.util.XMLSupport;
import org.apache.batik.transcoder.svg2svg.SVGTranscoder;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.TranscoderException;

import java.awt.Color;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.geom.Rectangle2D;
import java.util.Hashtable;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.OutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.swing.ImageIcon;

import org.apache.fop.render.AbstractRenderer;

public class SVGRenderer extends AbstractRenderer {
    static final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document svgDocument;
    Element svgRoot;
    Element currentPageG = null;
    Element lastLink = null;

    float totalWidth = 0;
    float totalHeight = 0;

    protected int pageWidth = 0;
    protected int pageHeight = 0;
    protected int pageNumber = 0;

    protected Hashtable fontNames = new Hashtable();
    protected Hashtable fontStyles = new Hashtable();
    protected Color saveColor = null;

    protected IDReferences idReferences = null;

    /**
     * The current (internal) font name
     */
    protected String currentFontName;

    /**
     * The current font size in millipoints
     */
    protected int currentFontSize;

    /**
     * The current colour's red, green and blue component
     */
    protected float currentRed = 0;
    protected float currentGreen = 0;
    protected float currentBlue = 0;

    /**
     * options
     */
    protected Hashtable options;

    /**
     * set up renderer options
     */
    public void setOptions(Hashtable options) {
        this.options = options;
    }

    public SVGRenderer() {
    }

    /**
     * add a line to the current stream
     *
     * @param x1 the start x location in millipoints
     * @param y1 the start y location in millipoints
     * @param x2 the end x location in millipoints
     * @param y2 the end y location in millipoints
     * @param th the thickness in millipoints
     * @param r the red component
     * @param g the green component
     * @param b the blue component
     */
    protected void addLine(int x1, int y1, int x2, int y2, int th, float r,
                           float g, float b) {
        Element line = SVGUtilities.createLine(svgDocument, x1 / 1000f, pageHeight - (y1 / 1000f), x2 / 1000f, pageHeight - (y2 / 1000f));
        line.setAttributeNS(null, "style", "stroke-width:" + (Math.abs(th) / 1000f)
                            + ";stroke:rgb(" + ((int)(255 * r)) + "," + ((int)(255 * g)) + "," + ((int)(255 * b)) + ")");
        currentPageG.appendChild(line);
    }

    /**
     * draw a rectangle
     *
     * @param x the x position of left edge in millipoints
     * @param y the y position of top edge in millipoints
     * @param w the width in millipoints
     * @param h the height in millipoints
     * @param r the red component
     * @param g the green component
     * @param b the blue component
     */
    protected void addRect(int x, int y, int w, int h, float r, float g,
                           float b) {
        Element rect = SVGUtilities.createRect(svgDocument, x / 1000f, pageHeight - (y / 1000f), w / 1000f, h / 1000f);
        rect.setAttributeNS(null, "style", "stroke:rgb(" + ((int)(255 * r)) + "," + ((int)(255 * g)) + "," + ((int)(255 * b)) + ")");
        currentPageG.appendChild(rect);
    }

    /**
     * draw a filled rectangle
     *
     * @param x the x position of left edge in millipoints
     * @param y the y position of top edge in millipoints
     * @param w the width in millipoints
     * @param h the height in millipoints
     * @param r the red component of edges
     * @param g the green component of edges
     * @param b the blue component of edges
     * @param fr the red component of the fill
     * @param fg the green component of the fill
     * @param fb the blue component of the fill
     */
    protected void addRect(int x, int y, int w, int h, float r, float g,
                           float b, float fr, float fg, float fb) {
        Element rect = SVGUtilities.createRect(svgDocument, x / 1000f, pageHeight - (y / 1000f), w / 1000f, h / 1000f);
        rect.setAttributeNS(null, "style", "stroke:rgb(" + ((int)(255 * r)) + "," + ((int)(255 * g)) + "," + ((int)(255 * b)) + ");fill:rgb(" + ((int)(255 * fr)) + "," + ((int)(255 * fg)) + "," + ((int)(255 * fb)) + ")");
        currentPageG.appendChild(rect);
    }

    /**
     * draw a filled rectangle in the current color
     *
     * @param x the x position of left edge in millipoints
     * @param y the y position of top edge in millipoints
     * @param w the width in millipoints
     * @param h the height in millipoints
     * @param drawAsOutline true for draw, false for fill
     */
    protected void addRect(int x, int y, int w, int h,
                           boolean drawAsOutline) {
        int startx = (x + 500) / 1000;
        int starty = pageHeight - ((y + 500) / 1000);
        int endx = (x + w + 500) / 1000;
        int endy = pageHeight - ((y + h + 500) / 1000);
        if (drawAsOutline) {
            Element rect = SVGUtilities.createRect(svgDocument, startx, starty, endx - startx, endy - starty);
            rect.setAttributeNS(null, "style", "fill:none");
            currentPageG.appendChild(rect);
        } else {
            Element rect = SVGUtilities.createRect(svgDocument, startx, starty, endx - startx, starty - endy);
            rect.setAttributeNS(null, "style", "stroke:none");
            currentPageG.appendChild(rect);
        }
    }

    protected void addFilledRect(int x, int y, int w, int h,
                                 ColorType col) {
        float r = col.red();
        float g = col.green();
        float b = col.blue();
        addRect(x, y, w, h, r, g, b, r, g, b);
    }

    protected void drawFrame() {
        int width = pageWidth;
        int height = pageHeight;
        Element rect = SVGUtilities.createRect(svgDocument, 0, 0, width, height);
        rect.setAttributeNS(null, "style", "fill:none;stroke:black");
        currentPageG.appendChild(rect);
    }

    public void render(Page page, OutputStream stream)
    throws IOException {
        pageNumber++;
        this.render(page);
    }

    public void render(Page page)
    throws IOException {
        idReferences = page.getIDReferences();

        int lastWidth = pageWidth;
        int lastHeight = pageHeight;

        pageWidth = (int)((float)page.getWidth() / 1000f + .5);
        pageHeight = (int)((float)page.getHeight() / 1000f + .5);

        if(lastLink != null && currentPageG != null) {
            lastLink.setAttributeNS(null, "xlink:href", "#svgView(viewBox(0, "+ (totalHeight) + ", " + pageWidth + ", " + pageHeight + "))");
            currentPageG.appendChild(lastLink);
        }

        totalHeight += pageHeight;
        if(totalWidth < pageWidth) {
            totalWidth = pageWidth;
        }

        currentPageG = SVGUtilities.createG(svgDocument);
        currentPageG.setAttributeNS(null, "id", /*title + */"Page-" + pageNumber);
        currentPageG.setAttributeNS(null, "style", "font-family:sanserif;font-size:12");
        svgRoot.appendChild(currentPageG);

        drawFrame();

        renderPage(page);

        currentPageG.setAttributeNS(null, "transform", "translate(0," + (totalHeight - pageHeight) + ")");

        Element lastPageLink = svgDocument.createElementNS(svgNS, "a");
        if(lastLink != null) {
            lastPageLink.setAttributeNS(null, "xlink:href", "#svgView(viewBox(0, " + (totalHeight - pageHeight - lastHeight) + ", " + lastWidth + ", " + lastHeight + "))");
        } else {
            lastPageLink.setAttributeNS(null, "xlink:href", "#svgView(viewBox(0, " + (totalHeight - pageHeight) + ", " + pageWidth + ", " + pageHeight + "))");
        }
        currentPageG.appendChild(lastPageLink);
        Element rect = SVGUtilities.createRect(svgDocument, 0, 0, pageWidth / 2, pageHeight);
        rect.setAttributeNS(null, "style", "fill:blue;visibility:hidden");
        lastPageLink.appendChild(rect);

        lastLink = svgDocument.createElementNS(svgNS, "a");
        rect = SVGUtilities.createRect(svgDocument, pageWidth / 2, 0, pageWidth / 2, pageHeight);
        rect.setAttributeNS(null, "style", "fill:blue;visibility:hidden");
        lastLink.appendChild(rect);

        /*
         * if (page.hasLinks()) {
         * ....
         * }
         */

    }

    public void renderPage(Page page) {
        BodyAreaContainer body;
        AreaContainer before, after;

        body = page.getBody();
        before = page.getBefore();
        after = page.getAfter();

        this.currentFontName = "";
        this.currentFontSize = 0;

        renderBodyAreaContainer(body);

        if (before != null) {
            renderAreaContainer(before);
        }

        if (after != null) {
            renderAreaContainer(after);
        }
    }

    protected void doFrame(org.apache.fop.layout.Area area) {
        int w, h;
        int rx = this.currentAreaContainerXPosition;
        w = area.getContentWidth();

        if (area instanceof BlockArea) {
            rx += ((BlockArea)area).getStartIndent();
        }

        h = area.getContentHeight();
        int ry = this.currentYPosition;
        ColorType bg = area.getBackgroundColor();

        rx = rx - area.getPaddingLeft();
        ry = ry + area.getPaddingTop();
        w = w + area.getPaddingLeft() + area.getPaddingRight();
        h = h + area.getPaddingTop() + area.getPaddingBottom();

        // I'm not sure I should have to check for bg being null
        // but I do
        if ((bg != null) && (bg.alpha() == 0)) {
            this.addRect(rx, ry, w, h, bg.red(), bg.green(), bg.blue(),
                         bg.red(), bg.green(), bg.blue());
        }

        rx = rx - area.getBorderLeftWidth();
        ry = ry + area.getBorderTopWidth();
        w = w + area.getBorderLeftWidth() + area.getBorderRightWidth();
        h = h + area.getBorderTopWidth() + area.getBorderBottomWidth();

        BorderAndPadding bp = area.getBorderAndPadding();
        ColorType borderColor;

        if (area.getBorderTopWidth() != 0) {
            borderColor = bp.getBorderColor(BorderAndPadding.TOP);
            addLine(rx, ry, rx + w, ry, area.getBorderTopWidth(),
                    borderColor.red(), borderColor.green(),
                    borderColor.blue());
        }

        if (area.getBorderLeftWidth() != 0) {
            borderColor = bp.getBorderColor(BorderAndPadding.LEFT);
            addLine(rx, ry, rx, ry - h, area.getBorderLeftWidth(),
                    borderColor.red(), borderColor.green(),
                    borderColor.blue());
        }

        if (area.getBorderRightWidth() != 0) {
            borderColor = bp.getBorderColor(BorderAndPadding.RIGHT);
            addLine(rx + w, ry, rx + w, ry - h,
                    area.getBorderRightWidth(), borderColor.red(),
                    borderColor.green(),
                    borderColor.blue());
        }

        if (area.getBorderBottomWidth() != 0) {
            borderColor = bp.getBorderColor(BorderAndPadding.BOTTOM);
            addLine(rx, ry - h, rx + w, ry - h, area.getBorderBottomWidth(),
                    borderColor.red(), borderColor.green(),
                    borderColor.blue());
        }
    }

    protected Rectangle2D getBounds(org.apache.fop.layout.Area a) {
        return new Rectangle2D.Double(currentAreaContainerXPosition,
                                      currentYPosition,
                                      a.getAllocationWidth(), a.getHeight());
    }

    public void setupFontInfo(FontInfo fontInfo) {
        // create a temp Image to test font metrics on
        BufferedImage fontImage =
            new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
        org.apache.fop.render.awt.FontSetup.setup(fontInfo, fontImage.createGraphics());
    }

    public void renderDisplaySpace(DisplaySpace space) {
        int d = space.getSize();
        this.currentYPosition -= d;
    }

    public void renderImageArea(ImageArea area) {

        int x = currentXPosition + area.getXOffset();
        int y = currentYPosition;
        int w = area.getContentWidth();
        int h = area.getHeight();
        this.currentYPosition -= h;

        FopImage img = area.getImage();

        if (img == null) {
            log.error("Error while loading image : area.getImage() is null");

            addRect(x, y, w, h, true);    // use helper function

        } else {
            if (img instanceof SVGImage) {
                try {
                    SVGDocument svg = ((SVGImage)img).getSVGDocument();
                    renderSVGDocument(svg, x / 1000f, pageHeight - y / 1000f);
                } catch (FopImageException e) {}

            } else {

                String urlString = img.getURL();
                try {
                    URL url = new URL(urlString);

                    ImageIcon icon = new ImageIcon(url);
                    Image image = icon.getImage();

                    int startx = (x + 500) / 1000;
                    int starty = pageHeight - ((y + 500) / 1000);
                    int endx = (x + w + 500) / 1000;
                    int endy = pageHeight - ((y + h + 500) / 1000);

                    // reverse start and end y because h is positive
                    //graphics.drawImage(image, startx, starty, endx - startx,
                    //                   starty - endy, null);

                } catch (MalformedURLException mue) {
                    // cannot normally occur because, if URL is wrong, constructing FopImage
                    // will already have failed earlier on
                }
            }
        }

        this.currentXPosition += area.getContentWidth();
    }

    public void renderWordArea(WordArea area) {
        char ch;
        StringBuffer pdf = new StringBuffer();

        String name = area.getFontState().getFontFamily();
        int size = area.getFontState().getFontSize();
        boolean underlined = area.getUnderlined();

        float red = area.getRed();
        float green = area.getGreen();
        float blue = area.getBlue();

        if ((!name.equals(this.currentFontName))
                || (size != this.currentFontSize)) {
            this.currentFontName = name;
            this.currentFontSize = size;
        }

        if ((red != this.currentRed) || (green != this.currentGreen)
                || (blue != this.currentBlue)) {
            this.currentRed = red;
            this.currentGreen = green;
            this.currentBlue = blue;
        }

        int rx = this.currentXPosition;
        int bl = this.currentYPosition;

        String s;    // = area.getText();
        if (area.getPageNumberID()
                != null) {    // this text is a page number, so resolve it
            s = idReferences.getPageNumber(area.getPageNumberID());
            if (s == null) {
                s = "";
            }
        } else {
            s = area.getText();
        }

        if (saveColor != null) {
            if (saveColor.getRed() != red || saveColor.getGreen() != green
                    || saveColor.getBlue() != blue) {
                saveColor = new Color(red, green, blue);
            }
        } else {
            saveColor = new Color(red, green, blue);
        }

        Element text = SVGUtilities.createText(svgDocument, rx / 1000f, pageHeight - bl / 1000f, s);
        String st = null;
        if(!"sans-serif".equals(this.currentFontName)) {
            st = "font-family:" + this.currentFontName;
        }
        if(this.currentFontSize != 12000) {
            if(st == null) {
                st = "";
            } else {
                st += ";";
            }
            st += "font-size:" + (this.currentFontSize / 1000f);
        }
        if(red != 0 || green != 0 || blue != 0) {
            if(st == null) {
                st = "";
            } else {
                st += ";";
            }
            st += "fill:rgb(" + ((int)(255 * red)) + "," + ((int)(255 * green)) + "," + ((int)(255 * blue)) + ")";
        }
        String fweight = area.getFontState().getFontWeight();
        if(!"normal".equals(fweight)) {
            if(st == null) {
                st = "";
            } else {
                st += ";";
            }
            st += "font-weight:" + fweight;
        }
        String fstyle = area.getFontState().getFontStyle();
        if(!"normal".equals(fstyle)) {
            if(st == null) {
                st = "";
            } else {
                st += ";";
            }
            st += "font-style:" + fstyle;
        }

        if(st != null) {
            text.setAttributeNS(null, "style", st);
        }
        currentPageG.appendChild(text);

        this.currentXPosition += area.getContentWidth();
    }

    public void renderInlineSpace(InlineSpace space) {
        this.currentXPosition += space.getSize();
    }

    /**
     *
     * @param area area to render
     */
    public void renderLeaderArea(LeaderArea area) {

        int rx = this.currentXPosition;
        int ry = this.currentYPosition;
        int w = area.getLeaderLength();
        int h = area.getHeight();
        int th = area.getRuleThickness();
        int st = area.getRuleStyle();    // not used at the moment
        float r = area.getRed();
        float g = area.getGreen();
        float b = area.getBlue();

        //graphics.setColor(new Color(r, g, b));

        addRect(rx, ry, w, th, false);

        this.currentXPosition += area.getContentWidth();
    }

    public void renderSVGArea(SVGArea area) {

        float x = this.currentXPosition / 1000f;
        float y = pageHeight - this.currentYPosition / 1000f;
        int w = area.getContentWidth();
        int h = area.getHeight();

        Document doc = area.getSVGDocument();
        renderSVGDocument(doc, x, y);
        this.currentXPosition += area.getContentWidth();
    }

    protected void renderSVGDocument(Document doc, float x, float y) {
        SVGSVGElement svg = ((SVGDocument)doc).getRootElement();
        Element view = svgDocument.createElementNS(svgNS, "svg");
        Node newsvg = svgDocument.importNode(svg, true);
        //view.setAttributeNS(null, "viewBox", "0 0 ");
        view.setAttributeNS(null, "x", "" + x);
        view.setAttributeNS(null, "y", "" + y);

        // this fixes a problem where the xmlns is repeated sometimes
        Element ele = (Element)newsvg;
        ele.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns", svgNS);
        if(ele.hasAttributeNS(null, "xmlns")) {
           ele.removeAttributeNS(null, "xmlns");
        }

        view.appendChild(newsvg);
        currentPageG.appendChild(view);
    }

    public void setProducer(String producer) {
        // defined in Renderer Interface
    }

    public static Color colorType2Color(ColorType ct) {
        if (ct == null) {
            return null;
        }
        return new Color(ct.red(), ct.green(), ct.blue());
    }

    public void renderForeignObjectArea(ForeignObjectArea area) {
        area.getObject().render(this);
    }

    public void startRenderer(OutputStream outputStream)
              throws IOException {
        DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
        svgDocument = impl.createDocument(svgNS, "svg", null);
        ProcessingInstruction pi = 
                 svgDocument.createProcessingInstruction(
                         "xml",
                         " version=\"1.0\" encoding=\"ISO-8859-1\"");
				svgRoot = svgDocument.getDocumentElement();
        svgDocument.insertBefore(pi, svgRoot);
		}

    public void stopRenderer(OutputStream outputStream)
    throws IOException {
        svgRoot.setAttributeNS(null, "width", "" + totalWidth);
        svgRoot.setAttributeNS(null, "height", "" + totalHeight);
        //svgRoot.setAttributeNS(null, "viewBox", "0 0 " + pageWidth + " " + pageHeight);
        SVGTranscoder svgT = new SVGTranscoder();
        TranscoderInput input = new TranscoderInput(svgDocument);
        TranscoderOutput output = new TranscoderOutput(new OutputStreamWriter(outputStream));
        try {
            svgT.transcode(input, output);
        } catch(TranscoderException e) {
            log.error("could not write svg file :" + e.getMessage(), e);
        }
        outputStream.flush();

        svgDocument = null;
        svgRoot = null;
        currentPageG = null;
        lastLink = null;

        totalWidth = 0;
        totalHeight = 0;

        pageNumber = 0;
    }

}