Example usage for com.lowagie.text FontFactory registerDirectories

List of usage examples for com.lowagie.text FontFactory registerDirectories

Introduction

In this page you can find the example usage for com.lowagie.text FontFactory registerDirectories.

Prototype

public static int registerDirectories() 

Source Link

Document

Register fonts in some probable directories.

Usage

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {//  w  w w .  j av a  2 s  .  c o  m
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

License:Apache License

private void printGraphPdf(DocWriter writer, CanvasCommon canvas, Graph process, Rectangle page_size,
        String type, String filename, Chapter chapter, int chapter_number) throws Exception {
    Dimension graphsize = process.getGraphSize();
    // we create a fontMapper and read all the fonts in the font directory
    DefaultFontMapper mapper = new DefaultFontMapper();
    FontFactory.registerDirectories();
    mapper.insertDirectory("c:\\winnt\\fonts");
    // mapper.insertDirectory("c:\\windows\\fonts");
    // we create a template and a Graphics2D object that corresponds with it
    int w, h;/* w  w  w . ja  v a 2  s .c o  m*/
    float scale;
    if ((float) graphsize.width < page_size.getWidth() * 0.8
            && (float) graphsize.height < page_size.getHeight() * 0.8 || type.equals(HTML)) {
        w = graphsize.width + 36;
        h = graphsize.height + 36;
        scale = -1f;
    } else {
        scale = page_size.getWidth() * 0.8f / (float) graphsize.width;
        if (scale > page_size.getHeight() * 0.8f / (float) graphsize.height)
            scale = page_size.getHeight() * 0.8f / (float) graphsize.height;
        w = (int) (graphsize.width * scale) + 36;
        h = (int) (graphsize.height * scale) + 36;
    }
    Image img;
    int zoomSave = process.zoom;
    process.zoom = 100;
    Color bgsave = canvas.getBackground();
    boolean edsave = canvas.editable;
    canvas.editable = false;
    canvas.setBackground(Color.white);

    if (type.equals(PDF)) {
        PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
        PdfTemplate tp = cb.createTemplate(w, h);
        Graphics2D g2 = tp.createGraphics(w, h, mapper);
        if (scale > 0)
            g2.scale(scale, scale);
        tp.setWidth(w);
        tp.setHeight(h);
        canvas.paintComponent(g2);
        g2.dispose();
        // cb.addTemplate(tp, 50, 400);
        img = new ImgTemplate(tp);
    } else {
        String imgfilename = filename + "." + process.getName() + "_ch" + chapter_number + ".jpg";
        printImage(imgfilename, -1f, canvas, graphsize);
        img = Image.getInstance(imgfilename);
        if (scale > 0)
            img.scalePercent(scale * 100);
    }
    process.zoom = zoomSave;
    canvas.setBackground(bgsave);
    canvas.editable = edsave;
    if (img != null)
        chapter.add(img);
}

From source file:com.gtdfree.test.PDFTestFont.java

License:Open Source License

/**
 * Fonts and encoding./*from   w  w  w . j  a  v  a  2 s .  c o m*/
 * @param args no arguments needed
 */
public static void main(String[] args) {

    System.out.println("Encodings");

    String[] names = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();

    System.out.println(Arrays.toString(names));

    /*System.out.println("---");
    try {
    System.getProperties().store(System.out, "");
    } catch (IOException e1) {
    e1.printStackTrace();
    }
    System.out.println("---");*/
    //System.out.println(System.getenv());
    //System.out.println("---");

    //String font= System.getProperty("java.home")+"/lib/fonts/LucidaBrightRegular.ttf";
    //String font= "fonts/DejaVuSans.ttf";

    //byte[] ttf= ApplicationHelper.loadResource(font);

    try {
        // step 1
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        // step 2
        PdfWriter.getInstance(document, new FileOutputStream("encodingfont.pdf"));
        // step 3
        document.open();
        // step 4
        String all[] = { "Symbol", "ZapfDingbats" };
        Font hex = new Font(Font.HELVETICA, 5);
        for (int z = 0; z < all.length; ++z) {
            String file = all[z];
            document.add(new Paragraph(
                    "Unicode equivalence for the font \"" + file + "\" with the encoding \"" + file + "\"\n"));
            /*char tb[];
            if (z == 0)
               tb = SYMBOL_TABLE;
            else
               tb = DINGBATS_TABLE;*/
            BaseFont bf;
            if (z == 2) {
                bf = BaseFont.createFont(file, BaseFont.IDENTITY_H, BaseFont.EMBEDDED, true, null, null);
                ;
            } else {
                bf = BaseFont.createFont(file, file, true);
            }
            Font f = new Font(bf, 12);
            PdfPTable table = new PdfPTable(16);
            table.setWidthPercentage(100);
            table.getDefaultCell().setBorderWidth(1);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            for (char k = 0; k < Character.MAX_VALUE; ++k) {
                char c = k;
                if (bf.charExists(c)) {
                    Phrase ph = new Phrase(12, new String(new char[] { c }), f);
                    ph.add(new Phrase(12, "\n" + Integer.toString(c) + "\n" + cst(c), hex));
                    table.addCell(ph);
                } /*
                  else {
                     Phrase ph = new Phrase("\u00a0");
                     ph.add(new Phrase(12, "\n\n" + cst(c), hex));
                     table.addCell(ph);
                  }*/
            }
            document.add(table);
            document.newPage();
        }
        // step 5
        document.close();

        FontFactory.registerDirectories();

        Set<?> s = FontFactory.getRegisteredFonts();

        System.out.println("Fonts: " + s);

        s = FontFactory.getRegisteredFamilies();

        System.out.println("Families: " + s);

        ArrayList<Font> f = new ArrayList<Font>(s.size());

        for (Object name : s) {

            try {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", true, 12, Font.NORMAL, Color.BLACK, true));
            } catch (Exception e) {
                f.add(FontFactory.getFont(name.toString(), "UTF-8", false, 12, Font.NORMAL, Color.BLACK, true));
            }

        }

        Collections.sort(f, new Comparator<Font>() {
            @Override
            public int compare(Font o1, Font o2) {
                return o1.getFamilyname().compareTo(o2.getFamilyname());
            }
        });

        for (Font ff : f) {

            if (ff.getBaseFont() == null) {
                continue;
            }
            System.out.println(ff.getFamilyname() + " " + ff.getBaseFont().isEmbedded());

        }

    } catch (Exception de) {
        de.printStackTrace();
    }
}

From source file:com.songbook.pc.exporter.PdfExporter.java

License:Open Source License

public PdfExporter(SongNodeLoader loader) {
    this.loader = loader;

    // Load fonts
    FontFactory.registerDirectories();
    BaseFont timesFont = null;//from   ww w.j  a v  a 2  s .  c  o m
    try {
        timesFont = BaseFont.createFont("C:/Windows/Fonts/times.ttf", BaseFont.CP1250, true);
        logger.info("Embedded TTF fonts from C:/Windows/Fonts");
    } catch (Exception ex) {
        try {
            timesFont = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, true);
            logger.info("Embedded default fonts");
        } catch (Exception ex1) {
            logger.error("Failed to load fonts ...");
        }
    }

    // Initialize fonts
    if (timesFont != null) {
        songTitleFont = new Font(timesFont, 14f, Font.BOLD);
        textFont = new Font(timesFont, 11f, Font.NORMAL);
        chordFont = FontFactory.getFont(FontFactory.HELVETICA, BaseFont.CP1250, 11f, Font.BOLD);
    } else {
        songTitleFont = null;
        textFont = null;
        chordFont = null;
    }

    verseSpacing = new Paragraph(" ");
    verseSpacing.setLeading(5f, 0.5f);
}

From source file:de.unigoettingen.sub.commons.contentlib.pdflib.PDFManager.java

License:Apache License

/**
 * Creates the pdf writer./*from   w w w.  j a v a2 s.  c o  m*/
 * 
 * @param out the out
 * @param writer the writer
 * @param pdfdoc the pdfdoc
 * 
 * @return the pdf writer
 * 
 * @throws PDFManagerException the PDF manager exception
 */
private PdfWriter createPDFWriter(OutputStream out, Document pdfdoc) throws PDFManagerException {
    PdfWriter writer = null;
    try {
        // open the pdfwriter using the outstream
        writer = PdfWriter.getInstance(pdfdoc, out);
        LOGGER.debug("PDFWriter intstantiated");

        // register Fonts
        int numoffonts = FontFactory.registerDirectories();

        LOGGER.debug(numoffonts + " fonts found and registered!");

        if ((pdfa) && (iccprofile != null)) {
            // we want to write PDFA, we have to set the PDFX conformance
            // before we open the writer
            writer.setPDFXConformance(PdfWriter.PDFA1B);
        }

        // open the pdf document to add pages and other content
        try {
            pdfdoc.open();
            LOGGER.debug("PDFDocument opened");
        } catch (Exception e) {
            throw new PDFManagerException("PdfWriter was opened, but the pdf document couldn't be opened", e);
        }

        if ((pdfa) && (iccprofile != null)) {

            // set the required PDFDictionary which
            // contains the appropriate ICC profile
            PdfDictionary pdfdict_out = new PdfDictionary(PdfName.OUTPUTINTENT);

            // set identifier for ICC profile
            pdfdict_out.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGBIEC61966-2.1"));
            pdfdict_out.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1"));
            pdfdict_out.put(PdfName.S, PdfName.GTS_PDFA1);

            // PdfICCBased ib = new PdfICCBased(iccprofile);
            // writer.setOutputIntents("Custom", "PDF/A sRGB", null, "PDF/A
            // sRGB ICC Profile, sRGB_IEC61966-2-1_withBPC.icc",
            // colorProfileData);

            // read icc profile
            // ICC_Profile icc = ICC_Profile.getInstance(new
            // FileInputStream("c:\\srgb.profile"));
            PdfICCBased ib = new PdfICCBased(iccprofile);
            ib.remove(PdfName.ALTERNATE);

            PdfIndirectObject pio = writer.addToBody(ib);
            pdfdict_out.put(PdfName.DESTOUTPUTPROFILE, pio.getIndirectReference());
            writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(pdfdict_out));

            // create MarkInfo elements
            // not sure this is necessary; maybe just needed for tagged PDFs
            // (PDF/A 1a)
            PdfDictionary markInfo = new PdfDictionary(PdfName.MARKINFO);
            markInfo.put(PdfName.MARKED, new PdfBoolean("false"));
            writer.getExtraCatalog().put(PdfName.MARKINFO, markInfo);

            // write XMP
            this.writeXMPMetadata(writer);
        }
    } catch (Exception e) {
        LOGGER.error("Can't open the PdfWriter object\n" + e.toString() + "\n" + e.getMessage());
        throw new PDFManagerException("Can't open the PdfWriter object", e);
    }
    return writer;
}

From source file:fr.opensagres.xdocreport.itext.extension.font.AbstractFontRegistry.java

License:Open Source License

private void initFontRegistryIfNeeded() {
    if (!fontRegistryInitialized) {
        // clear built-in fonts which may clash with document fonts
        ExtendedBaseFont.clearBuiltinFonts();
        // register fonts from files (ex : for windows, load files from C:\WINDOWS\Fonts)
        FontFactory.registerDirectories();
        fontRegistryInitialized = true;/* w  w  w .j  av  a  2 s  .c  o m*/
    }
}

From source file:jdraw.JDrawApplication.java

private void saveAsPDF() {
    JDocumentFrame frame = (JDocumentFrame) jDesktopPane1.getSelectedFrame();
    if (frame == null) {
        return;//  w  w  w  .j  a  va 2  s .com
    }
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter(
            java.util.ResourceBundle.getBundle("main").getString("filter_pdf"), "pdf"));
    chooser.setDialogTitle(java.util.ResourceBundle.getBundle("main").getString("dialog_export_as_pdf"));
    File f = chooser.getCurrentDirectory();
    f = new File(f.getPath(), frame.getDocument().getName() + ".pdf");
    chooser.setSelectedFile(f);
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;
    }
    JDocument doc = frame.getDocument();
    f = chooser.getSelectedFile();
    if (f.exists() && JOptionPane.showConfirmDialog(this, f.getName() + java.util.ResourceBundle
            .getBundle("main").getString("msg_is_exist_overwrite")) != JOptionPane.OK_OPTION) {
        return;
    }
    frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    com.lowagie.text.Document pDoc = new com.lowagie.text.Document();
    try {
        FileOutputStream wt = new FileOutputStream(f);
        BufferedOutputStream bout = new BufferedOutputStream(wt);
        com.lowagie.text.pdf.PdfWriter pwriter = com.lowagie.text.pdf.PdfWriter.getInstance(pDoc, bout);
        pDoc.open();
        FontFactory.registerDirectories();
        Set set = FontFactory.getRegisteredFonts();

        for (int i = 0; i < doc.size(); i++) {
            JPage cPage = doc.get(i);
            PageFormat pFormat = cPage.getPageFormat();
            com.lowagie.text.Rectangle rc = new com.lowagie.text.Rectangle((float) pFormat.getWidth(),
                    (float) pFormat.getHeight());
            float left = (float) (pFormat.getImageableX());
            float right = (float) (pFormat.getWidth() - pFormat.getImageableWidth() - left);
            float top = (float) pFormat.getImageableX();
            float bottom = (float) (pFormat.getHeight() - pFormat.getImageableHeight() - top);
            pDoc.newPage();

            com.lowagie.text.pdf.PdfContentByte cb = pdfContentByte = pwriter.getDirectContent();
            cb.saveState();

            Graphics2D g2 = (com.lowagie.text.pdf.PdfGraphics2D) cb.createGraphics((float) pFormat.getWidth(),
                    (float) pFormat.getHeight());

            boolean vg = cPage.getGuidLayer().isVisible();
            cPage.getGuidLayer().setVisible(false);
            cPage.paint(new Rectangle.Double(0, 0, pFormat.getWidth(), pFormat.getHeight()), g2);
            cPage.getGuidLayer().setVisible(vg);
            g2.dispose();
            cb.restoreState();
        }
        pDoc.close();
    } catch (Exception e) {
        JOptionPane.showConfirmDialog(this, e.getMessage(), "", JOptionPane.OK_OPTION,
                JOptionPane.ERROR_MESSAGE);
    }
    frame.getViewer().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

}

From source file:jmemorize.core.io.PdfRtfBuilder.java

License:Open Source License

private static void export(Lesson lesson, int mode, File file) throws IOException {
    logger = Main.getLogger();/*from   w w w  .jav a2  s. c  o m*/

    FontFactory.registerDirectories();
    // set up the fonts we will use to write the front and back of cards
    String frontFontName = Settings.loadFont(FontType.CARD_FRONT).getFont().getFamily();
    frontFont = FontFactory.getFont(frontFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    if (frontFont == null) {
        logger.warning("FontFactory returned null (front) font for: " + frontFontName);
    }

    String backFontName = Settings.loadFont(FontType.CARD_FLIP).getFont().getFamily();
    backFont = FontFactory.getFont(backFontName, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

    if (backFont == null) {
        logger.warning("FontFactory returned null (back) font for: " + backFontName);
    }

    try {
        Document doc = new Document();
        OutputStream out = new FileOutputStream(file);

        switch (mode) {
        case PDF_MODE:
            PdfWriter.getInstance(doc, out);
            break;

        case RTF_MODE:
            RtfWriter2.getInstance(doc, out);
            break;
        }

        doc.setHeader(new HeaderFooter(new Phrase(file.getName()), false));
        doc.open();

        // add cards in subtrees
        List<Category> subtree = lesson.getRootCategory().getSubtreeList();
        for (Category category : subtree) {
            writeCategory(doc, category);
        }

        doc.close();

    } catch (Throwable t) {
        throw (IOException) new IOException("Could not export to PDF").initCause(t);
    }
}

From source file:org.forester.archaeopteryx.PdfExporter.java

License:Open Source License

static String writePhylogenyToPdf(final String file_name, final TreePanel tree_panel, int width, int height)
        throws IOException {
    if (height < HEIGHT_LIMIT) {
        height = HEIGHT_LIMIT;/*from ww  w .  j a  va2  s.  co m*/
    }
    if (width < WIDTH_LIMIT) {
        width = WIDTH_LIMIT;
    }
    final Phylogeny phylogeny = tree_panel.getPhylogeny();
    if ((phylogeny == null) || phylogeny.isEmpty()) {
        return "";
    }
    if (tree_panel.getMainPanel().getTreeFontSet().getSmallFont().getSize() < 1) {
        throw new IOException("fonts are too small for PDF export");
    }
    final File file = new File(file_name);
    if (file.isDirectory()) {
        throw new IOException("[" + file_name + "] is a directory");
    }
    final Document document = new Document();
    document.setPageSize(new Rectangle(width, height));
    document.setMargins(WIDTH_LIMIT / 2, WIDTH_LIMIT / 2, HEIGHT_LIMIT / 2, HEIGHT_LIMIT / 2);
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(file_name));
    } catch (final DocumentException e) {
        throw new IOException(e);
    }
    document.open();
    final DefaultFontMapper mapper = new DefaultFontMapper();
    FontFactory.registerDirectories();
    if (Util.isWindows()) {
        mapper.insertDirectory("C:\\WINDOWS\\Fonts\\");
    } else if (Util.isMac()) {
        mapper.insertDirectory("/Library/Fonts/");
        mapper.insertDirectory("/System/Library/Fonts/");
    } else {
        mapper.insertDirectory("/usr/X/lib/X11/fonts/TrueType/");
        mapper.insertDirectory("/usr/X/lib/X11/fonts/Type1/");
        mapper.insertDirectory("/usr/share/fonts/default/TrueType/");
        mapper.insertDirectory("/usr/share/fonts/default/Type1/");
    }
    final PdfContentByte cb = writer.getDirectContent();
    final Graphics2D g2 = cb.createGraphics(width, height, mapper);
    try {
        tree_panel.paintPhylogeny(g2, true, false, width - WIDTH_LIMIT, height - HEIGHT_LIMIT, 0, 0);
    } catch (final Exception e) {
        Util.unexpectedException(e);
    } finally {
        try {
            g2.dispose();
            document.close();
        } catch (final Exception e) {
            //Do nothing.
        }
    }
    String msg = file.toString();
    if ((width > 0) && (height > 0)) {
        msg += " [size: " + width + ", " + height + "]";
    }
    return msg;
}

From source file:org.geoserver.wms.map.PDFMapResponse.java

License:Open Source License

/**
 * Writes the PDF./* w w  w  . j  a v a2s.  co  m*/
 * <p>
 * NOTE: the document seems to actually be created in memory, and being written down to
 * {@code output} once we call {@link Document#close()}. If there's no other way to do so, it'd
 * be better to actually split out the process into produceMap/write?
 * </p>
 * 
 * @see org.geoserver.ows.Response#write(java.lang.Object, java.io.OutputStream,
 *      org.geoserver.platform.Operation)
 */
@Override
public void write(Object value, OutputStream output, Operation operation) throws IOException, ServiceException {

    Assert.isInstanceOf(PDFMap.class, value);
    WMSMapContent mapContent = ((PDFMap) value).getContext();

    final int width = mapContent.getMapWidth();
    final int height = mapContent.getMapHeight();

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("setting up " + width + "x" + height + " image");
    }

    try {
        // step 1: creation of a document-object
        // width of document-object is width*72 inches
        // height of document-object is height*72 inches
        com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(width, height);

        Document document = new Document(pageSize);
        document.setMargins(0, 0, 0, 0);

        // step 2: creation of the writer
        PdfWriter writer = PdfWriter.getInstance(document, output);

        // step 3: we open the document
        document.open();

        // step 4: we grab the ContentByte and do some stuff with it

        // we create a fontMapper and read all the fonts in the font
        // directory
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();

        // we create a template and a Graphics2D object that corresponds
        // with it
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(width, height);
        PdfGraphics2D graphic = (PdfGraphics2D) tp.createGraphics(width, height, mapper);

        // we set graphics options
        if (!mapContent.isTransparent()) {
            graphic.setColor(mapContent.getBgColor());
            graphic.fillRect(0, 0, width, height);
        } else {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("setting to transparent");
            }

            int type = AlphaComposite.SRC;
            graphic.setComposite(AlphaComposite.getInstance(type));

            Color c = new Color(mapContent.getBgColor().getRed(), mapContent.getBgColor().getGreen(),
                    mapContent.getBgColor().getBlue(), 0);
            graphic.setBackground(mapContent.getBgColor());
            graphic.setColor(c);
            graphic.fillRect(0, 0, width, height);

            type = AlphaComposite.SRC_OVER;
            graphic.setComposite(AlphaComposite.getInstance(type));
        }

        Rectangle paintArea = new Rectangle(width, height);

        StreamingRenderer renderer = new StreamingRenderer();
        renderer.setMapContent(mapContent);
        // TODO: expose the generalization distance as a param
        // ((StreamingRenderer) renderer).setGeneralizationDistance(0);

        RenderingHints hints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        renderer.setJava2DHints(hints);

        // we already do everything that the optimized data loading does...
        // if we set it to true then it does it all twice...
        java.util.Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true));
        rendererParams.put("renderingBuffer", new Integer(mapContent.getBuffer()));
        // we need the renderer to draw everything on the batik provided graphics object
        rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
        // render everything in vector form if possible
        rendererParams.put(StreamingRenderer.VECTOR_RENDERING_KEY, Boolean.TRUE);
        if (DefaultWebMapService.isLineWidthOptimizationEnabled()) {
            rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, true);
        }
        rendererParams.put(StreamingRenderer.SCALE_COMPUTATION_METHOD_KEY, mapContent.getRendererScaleMethod());

        renderer.setRendererHints(rendererParams);

        Envelope dataArea = mapContent.getRenderingArea();

        // enforce no more than x rendering errors
        int maxErrors = wms.getMaxRenderingErrors();
        MaxErrorEnforcer errorChecker = new MaxErrorEnforcer(renderer, maxErrors);

        // Add a render listener that ignores well known rendering exceptions and reports back
        // non
        // ignorable ones
        final RenderExceptionStrategy nonIgnorableExceptionListener;
        nonIgnorableExceptionListener = new RenderExceptionStrategy(renderer);
        renderer.addRenderListener(nonIgnorableExceptionListener);

        // enforce max memory usage
        int maxMemory = wms.getMaxRequestMemory() * KB;
        PDFMaxSizeEnforcer memoryChecker = new PDFMaxSizeEnforcer(renderer, graphic, maxMemory);

        // render the map
        renderer.paint(graphic, paintArea, mapContent.getRenderingArea(), mapContent.getRenderingTransform());

        // render the watermark
        MapDecorationLayout.Block watermark = RenderedImageMapOutputFormat.getWatermark(wms.getServiceInfo());

        if (watermark != null) {
            MapDecorationLayout layout = new MapDecorationLayout();
            layout.paint(graphic, paintArea, mapContent);
        }

        // check if a non ignorable error occurred
        if (nonIgnorableExceptionListener.exceptionOccurred()) {
            Exception renderError = nonIgnorableExceptionListener.getException();
            throw new ServiceException("Rendering process failed", renderError, "internalError");
        }

        // check if too many errors occurred
        if (errorChecker.exceedsMaxErrors()) {
            throw new ServiceException("More than " + maxErrors + " rendering errors occurred, bailing out",
                    errorChecker.getLastException(), "internalError");
        }

        // check we did not use too much memory
        if (memoryChecker.exceedsMaxSize()) {
            long kbMax = maxMemory / KB;
            throw new ServiceException(
                    "Rendering request used more memory than the maximum allowed:" + kbMax + "KB");
        }

        graphic.dispose();
        cb.addTemplate(tp, 0, 0);

        // step 5: we close the document
        document.close();
        writer.flush();
        writer.close();
    } catch (DocumentException t) {
        throw new ServiceException("Error setting up the PDF", t, "internalError");
    }
}