aboutsummaryrefslogtreecommitdiffstats
path: root/src/org/apache/fop/render/pdf/PDFRenderer.java
blob: bb62565aece22c7078849140a61dd1535fbf0c90 (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.pdf;

// FOP
import org.apache.fop.render.PrintRenderer;
import org.apache.fop.render.XMLHandler;
import org.apache.fop.render.RendererContext;
import org.apache.fop.fo.FOUserAgent;
import org.apache.fop.image.*;
import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.properties.*;
import org.apache.fop.datatypes.*;
import org.apache.fop.pdf.*;
import org.apache.fop.image.*;
import org.apache.fop.extensions.*;
import org.apache.fop.render.pdf.fonts.LazyFont;

import org.apache.fop.area.*;
import org.apache.fop.area.inline.*;
import org.apache.fop.area.inline.Character;
import org.apache.fop.layout.FontState;

import org.w3c.dom.Document;

// Java
import java.io.IOException;
import java.io.OutputStream;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.util.HashMap;
import java.util.List;

/*
TODO:

viewport clipping
word rendering and optimistion
pdf state optimisation
line and border
leader
background pattern
user agent xml (svg) rendering
orientation
writing mode
text decoration

 */

/**
 * Renderer that renders areas to PDF
 *
 */
public class PDFRenderer extends PrintRenderer {
    public static final String mimeType = "application/pdf";

    /**
     * the PDF Document being created
     */
    protected PDFDocument pdfDoc;

    // map of pages using the PageViewport as the key
    // this is used for prepared pages that cannot be immediately
    // rendered
    protected HashMap pages = null;

    // page references are stored using the PageViewport as the key
    // when a reference is made the PageViewport is used
    // for pdf this means we need the pdf page reference
    protected HashMap pageReferences = new HashMap();

    protected String producer;

    protected OutputStream ostream;

    /**
     * the /Resources object of the PDF document being created
     */
    protected PDFResources pdfResources;

    /**
     * the current stream to add PDF commands to
     */
    PDFStream currentStream;

    /**
     * the current annotation list to add annotations to
     */
    PDFAnnotList currentAnnotList;

    /**
     * the current page to add annotations to
     */
    PDFPage currentPage;

    // drawing state
    PDFState currentState = null;

    PDFColor currentColor;
    String currentFontName = "";
    int currentFontSize = 0;
    int pageHeight;

    /**
     * true if a TJ command is left to be written
     */
    boolean textOpen = false;

    /**
     * the previous Y coordinate of the last word written.
     * Used to decide if we can draw the next word on the same line.
     */
    int prevWordY = 0;

    /**
     * the previous X coordinate of the last word written.
     * used to calculate how much space between two words
     */
    int prevWordX = 0;

    /**
     * The width of the previous word. Used to calculate space between
     */
    int prevWordWidth = 0;

    /**
     * reusable word area string buffer to reduce memory usage
     */
    private StringBuffer _wordAreaPDF = new StringBuffer();

    /**
     * create the PDF renderer
     */
    public PDFRenderer() {
    }

    /**
     * set the PDF document's producer
     *
     * @param producer string indicating application producing PDF
     */
    public void setProducer(String prod) {
        producer = prod;
    }

    public void setUserAgent(FOUserAgent agent) {
        super.setUserAgent(agent);
        PDFXMLHandler xmlHandler = new PDFXMLHandler();
        //userAgent.setDefaultXMLHandler(mimeType, xmlHandler);
        String svg = "http://www.w3.org/2000/svg";
        userAgent.addXMLHandler(mimeType, svg, xmlHandler);
    }

    public void startRenderer(OutputStream stream) throws IOException {
        ostream = stream;
        this.pdfDoc = new PDFDocument();
        this.pdfDoc.setProducer(producer);
        pdfDoc.outputHeader(stream);
    }

    public void stopRenderer() throws IOException {
        FontSetup.addToResources(pdfDoc, pdfDoc.getResources(), fontInfo);
        pdfDoc.outputTrailer(ostream);

        this.pdfDoc = null;
        ostream = null;
    }

    public boolean supportsOutOfOrder() {
        return true;
    }

    /**
     * The pdf page is prepared by making the page.
     * The page is made in the pdf document without any contents
     * and then stored to add the contents later.
     * The page objects is stored using the area tree PageViewport
     * as a key.
     */
    public void preparePage(PageViewport page) {
        this.pdfResources = this.pdfDoc.getResources();
    
        Rectangle2D bounds = page.getViewArea();
        double w = bounds.getWidth();
        double h = bounds.getHeight();
        currentPage = this.pdfDoc.makePage(this.pdfResources,
                                           (int) Math.round(w / 1000), (int) Math.round(h / 1000));
        if(pages == null) {
            pages = new HashMap();
        }
        pages.put(page, currentPage);
        pageReferences.put(page, currentPage.referencePDF());
    }

    /**
     * This method creates a pdf stream for the current page
     * uses it as the contents of a new page. The page is written
     * immediately to the output stream.
     */
    public void renderPage(PageViewport page) throws IOException,
    FOPException {
        if(pages != null && (currentPage = (PDFPage)pages.get(page)) != null) {
            pages.remove(page);
        } else {
            this.pdfResources = this.pdfDoc.getResources();
            Rectangle2D bounds = page.getViewArea();
            double w = bounds.getWidth();
            double h = bounds.getHeight();
            pageHeight = (int)h;
            currentPage = this.pdfDoc.makePage(this.pdfResources, 
                                           (int) Math.round(w / 1000), (int) Math.round(h / 1000));
            pageReferences.put(page, currentPage.referencePDF());
        }
        currentStream = this.pdfDoc.makeStream(PDFStream.CONTENT_FILTER, false);

        currentState = new PDFState();
        currentState.setTransform(new AffineTransform(1, 0, 0, -1, 0, (int) Math.round(pageHeight / 1000)));
	// Transform origin at top left to origin at bottom left
	currentStream.add("1 0 0 -1 0 " +
			  (int) Math.round(pageHeight / 1000) + " cm\n");
        //currentStream.add("BT\n");

        Page p = page.getPage();
        renderPageAreas(p);

        //currentStream.add("ET\n");

        this.pdfDoc.addStream(currentStream);
        currentPage.setContents(currentStream);
        this.pdfDoc.addPage(currentPage);
        this.pdfDoc.output(ostream);
    }


    protected void startVParea(CTM ctm) {
	// Set the given CTM in the graphics state
        currentState.push();
        currentState.setTransform(new AffineTransform(ctm.toArray()));

	currentStream.add("q\n");
	// multiply with current CTM
	currentStream.add(ctm.toPDFctm() + " cm\n");
	// Set clip?
  currentStream.add("BT\n");
    }

    protected void endVParea() {
  currentStream.add("ET\n");
	currentStream.add("Q\n");
        currentState.pop();
    }

    protected void renderRegion(RegionReference region) {
	// Draw a rectangle so we can see it!
	// x=0,y=0,w=ipd,h=bpd
	super.renderRegion(region);
    }

    protected void renderLineArea(LineArea line) {
	super.renderLineArea(line);
	closeText();
    }

    public void renderCharacter(Character ch) {

        super.renderCharacter(ch);
    }

    public void renderWord(Word word) {
            StringBuffer pdf = new StringBuffer();

            FontState fs = null;

	    fs = (FontState)word.getTrait(Trait.FONT_STATE);
            String name = fs.getFontName();
            int size = fs.getFontSize();

            // This assumes that *all* CIDFonts use a /ToUnicode mapping
            Font f = (Font)fs.getFontInfo().getFonts().get(name);
            boolean useMultiByte = f.isMultiByte();

            // String startText = useMultiByte ? "<FEFF" : "(";
            String startText = useMultiByte ? "<" : "(";
            String endText = useMultiByte ? "> " : ") ";

            updateFont(name, size, pdf);
            updateColor(true, pdf);

            int rx = currentBlockIPPosition;
            // int bl = pageHeight - currentBPPosition;
            int bl = currentBPPosition + word.getOffset();

            // Set letterSpacing
            //float ls = fs.getLetterSpacing() / this.currentFontSize;
            //pdf.append(ls).append(" Tc\n");

            if (!textOpen || bl != prevWordY) {
                closeText();

                pdf.append("1 0 0 -1 " + (rx / 1000f) + " " + (bl / 1000f)
                           + " Tm [" + startText);
                prevWordY = bl;
                textOpen = true;
            } else {
                // express the space between words in thousandths of an em
                int space = prevWordX - rx + prevWordWidth;
                float emDiff = (float)space / (float)currentFontSize * 1000f;
                // this prevents a problem in Acrobat Reader and other viewers
                // where large numbers cause text to disappear or default to
                // a limit
                if (emDiff < -33000) {
                    closeText();

                    pdf.append("1 0 0 1 " + (rx / 1000f) + " " + (bl / 1000f)
                               + " Tm [" + startText);
                    textOpen = true;
                } else {
                    pdf.append(Float.toString(emDiff));
                    pdf.append(" ");
                    pdf.append(startText);
                }
            }
            prevWordWidth = word.getWidth();
            prevWordX = rx;

        String s = word.getWord();

        escapeText(s, fs, useMultiByte, pdf);
        pdf.append(endText);

        currentStream.add(pdf.toString());

        super.renderWord(word);
    }

    public void escapeText(String s, FontState fs, boolean useMultiByte, StringBuffer pdf) {
        String startText = useMultiByte ? "<" : "(";
        String endText = useMultiByte ? "> " : ") ";

        boolean kerningAvailable = false;
        HashMap kerning = null;
        kerning = fs.getKerning();
        if (kerning != null &&!kerning.isEmpty()) {
            kerningAvailable = true;
        }

        int l = s.length();

        for (int i = 0; i < l; i++) {
            char ch = fs.mapChar(s.charAt(i));

            if (!useMultiByte) {
                if (ch > 127) {
                    pdf.append("\\");
                    pdf.append(Integer.toOctalString((int)ch));
                } else {
                    switch (ch) {
                        case '(':
                        case ')':
                        case '\\':
                            pdf.append("\\");
                            break;
                    }
                    pdf.append(ch);
                }
            } else {
                pdf.append(getUnicodeString(ch));
            }

            if (kerningAvailable && (i + 1) < l) {
                addKerning(pdf, (new Integer((int)ch)),
                           (new Integer((int)fs.mapChar(s.charAt(i + 1)))),
                           kerning, startText, endText);
            }
        }
    }

    /**
     * Convert a char to a multibyte hex representation
     */
    private String getUnicodeString(char c) {
        StringBuffer buf = new StringBuffer(4);

        byte[] uniBytes = null;
        try {
            char[] a = {c};
            uniBytes = new String(a).getBytes("UnicodeBigUnmarked");
        } catch (java.io.UnsupportedEncodingException e) {
            // This should never fail
        }

        for (int i = 0; i < uniBytes.length; i++) {
            int b = (uniBytes[i] < 0) ? (int)(256 + uniBytes[i])
                    : (int)uniBytes[i];

            String hexString = Integer.toHexString(b);
            if (hexString.length() == 1)
                buf = buf.append("0" + hexString);
            else
                buf = buf.append(hexString);
        }
        return buf.toString();
    }

    private void addKerning(StringBuffer buf, Integer ch1, Integer ch2,
                            HashMap kerning, String startText,
                            String endText) {
        HashMap kernPair = (HashMap)kerning.get(ch1);

        if (kernPair != null) {
            Integer width = (Integer)kernPair.get(ch2);
            if (width != null) {
                buf.append(endText).append(-(width.intValue())).append(' ').append(startText);
            }
        }
    }

    /**
     * Checks to see if we have some text rendering commands open
     * still and writes out the TJ command to the stream if we do
     */
    private void closeText() {
        if (textOpen) {
            currentStream.add("] TJ\n");
            textOpen = false;
            prevWordX = 0;
            prevWordY = 0;
        }
    }

    private void updateColor(boolean fill, StringBuffer pdf) {
        /*PDFColor areaColor = null;
        if (this.currentFill instanceof PDFColor) {
            areaColor = (PDFColor)this.currentFill;
        }

        if (areaColor == null || areaColor.red() != (double)area.getRed()
                || areaColor.green() != (double)area.getGreen()
                || areaColor.blue() != (double)area.getBlue()) {

            areaColor = new PDFColor((double)area.getRed(),
                                     (double)area.getGreen(),
                                     (double)area.getBlue());

            closeText();
            this.currentFill = areaColor;
            pdf.append(this.currentFill.getColorSpaceOut(true));
        }*/
    }

    private void updateFont(String name, int size, StringBuffer pdf) {
        if ((!name.equals(this.currentFontName))
                || (size != this.currentFontSize)) {
            closeText();

            this.currentFontName = name;
            this.currentFontSize = size;
            pdf = pdf.append("/" + name + " " + ((float)size / 1000f) + " Tf\n");
        }
    }

    public void renderImage(Image image, Rectangle2D pos) {
        String url = image.getURL();

        PDFXObject xobject = pdfDoc.getImage(url);
        if(xobject != null) {
            int w = (int)pos.getWidth() / 1000;
            int h = (int)pos.getHeight() / 1000;
            placeImage((int)pos.getX() / 1000, (int)pos.getY() / 1000, w, h, xobject.getXNumber());
            return;
        }

        ImageFactory fact = ImageFactory.getInstance();
        FopImage fopimage = fact.getImage(url, userAgent);
        if(fopimage == null) {
            return;
        }
        if(!fopimage.load(FopImage.DIMENSIONS, userAgent)) {
            return;
        }
        String mime = fopimage.getMimeType();
        if("text/xml".equals(mime)) {
            if(!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
                return;
            }
            Document doc = ((XMLImage)fopimage).getDocument();
            String ns = ((XMLImage)fopimage).getNameSpace();

            renderDocument(doc, ns, pos);
        } else if("image/svg+xml".equals(mime)) {
            if(!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
                return;
            }
            Document doc = ((XMLImage)fopimage).getDocument();
            String ns = ((XMLImage)fopimage).getNameSpace();

            renderDocument(doc, ns, pos);
        } else if("image/eps".equals(mime)) {
            if(!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
                return;
            }
            FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
            int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
            fact.releaseImage(url, userAgent);
        } else if("image/jpg".equals(mime)) {
            if(!fopimage.load(FopImage.ORIGINAL_DATA, userAgent)) {
                return;
            }
            FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
            int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
            fact.releaseImage(url, userAgent);

            int w = (int)pos.getWidth() / 1000;
            int h = (int)pos.getHeight() / 1000;
            placeImage((int)pos.getX() / 1000, (int)pos.getY() / 1000, w, h, xobj);
        } else {
            if(!fopimage.load(FopImage.BITMAP, userAgent)) {
                return;
            }
            FopPDFImage pdfimage = new FopPDFImage(fopimage, url);
            int xobj = pdfDoc.addImage(null, pdfimage).getXNumber();
            fact.releaseImage(url, userAgent);

            int w = (int)pos.getWidth() / 1000;
            int h = (int)pos.getHeight() / 1000;
            placeImage((int)pos.getX() / 1000, (int)pos.getY() / 1000, w, h, xobj);
        }

        // output new data
        try {
            this.pdfDoc.output(ostream);
        } catch(IOException ioe) {

        }
    }

    protected void placeImage(int x, int y, int w, int h, int xobj) {
            currentStream.add("q\n" + ((float)w) + " 0 0 "
                              + ((float)-h) + " "
                              + (((float)currentBlockIPPosition) / 1000f + x) + " "
                              + (((float)(currentBPPosition + 1000 * h)) / 1000f + y) + " cm\n" + "/Im"
                              + xobj + " Do\nQ\n");

    }

    public void renderForeignObject(ForeignObject fo, Rectangle2D pos) {
        Document doc = fo.getDocument();
        String ns = fo.getNameSpace();
        renderDocument(doc, ns, pos);
    }

    public void renderDocument(Document doc, String ns, Rectangle2D pos) {
        RendererContext context;
        context = new RendererContext(mimeType);
        context.setUserAgent(userAgent);

        context.setProperty(PDFXMLHandler.PDF_DOCUMENT, pdfDoc);
        context.setProperty(PDFXMLHandler.OUTPUT_STREAM, ostream);
        context.setProperty(PDFXMLHandler.PDF_STATE, currentState);
        context.setProperty(PDFXMLHandler.PDF_PAGE, currentPage);
        context.setProperty(PDFXMLHandler.PDF_STREAM, currentStream);
        context.setProperty(PDFXMLHandler.PDF_XPOS, new Integer(currentBlockIPPosition + (int)pos.getX()));
        context.setProperty(PDFXMLHandler.PDF_YPOS, new Integer(currentBPPosition + (int)pos.getY()));
        FontState fs = null;
            try {
                fs = new FontState(fontInfo, "Helvetica", "",
                                          "", 12 * 1000, 0);
            } catch (org.apache.fop.apps.FOPException fope) {
                fope.printStackTrace();
            }

        context.setProperty(PDFXMLHandler.PDF_FONT_STATE, fs);
        context.setProperty(PDFXMLHandler.PDF_FONT_NAME, currentFontName);
        context.setProperty(PDFXMLHandler.PDF_FONT_SIZE, new Integer(currentFontSize));
        context.setProperty(PDFXMLHandler.PDF_WIDTH, new Integer((int)pos.getWidth()));
        context.setProperty(PDFXMLHandler.PDF_HEIGHT, new Integer((int)pos.getHeight()));
        userAgent.renderXML(context, doc, ns);

    }

    public void renderViewport(Viewport viewport) {
        closeText();
        currentStream.add("ET\n");
        if (viewport.getClip()) {
            currentStream.add("q\n");

            float x = currentBlockIPPosition / 1000f;
            float y = (currentBPPosition + viewport.getOffset()) / 1000f;
            float width = viewport.getWidth() / 1000f;
            float height = viewport.getHeight() / 1000f;
            currentStream.add(x + " " + y + " m\n");
            currentStream.add((x + width) + " " + y + " l\n");
            currentStream.add((x + width) + " " + (y + height) + " l\n");
            currentStream.add(x + " " + (y + height) + " l\n");
            currentStream.add("h\n");
            currentStream.add("W\n");
            currentStream.add("n\n");
        }
        super.renderViewport(viewport);

        if (viewport.getClip()) {
            currentStream.add("Q\n");
        }
        currentStream.add("BT\n");
    }

    public void renderLeader(Leader area) {
        currentStream.add("ET\n");
        currentStream.add((((float)currentBlockIPPosition) / 1000f) + " "
                          + ((currentBPPosition + area.getOffset()) / 1000f) + " m\n");
        currentStream.add(((currentBlockIPPosition + area.getWidth()) / 1000f) + " " + ((currentBPPosition + area.getOffset()) / 1000f) + " l\n");
        currentStream.add("S\n");
        currentStream.add("BT\n");
        super.renderLeader(area);
    }
}