Example usage for com.lowagie.text.pdf PdfGraphics2D dispose

List of usage examples for com.lowagie.text.pdf PdfGraphics2D dispose

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfGraphics2D dispose.

Prototype

public void dispose() 

Source Link

Usage

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

License:Open Source License

/**
 * Writes the PDF./*from   w w w  .  j av a  2  s  .  c o  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");
    }
}

From source file:org.vfny.geoserver.wms.responses.map.pdf.PDFMapProducer.java

License:Open Source License

/**
 * Writes the image to the client.//from  w ww.  j  a  va  2 s. co  m
 * 
 * @param out
 *            The output stream to write to.
 */
public void writeTo(OutputStream out) throws ServiceException, java.io.IOException {
    final int width = mapContext.getMapWidth();
    final int height = mapContext.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, out);

        // 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 (!mapContext.isTransparent()) {
            graphic.setColor(mapContext.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(mapContext.getBgColor().getRed(), mapContext.getBgColor().getGreen(),
                    mapContext.getBgColor().getBlue(), 0);
            graphic.setBackground(mapContext.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);

        renderer = new StreamingRenderer();
        renderer.setContext(mapContext);
        // 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...
        Map rendererParams = new HashMap();
        rendererParams.put("optimizedDataLoadingEnabled", new Boolean(true));
        rendererParams.put("renderingBuffer", new Integer(mapContext.getBuffer()));
        // we need the renderer to draw everything on the batik provided graphics object
        rendererParams.put(StreamingRenderer.OPTIMIZE_FTS_RENDERING_KEY, Boolean.FALSE);
        if (!DefaultWebMapService.isLineWidthOptimizationEnabled()) {
            rendererParams.put(StreamingRenderer.LINE_WIDTH_OPTIMIZATION_KEY, false);
        }
        renderer.setRendererHints(rendererParams);

        Envelope dataArea = mapContext.getAreaOfInterest();
        AffineTransform at = RendererUtilities.worldToScreenTransform(dataArea, paintArea);

        if (this.abortRequested) {
            graphic.dispose();
            // step 5: we close the document
            document.close();

            return;
        }

        // 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, at);

        // render the watermark
        MapDecorationLayout.Block watermark = DefaultRasterMapProducer
                .getWatermark(this.mapContext.getRequest().getWMS().getServiceInfo());

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

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

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

        // check we did not use too much memory
        if (memoryChecker.exceedsMaxSize()) {
            long kbMax = maxMemory / KB;
            throw new WmsException(
                    "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 WmsException("Error setting up the PDF", "internalError", t);
    }
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createMapAsPDF(File file, LWMap map) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER.rotate());

    try {/*  w w  w. j  a v a  2s  .c  o m*/
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        PdfContentByte cb = writer.getDirectContent();
        //  cb.setFontAndSize(arg0, arg1)
        PdfTemplate tp = cb.createTemplate(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70);
        // tp.createGraphicsShapes(arg0, arg1) 

        PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(document.getPageSize().getWidth() - 70,
                document.getPageSize().getHeight() - 70, getFontMapper(), false, 60.0f);

        Dimension page = new Dimension((int) document.getPageSize().getWidth() - 70,
                (int) document.getPageSize().getHeight() - 70);
        // compute zoom & offset for visible map components
        Point2D.Float offset = new Point2D.Float();
        offset.x = 35;
        offset.y = 35;
        // center vertically only if landscape mode
        //if (format.getOrientation() == PageFormat.LANDSCAPE)
        //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)
        Rectangle2D bounds = map.getBounds();
        double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
        //  System.out.println(scale  + " zoom factor...");
        // set up the DrawContext
        DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                map, false); // todo: absolute links shouldn't be spec'd here

        //    dc.setAntiAlias(true);
        dc.setMapDrawing();
        //   dc.setPDFRender(true);
        //dc.setPrioritizeQuality(false); // why was this low quality?
        dc.setPrintQuality();
        //dc.setAntiAlias(false); // why was this turned off?  was it redundant?

        dc.setClipOptimized(true);
        //   dc.setDraftQuality(true);
        //  dc.setRawDrawing();
        //dc.setClipOptimized(false);

        dc.setInteractive(false);
        dc.setDrawPathways(false);

        // VUE.getActiveMap().draw(dc);
        LWPathway.setShowSlides(false);
        map.drawZero(dc);
        LWPathway.setShowSlides(true);
        g2d.dispose();
        //  document.add(new Paragraph(new Chunk().setAnchor("http://www.cnn.com")));
        cb.addTemplate(tp, 0, 0);
        document.newPage();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationSlidesDeck(File file) {
    // step 1: creation of a document-object
    final Document document = new Document(PageSize.LETTER.rotate());

    try {//from   w ww .  j av a2  s  . c  om
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        writer.setStrictImageSequence(true);
        // step 3: we open the document

        document.open();

        final float pageWidth = document.getPageSize().getWidth();
        final float pageHeight = document.getPageSize().getHeight();
        final float fillWidth = pageWidth - 70;
        final float fillHeight = pageHeight - 70;

        if (DEBUG.Enabled) {
            System.out.println("\n---------------------------------");
            System.out.println("PDF DOCUMENT: pageSize " + document.getPageSize());
            System.out.println("fillWidth=" + fillWidth + " fillHeight=" + fillHeight);
        }
        int currentIndex = VUE.getActivePathway().getIndex();
        VUE.getActivePathway().setIndex(-1);
        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            if (DEBUG.Enabled)
                Log.debug("\n\nHANDLING DECK ENTRY " + entry);
            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            final PdfTemplate template = PdfTemplate.createTemplate(writer, fillWidth, fillHeight);
            final PdfGraphics2D graphics = (PdfGraphics2D) template.createGraphics(fillWidth, fillHeight,
                    getFontMapper(), false, 60.0f);
            final DrawContext dc = new DrawContext(graphics, 1.0);
            //                 //final DrawContext dc = new DrawContext(graphics, scale);
            //final DrawContext dc = new DrawContext(graphics, toDraw); // ideally, should use this
            dc.setClipOptimized(false);
            dc.setInteractive(false); // should be un-needed
            dc.setPrintQuality();

            // We set dc.focused to the node, which is needed for portals so they know to render contents in their clip-region.
            // Normally a portal knows to do this because it's the focal (dc.focal), but in this case, the dc.focal could,
            // at best, be the slide.  The current code actually uses NO focal in creating the DrawContext above,
            // and I'm not changing that just now as that would require lots of regression testing of printing.  SMF 6/24/10
            dc.focused = entry.node;

            if (DEBUG.Enabled) {
                Log.debug("DRAWING INTO " + dc + " g=" + graphics + " clip="
                        + tufts.Util.fmt(graphics.getClip()));
                if (DEBUG.PDF) {
                    dc.g.setColor(Color.green);
                    dc.g.fillRect(-Short.MAX_VALUE / 2, -Short.MAX_VALUE / 2, Short.MAX_VALUE, Short.MAX_VALUE);
                }
            }

            try {
                if (DEBUG.Enabled)
                    dc.clearDebug();
                toDraw.drawFit(dc, 0);
            } catch (Throwable t) {
                Log.error("exception drawing " + toDraw, t);
            }

            try {

                if (DEBUG.Enabled)
                    Log.debug("painted " + DrawContext.getDebug() + " to " + dc);

                if (DEBUG.PDF) {
                    final String dcDesc = dc.toString()
                            + String.format(" scale=%.1f%%", dc.g.getTransform().getScaleX() * 100);
                    dc.setRawDrawing();
                    dc.g.setColor(Color.red);
                    dc.g.setFont(VueConstants.FixedSmallFont);
                    dc.g.drawString(dcDesc, 10, fillHeight - 27);
                    dc.g.drawString(entry.toString(), 10, fillHeight - 16);
                    dc.g.drawString(toDraw.toString(), 10, fillHeight - 5);
                }

                // the graphics dispose appears to be very important -- we've seen completely intermittant
                // problems with generating many page PDF documents, which would be well explained by
                // java or internal itext buffers running out of memory.
                graphics.dispose();

                document.add(Image.getInstance(template));
                document.newPage();
            } catch (Throwable t) {
                Log.error("exception finishing " + toDraw + " in " + dc, t);
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
        if (DEBUG.Enabled)
            Log.debug("PROCESSED ALL ENTRIES");

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createPresentationNotes8PerPage(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612/*  w ww  . j  av  a 2 s . co m*/
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

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

        // PdfPTable table;
        // PdfPCell cell;            
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            entryCount++;
            //String label = entry.getLabel();
            PdfContentByte cb = writer.getDirectContent();
            //cb.cr
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);
            Point2D.Float offset = new Point2D.Float();

            Rectangle2D bounds = null;

            bounds = slide.getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();
            //slide.drawZero(dc);
            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            if (entryOnPage == 0) {
                drawSequenceNumber(writer, 36, 739, entryCount);
                cb.addTemplate(tp, 56, 583);
            }
            if (entryOnPage == 1) {
                drawSequenceNumber(writer, 296, 739, entryCount);
                cb.addTemplate(tp, 306, 583);
            }
            if (entryOnPage == 2) {
                drawSequenceNumber(writer, 36, 559, entryCount);
                cb.addTemplate(tp, 56, 403);
            }
            if (entryOnPage == 3) {
                drawSequenceNumber(writer, 296, 559, entryCount);
                cb.addTemplate(tp, 306, 403);
            }
            if (entryOnPage == 4) {
                drawSequenceNumber(writer, 36, 375, entryCount);
                cb.addTemplate(tp, 56, 219);
            }
            if (entryOnPage == 5) {
                drawSequenceNumber(writer, 296, 375, entryCount);
                cb.addTemplate(tp, 306, 219);
            }
            if (entryOnPage == 6) {
                drawSequenceNumber(writer, 36, 192, entryCount);
                cb.addTemplate(tp, 56, 36);
                //cb.addTemplate(drawLines(writer),296,18);
            }
            if (entryOnPage == 7) {
                drawSequenceNumber(writer, 296, 192, entryCount);
                cb.addTemplate(tp, 306, 36);
            }

            entryOnPage++;
            if (entryCount % 8 == 0) {
                document.newPage();
                entryOnPage = 0;
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createAudienceNotes(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612//  ww  w .  j  av  a 2s .  co m
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object
    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

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

        // PdfPTable table;
        // PdfPCell cell;            
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);

            entryCount++;
            //String label = entry.getLabel();
            PdfContentByte cb = writer.getDirectContent();
            //cb.cr
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);
            Point2D.Float offset = new Point2D.Float();
            // center vertically only if landscape mode
            //if (format.getOrientation() == PageFormat.LANDSCAPE)
            //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)

            Rectangle2D bounds = null;

            bounds = slide.getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();

            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            if (entryOnPage == 0) {
                drawSequenceNumber(writer, 36, 739, entryCount);
                cb.addTemplate(tp, 56, 583);
                cb.addTemplate(drawLines(writer), 296, 565);

            }
            if (entryOnPage == 1) {
                drawSequenceNumber(writer, 36, 559, entryCount);
                cb.addTemplate(tp, 56, 403);
                cb.addTemplate(drawLines(writer), 296, 385);
            }
            if (entryOnPage == 2) {
                drawSequenceNumber(writer, 36, 375, entryCount);
                cb.addTemplate(tp, 56, 219);
                cb.addTemplate(drawLines(writer), 296, 201);
            }
            if (entryOnPage == 3) {
                drawSequenceNumber(writer, 36, 192, entryCount);
                cb.addTemplate(tp, 56, 36);
                cb.addTemplate(drawLines(writer), 296, 18);
            }

            entryOnPage++;
            if (entryCount % 4 == 0) {
                document.newPage();
                entryOnPage = 0;
            }
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createSpeakerNotes1PerPage(File file) {

    // step 1: creation of a document-object

    //This is a bit of a mess but because of hte bugs with drawing the slides
    //the easy way, we have no other choice but to render them directly onto the pdf
    //which makes it hard to use tables for stuff like formatting text...so we'll render
    // a blank table cell then render the image into it.
    Document document = new Document();

    try {/*from   w w w  . j a v a 2s  . c  o  m*/
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));

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

        PdfPTable table;
        PdfPCell cell;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);
            final String notes = entry.getNotes();
            //String label = entry.getLabel();

            PdfContentByte cb = writer.getDirectContent();

            Point2D.Float offset = new Point2D.Float();

            Rectangle2D bounds = null;

            //if (!entry.isMapView())
            bounds = slide.getBounds();
            //else 
            //bounds = entry.getFocal().getBounds();

            Dimension page = null;

            page = new Dimension(432, 324);

            PdfTemplate tp = cb.createTemplate(432, 324);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(432, 324, getFontMapper(), false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();
            /*if (!entry.isMapView())                   
               slide.drawZero(dc);
            else
            {                
               entry.getFocal().draw(dc);
            }*/
            toDraw.drawFit(dc, 0);

            g2d.dispose();

            cb.addTemplate(tp, 80, 482);

            //Paragraph p = new Paragraph();
            //p.setExtraParagraphSpace(330);
            // p.setSpacingBefore(330f);
            //  p.setAlignment(Element.ALIGN_CENTER);

            Paragraph phrase = new Paragraph(notes);
            //phrase.setExtraParagraphSpace(340f);
            phrase.setSpacingBefore(320f);
            phrase.setKeepTogether(true);
            //cell = new PdfPCell(phrase);
            //cell.setBorder(0);
            //         table = new PdfPTable(new float[]{ 1 });
            //        table.setWidthPercentage(100.0f);
            //        table.getDefaultCell().setBorder(0);
            //table.getDefaultCell().setPaddingTop(30);

            //PdfPCell c2 = new PdfPCell();
            //c2.setFixedHeight(340); //slides are 540x405
            //c2.setBorder(0);
            //table.addCell(c2);                
            //table.addCell(cell);
            //table.setKeepTogether(false);
            //cell.setVerticalAlignment(PdfPCell.ALIGN_TOP);

            //p.add(table);
            //System.out.println("CELL HEIGHT : " + cell.getHeight());
            //Section s1 = new Section();
            //ColumnText chunk2 = new ColumnText(cb);
            //chunk2.setText(phrase);
            //chunk2.setSi
            //chunk2.setSimpleColumn(phrase,70, 330, document.getPageSize().width()-70,document.getPageSize().height()-70,15, Element.ALIGN_LEFT);
            // chunk2.go();
            //PdfChunk chunk2 = new PdfChunk);
            Paragraph p2 = new Paragraph(" ");
            p2.setKeepTogether(false);
            phrase.setKeepTogether(false);
            // p2.setExtraParagraphSpace(230f);
            document.add(p2);
            document.add(phrase);
            document.newPage();
        }

        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();
}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createSpeakerNotes4PerPage(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612/*from   w w  w.java 2s  .  co m*/
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object

    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

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

        PdfPTable table;
        PdfPCell cell;
        int entryCount = 0;
        int entryOnPage = 0;
        int currentIndex = VUE.getActivePathway().getIndex();

        VUE.getActivePathway().setIndex(-1);

        for (LWPathway.Entry entry : VUE.getActivePathway().getEntries()) {

            final LWSlide slide = entry.produceSlide();
            final LWComponent toDraw = (slide == null ? entry.node : slide);
            final String notes = entry.getNotes();
            entryCount++;

            table = new PdfPTable(new float[] { 1, 1 });
            table.getDefaultCell().setBorder(0);
            //table.getDefaultCell().setPaddingBottom(50.0f);
            table.setSpacingAfter(20.0f);
            Paragraph p = new Paragraph();

            p.setAlignment(Element.ALIGN_CENTER);

            Phrase phrase = new Phrase(notes);
            Font f = phrase.getFont();
            f.setSize(8.0f);
            p.setFont(f);
            cell = new PdfPCell(phrase);
            cell.setBorder(0);

            PdfPCell i2 = new PdfPCell();
            i2.setFixedHeight(172);
            i2.setBorder(0);

            //Render the table then throw the images on
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);

            Point2D.Float offset = new Point2D.Float();
            // center vertically only if landscape mode
            //if (format.getOrientation() == PageFormat.LANDSCAPE)
            //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)

            Rectangle2D bounds = null;
            //if (!entry.isMapView())
            bounds = slide.getBounds();
            //else 
            //bounds = entry.getFocal().getBounds();

            Dimension page = null;

            page = new Dimension(SlideSizeX, 172);

            //PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
            double scale = ZoomTool.computeZoomFit(page, 5, bounds, offset, true);
            PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                    false, 60.0f);
            DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                    entry.isMapView() ? entry.getFocal() : slide, false); // todo: absolute links shouldn't be spec'd here

            dc.setClipOptimized(false);
            dc.setPrintQuality();
            /*if (!entry.isMapView())                   
               slide.drawZero(dc);
            else
            {                
               entry.getFocal().draw(dc);
            }*/
            toDraw.drawFit(dc, 0);

            g2d.dispose();
            //document.add(Image.getInstance(tp));

            //  int position = cell.
            //     drawSequenceNumber(writer,36,position+203,entryCount);

            //     cb.addTemplate(tp,56, position);                                                           

            Image img = Image.getInstance(tp);
            table.addCell(img);
            table.addCell(cell);
            p.add(table);
            document.add(p);
        }
        VUE.getActivePathway().setIndex(currentIndex);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();

}

From source file:tufts.vue.PresentationNotes.java

License:Educational Community License

public static void createNodeNotes4PerPage(File file) {
    //page size notes:
    //martin-top,left,right,bottom = 36
    //widht :612/*  w  w  w  .j a v  a  2 s. c  o  m*/
    //height : 792
    //usable space 540 x 720
    // step 1: creation of a document-object

    Document document = new Document(PageSize.LETTER);

    try {
        GUI.activateWaitCursor();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file            
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        //  writer.setDefaultColorspace(PdfName.DEFAULTRGB, null);
        // writer.setStrictImageSequence(true);

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

        PdfPTable table;
        PdfPCell cell;
        int entryCount = 0;
        int entryOnPage = 0;

        Iterator i = VUE.getActiveMap().getAllDescendents(LWComponent.ChildKind.PROPER).iterator();
        while (i.hasNext()) {
            LWComponent component = (LWComponent) i.next();
            if (component instanceof LWNode) {
                final LWNode node = (LWNode) component;

                final String notes = node.getNotes();

                entryCount++;

                table = new PdfPTable(new float[] { 1, 1 });
                table.getDefaultCell().setBorder(0);

                table.setSpacingAfter(20.0f);
                Paragraph p = new Paragraph();

                p.setAlignment(Element.ALIGN_CENTER);

                Phrase phrase = new Phrase(notes);

                Font f = phrase.getFont();
                f.setSize(8.0f);
                p.setFont(f);
                cell = new PdfPCell(phrase);
                cell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                cell.setBorder(0);

                PdfPCell i2 = new PdfPCell();
                i2.setFixedHeight(172);
                i2.setBorder(0);

                //Render the table then throw the images on
                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(SlideSizeX, SlideSizeY);

                Point2D.Float offset = new Point2D.Float();
                //center vertically only if landscape mode
                //if (format.getOrientation() == PageFormat.LANDSCAPE)
                //TODO: allow horizontal centering, but not vertical centering (handle in computeZoomFit)

                Rectangle2D bounds = null;

                bounds = node.getBounds();

                Dimension page = null;

                page = new Dimension(SlideSizeX, 172);

                //   PdfTemplate tp = cb.createTemplate(document.getPageSize().width()-80, document.getPageSize().height()-80);
                double scale = ZoomTool.computeZoomFit(page, 15, bounds, offset, true);
                PdfGraphics2D g2d = (PdfGraphics2D) tp.createGraphics(SlideSizeX, SlideSizeY, getFontMapper(),
                        false, 60.0f);
                DrawContext dc = new DrawContext(g2d, scale, -offset.x, -offset.y, null, // frame would be the PageFormat offset & size rectangle
                        node, false); // todo: absolute links shouldn't be spec'd here

                dc.setClipOptimized(false);
                dc.setPrintQuality();
                node.drawFit(dc, 15);

                g2d.dispose();

                Image img = Image.getInstance(tp);
                table.addCell(img);
                table.addCell(cell);
                p.add(table);
                document.add(p);
            }
        }

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    } finally {
        GUI.clearWaitCursor();
    }

    // step 5: we close the document
    document.close();

}