Example usage for com.lowagie.text.pdf PdfContentByte createGraphicsShapes

List of usage examples for com.lowagie.text.pdf PdfContentByte createGraphicsShapes

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfContentByte createGraphicsShapes.

Prototype

public java.awt.Graphics2D createGraphicsShapes(float width, float height) 

Source Link

Document

Gets a Graphics2D to write on.

Usage

From source file:PRCR_Checkroll_Amalgamation.java

private void print() {
    Document document = new Document(PageSize.A4.rotate());
    try {//from w  w  w. j  av  a 2s  . com
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/Amalgamation.pdf"));

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        Graphics2D g2 = cb.createGraphicsShapes(1800, 750);

        Shape oldClip = g2.getClip();
        g2.clipRect(0, 0, 1800, 750);

        jTable1.print(g2);
        g2.setClip(oldClip);

        g2.dispose();
        cb.restoreState();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    document.close();
}

From source file:PRCR_Checkroll_Summar.java

private void print() {
    Document document = new Document(PageSize.A4);
    try {//  w w w.j a v  a 2  s . c o  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("E:/CheckrollSummary.pdf"));

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        Graphics2D g2 = cb.createGraphicsShapes(600, 750);

        Shape oldClip = g2.getClip();
        g2.clipRect(0, 0, 600, 750);

        jTable1.print(g2);
        g2.setClip(oldClip);

        g2.dispose();
        cb.restoreState();
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    document.close();
}

From source file:ca.sqlpower.architect.swingui.action.ExportPlaypenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    logger.debug("Creating PDF of playpen: " + getPlaypen());

    //This is the current play pen snapshot at the time of starting the worker
    //thread. This way the play pen doesn't change while it is printing.
    PlayPen pp = playPen;// w w  w. ja  v  a2 s  .  c o  m

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = pp.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = pp.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle(Messages.getString("ExportPlaypenToPDFAction.PdfTitle")); //$NON-NLS-1$
        d.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
        d.addCreator(Messages.getString("ExportPlaypenToPDFAction.powerArchitectVersion") //$NON-NLS-1$
                + ArchitectVersion.APP_FULL_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);
        PlayPenContentPane contentPane = pp.getContentPane();
        for (int i = 0; i < contentPane.getChildren().size(); i++) {
            PlayPenComponent ppc = contentPane.getChildren().get(i);
            if (logger.isDebugEnabled()) {
                logger.debug("Painting component " + ppc);
            }
            g.translate(ppc.getLocation().x, ppc.getLocation().y);
            Font gFont = g.getFont();
            ppc.paint(g);
            g.setFont(gFont);
            g.translate(-ppc.getLocation().x, -ppc.getLocation().y);
            monitor.setProgress(i);
        }
        pp.paintComponent(g);
        g.dispose();
    } catch (Exception ex) {
        ASUtils.showExceptionDialog(getSession(),
                Messages.getString("ExportPlaypenToPDFAction.couldNotExportPlaypen"), //$NON-NLS-1$
                ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotCloseDocument"), //$NON-NLS-1$
                        ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                ASUtils.showExceptionDialog(getSession(),
                        Messages.getString("ExportPlaypenToPDFAction.couldNotClosePdfFile"), //$NON-NLS-1$
                        ex);
            }
        }
    }
}

From source file:ca.sqlpower.matchmaker.swingui.action.ExportMungePenToPDFAction.java

License:Open Source License

@Override
public void doStuff(MonitorableImpl monitor, Map<String, Object> properties) {
    if (!(session.getOldPane() instanceof MungeProcessEditor)) {
        JOptionPane.showMessageDialog(session.getFrame(),
                "We only allow PDF exports of the playpen at current.", "Cannot Export Playpen",
                JOptionPane.WARNING_MESSAGE);
        return;//from   w  w w .  j a  v a 2  s  .  co m
    }

    MungePen mungePen = ((MungeProcessEditor) session.getOldPane()).getMungePen();

    /* We translate the graphics to (OUTSIDE_PADDING, OUTSIDE_PADDING) 
     * so nothing is drawn right on the edge of the document. So
     * we multiply by 2 so we can accomodate the translate and ensure
     * nothing gets drawn outside of the document size.
     */
    final int width = mungePen.getBounds().width + 2 * OUTSIDE_PADDING;
    final int height = mungePen.getBounds().height + 2 * OUTSIDE_PADDING;
    final Rectangle ppSize = new Rectangle(width, height);

    OutputStream out = null;
    Document d = null;
    try {
        out = new BufferedOutputStream(new FileOutputStream((File) properties.get(FILE_KEY)));
        d = new Document(ppSize);

        d.addTitle("DQguru Transform PDF Export");
        d.addAuthor(System.getProperty("user.name"));
        d.addCreator("DQguru version " + MatchMakerVersion.APP_VERSION);

        PdfWriter writer = PdfWriter.getInstance(d, out);
        d.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g = cb.createGraphicsShapes(width, height);
        // ensure a margin
        g.translate(OUTSIDE_PADDING, OUTSIDE_PADDING);

        mungePen.paintComponent(g);

        int j = 0;
        //paint each component individually to show progress
        for (int i = mungePen.getComponentCount() - 1; i >= 0; i--) {
            JComponent mpc = (JComponent) mungePen.getComponent(i);

            //set text and foreground as paintComponent
            //does not normally do this
            g.setColor(mpc.getForeground());
            g.setFont(mpc.getFont());

            logger.debug("Printing " + mpc.getName() + " to PDF");
            paintComponentAndChildren(mpc, g);

            monitor.setProgress(j);
            j++;
        }
        g.dispose();
    } catch (Exception ex) {
        SPSUtils.showExceptionDialogNoReport(session.getFrame(), "Could not export the playpen", ex);
    } finally {
        if (d != null) {
            try {
                d.close();
            } catch (Exception ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close document for exporting playpen", ex);
            }
        }
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException ex) {
                SPSUtils.showExceptionDialogNoReport(session.getFrame(),
                        "Could not close pdf file for exporting playpen", ex);
            }
        }
    }
}

From source file:classroom.intro.HelloWorld11.java

public static void main(String[] args) {
    // step 1//from   w w  w  .  j  ava2 s .  co  m
    Document.compress = false;
    Document document = new Document();
    try {
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        // step 3
        document.open();
        // step 4
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D graphics2D = cb.createGraphicsShapes(PageSize.A4.getWidth(), PageSize.A4.getHeight());
        graphics2D.drawString("Hello World", 36, 54);
        graphics2D.dispose();
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }
    // step 5
    document.close();
}

From source file:com.iver.cit.gvsig.project.documents.layout.FLayoutDraw.java

License:Open Source License

/**
 * A partir de un fichero que se pasa como parmetro se crea un pdf con el
 * contenido del Layout./*from w w w.  j av  a 2 s.co m*/
 *
 * @param pdf
 */
public void toPDF(File pdf) {
    Attributes attributes = layout.getLayoutContext().getAttributes();
    LayoutControl layoutControl = layout.getLayoutControl();

    double w = 0;
    double h = 0;
    Document document = new Document();

    if (attributes.isLandSpace()) {
        w = ((attributes.m_sizePaper.getAlto() * Attributes.DPISCREEN) / Attributes.PULGADA);
        h = ((attributes.m_sizePaper.getAncho() * Attributes.DPISCREEN) / Attributes.PULGADA);
    } else {
        w = ((attributes.m_sizePaper.getAncho() * Attributes.DPISCREEN) / Attributes.PULGADA);
        h = ((attributes.m_sizePaper.getAlto() * Attributes.DPISCREEN) / Attributes.PULGADA);
    }

    document.setPageSize(new com.lowagie.text.Rectangle((float) w, (float) h));

    try {
        FileOutputStream fos = new FileOutputStream(pdf);
        PdfWriter writer = PdfWriter.getInstance(document, fos);
        document.open();

        Print print = new Print();
        print.setLayout(layout);

        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g2 = cb.createGraphicsShapes((float) w, (float) h);

        try {
            if (attributes.isLandSpace()) {
                g2.rotate(Math.toRadians(-90), 0 + (w / (h / w)), 0 + (h / 2));
                print.print(g2, new PageFormat(), 0);
                g2.rotate(Math.toRadians(90), 0 + (w / (h / w)), 0 + (h / 2));
            } else {
                print.print(g2, new PageFormat(), 0);
            }
        } catch (PrinterException e) {
            e.printStackTrace();
        }

        g2.dispose();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog((Component) PluginServices.getMainFrame(), ioe.getMessage());
    }

    document.close();

    layoutControl.fullRect();
}

From source file:fitnessmanagersystem.ExportPanel.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    Document document = new Document(PageSize.A2.rotate());
    try {/*from  w w w.j  a va2s.c  om*/

        JFileChooser chooser = new JFileChooser(".");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf");
        chooser.setFileFilter(filter);
        chooser.showSaveDialog(this);

        String fileName = chooser.getSelectedFile().getPath();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        cb.saveState();

        Graphics2D g2 = cb.createGraphicsShapes(1500, 500);
        Shape oldClip = g2.getClip();
        g2.clipRect(0, 0, 1500, 500);

        jTable1_clients.print(g2);
        g2.setClip(oldClip);
        g2.dispose();
        cb.restoreState();

    } catch (FileNotFoundException | DocumentException e) {
        System.err.println(e.getMessage());
    }
    document.close();

}

From source file:fitnessmanagersystem.ExportPanelProducts.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    Document document = new Document(PageSize.A2.rotate());
    try {/*w  w  w  .  ja v  a  2 s .c  o m*/
        String FileDialog = null;

        //   PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf"));

        JFileChooser chooser = new JFileChooser(".");
        FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf");
        chooser.setFileFilter(filter);
        chooser.showSaveDialog(this);

        //chooser.setFileFilter(filter);
        //        chooser.addChoosableFileFilter(filter);
        File file = chooser.getSelectedFile();

        String fileName = chooser.getSelectedFile().getPath();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));

        // PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FileDialog+"C:\\Users\\DISHLIEV\\Desktop\\jTsdfb11wablwe.pdf"));

        /*   FileDialog saveFileDialog = new FileDialog(new Frame(), "Save", FileDialog.SAVE);
              saveFileDialog.setFile("");
              saveFileDialog.setVisible(true);   
              saveFileDialog.getDirectory();
                
               try {
            dexceleporte exp = new dexceleporte();
                
          exp.fillData(jTable1, new File(saveFileDialog.getDirectory()+saveFileDialog.getFile()+".xls"));
                  
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        */

        document.open();
        PdfContentByte cb = writer.getDirectContent();

        cb.saveState();
        Graphics2D g2 = cb.createGraphicsShapes(1500, 500);

        Shape oldClip = g2.getClip();

        g2.clipRect(0, 0, 1500, 500);

        jTable12dfv.print(g2);
        g2.setClip(oldClip);

        g2.dispose();
        cb.restoreState();

        //}

    } catch (FileNotFoundException | DocumentException e) {
        System.err.println(e.getMessage());
    }
    document.close();

}

From source file:org.cytoscape.io.internal.write.graphics.PDFWriter.java

License:Open Source License

@Override
public void run(TaskMonitor taskMonitor) throws Exception {
    // TODO should be accomplished with renderer properties
    // view.setPrintingTextAsShape(!exportTextAsFont);

    taskMonitor.setProgress(0.0);/*from   www.  j  a v  a2s.com*/
    taskMonitor.setStatusMessage("Creating PDF image...");

    logger.debug("PDF Rendering start");
    final Rectangle pageSize = PageSize.LETTER;
    final Document document = new Document(pageSize);

    logger.debug("Document created: " + document);

    final PdfWriter writer = PdfWriter.getInstance(document, stream);
    document.open();

    taskMonitor.setProgress(0.1);

    final PdfContentByte canvas = writer.getDirectContent();
    logger.debug("CB0 created: " + canvas.getClass());

    final float pageWidth = pageSize.getWidth();
    final float pageHeight = pageSize.getHeight();

    logger.debug("Page W: " + pageWidth + " Page H: " + pageHeight);
    final DefaultFontMapper fontMapper = new DefaultFontMapper();
    logger.debug("FontMapper created = " + fontMapper);
    Graphics2D g = null;
    logger.debug("!!!!! Enter block 2");

    engine.getProperties().setProperty("exportTextAsShape", new Boolean(!exportTextAsFont).toString());

    taskMonitor.setProgress(0.2);

    if (exportTextAsFont) {
        g = canvas.createGraphics(pageWidth, pageHeight, new DefaultFontMapper());
    } else {
        g = canvas.createGraphicsShapes(pageWidth, pageHeight);
    }

    taskMonitor.setProgress(0.4);

    logger.debug("##### G2D created: " + g);

    double imageScale = Math.min(pageSize.getWidth() / width, pageSize.getHeight() / height);
    g.scale(imageScale, imageScale);

    logger.debug("##### Start Rendering Phase 2: " + engine.toString());
    engine.printCanvas(g);
    logger.debug("##### Canvas Rendering Done: ");

    taskMonitor.setProgress(0.8);

    g.dispose();
    document.close();
    writer.close();

    stream.close();

    logger.debug("PDF rendering finished.");
    taskMonitor.setProgress(1.0);
}

From source file:org.tellervo.desktop.graph.GraphPrintDialog.java

License:Open Source License

protected boolean printPDF(final GraphSettings pinfo, final GrapherPanel plotter) {
    final JFileChooser chooser = new JFileChooser();
    final Container me = getParent();
    chooser.setFileFilter(new FileFilter() {
        @Override/*from w  w  w .  ja  v  a 2 s.  c o m*/
        public boolean accept(File f) {
            return f.getName().endsWith(".pdf");
        }

        @Override
        public String getDescription() {
            return "PDF Document files (*.pdf)";
        }
    });
    chooser.setMultiSelectionEnabled(false);
    chooser.setAcceptAllFileFilterUsed(false);
    //chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return false;

    EventQueue.invokeLater(new Runnable() {
        public void run() {

            ProgressMonitor pm = new ProgressMonitor(me, // parent
                    "Exporting graph to PDF file...", // message
                    "", // note
                    0, 5); // round up to 45 MB

            pm.setMillisToDecideToPopup(0);
            pm.setMillisToPopup(0);

            pm.setProgress(1);
            pm.setNote("Creating PDF document...");

            String fn = chooser.getSelectedFile().getAbsolutePath();
            if (!fn.toLowerCase().endsWith(".pdf"))
                fn += ".pdf";

            // create a PDF document

            Rectangle rect = new Rectangle(0, 0, (pinfo.getDrawBounds().getSpan() * pinfo.getYearWidth()),
                    (pinfo.getPrintHeight()));
            com.lowagie.text.Rectangle pageSize = new com.lowagie.text.Rectangle(rect.width, rect.height);
            Document document = new Document(pageSize);

            try {
                // create an associated writer
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(fn)));

                // "open" the PDF
                document.open();

                // set up a font mapper
                //DefaultFontMapper mapper = new DefaultFontMapper();               
                //FontFactory.registerDirectories();

                pm.setProgress(2);
                pm.setNote("Creating PDF memory context...");

                // do some magic to set up the pdf context
                PdfContentByte cb = writer.getDirectContent();
                Graphics2D g = cb.createGraphicsShapes(pageSize.getWidth(), pageSize.getHeight());

                plotter.computeRange(pinfo, g);
                plotter.paintGraph(g, pinfo);

                // finish up the PDF cruft
                //cb.addTemplate(tp, 0, 0);                        

                //dispose of the graphics content
                pm.setProgress(4);
                pm.setNote("Cleaning up...");
                g.dispose();
            } catch (DocumentException de) {
                log.error(de.getMessage());
                de.printStackTrace();
            } catch (IOException ioe) {
                log.error(ioe.getMessage());
                ioe.printStackTrace();
            }

            document.close();
            pm.setProgress(5);
        }
    });
    return true;
}