Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

converting JTable into .pdf format

807606Aug 8 2006 — edited Mar 27 2007
Hi all,

I just started exploring the iText library because I need to convert a JTable into .pdf format.

I use the sample code given on their web site:

/*
 * $Id: JTable2Pdf.java,v 1.5 2005/08/24 08:45:34 blowagie Exp $
 * $Name:  $
 *
 * This code is part of the 'iText Tutorial'.
 * You can find the complete tutorial at the following address:
 * http://itextdocs.lowagie.com/tutorial/
 *
 * This code is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *
 * itext-questions@lists.sourceforge.net
 */
package com.lowagie.examples.objects.tables.alternatives;

import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JToolBar;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfWriter;

/**
 * Constructing a JTable and printing it to PDF.
 */
public class JTable2Pdf extends JFrame {
    /** The JTable we will show in a Swing app and print to PDF. */
    private JTable table;
    
    /**
     * Constructor for PrintJTable.
     */
    public JTable2Pdf() {
        getContentPane().setLayout(new BorderLayout());
        setTitle("JTable test");
        createToolbar();
        createTable();
        
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e)
            {System.exit(0);}
        });        
    }
    
    /**
     * Create a table with some dummy data
     */
    private void createTable() {
        Object[][] data ={
            {"Mary", "Campione", "Snowboarding", new
             Integer(5), new Boolean(false)},
             {"Alison", "Huml", "Rowing", new
              Integer(3), new Boolean(true)},
              {"Kathy", "Walrath", "Chasing toddlers",
               new Integer(2), new Boolean(false)},
               {"Mark", "Andrews", "Speed reading", new
                Integer(20), new Boolean(true)},
                {"Angela", "Lih", "Teaching high school", new Integer(4), new Boolean(false)}
        };
        
        String[] columnNames =
        {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
        
        table = new JTable(data, columnNames);
        
        // Use a panel to contains the table and add it the frame
        JPanel tPanel = new JPanel(new BorderLayout());
        tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tPanel.add(table, BorderLayout.CENTER);
        
        getContentPane().add(tPanel, BorderLayout.CENTER);
    }
    
    /**
     * Toolbar for print and exit
     */
    private void createToolbar() {
        JToolBar tb = new JToolBar();
        
        JButton printBtn = new JButton("Print");
        printBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                print();
            }
        });
        
        JButton exitBtn = new JButton("Exit");
        exitBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                exit();
            }
        });
        
        tb.add(printBtn);
        tb.add(exitBtn);
        
        getContentPane().add(tb, BorderLayout.NORTH);
    }
    /**
     * Print the table into a PDF file
     */
    private void print() {
        Document document = new Document(PageSize.A4.rotate());
        try {
            PdfWriter writer =
            PdfWriter.getInstance(document, new FileOutputStream("jTable.pdf"));
            
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            
            // Create the graphics as shapes
            cb.saveState();
            Graphics2D g2 = cb.createGraphicsShapes(500, 500);
            // Print the table to the graphics
            Shape oldClip = g2.getClip();
            g2.clipRect(0, 0, 500, 500);
            table.print(g2);
            g2.setClip(oldClip);
            
            g2.dispose();
            cb.restoreState();
            
            document.newPage();
            
            // Create the graphics with pdf fonts
            cb.saveState();
            g2 = cb.createGraphics(500, 500);
            
            // Print the table to the graphics
            oldClip = g2.getClip();
            g2.clipRect(0, 0, 500, 500);
            table.print(g2);
            g2.setClip(oldClip);
            
            g2.dispose();
            cb.restoreState();
            
        } catch (Exception e) {
        	e.printStackTrace();
            System.err.println(e.getMessage());
        }
        
        document.close();
    }
    
    /**
     * Exit app
     */
    private void exit() {
        System.exit(0);
    }    
	/**
	 * A very simple PdfPTable example.
	 * 
	 * @param args
	 *            no arguments needed
	 */
	public static void main(String[] args) {
        JTable2Pdf frame = new JTable2Pdf();
        frame.pack();
        frame.setVisible(true);
        frame.print();
        frame.exit();
	}
}
This is all the code, but I guess only the function print() is important to answer my questions:
1. Why when g2 is created they use cb.createGraphicsShapes(500, 500) but when it is changed later on they use g2 = cb.createGraphics(500, 500)

2. I can't figure out how to resize my JTable in the pdf file. When I change the arguments of createGraphicsShapes(x, y), i get the table clipped off and also its location in the page changes.

3. Is there any way to print also the JTable header, because now only the table contents are printed to the .pdf file.

I'd be really grateful if you could answer at least one of my questions!
Thanks in advance!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 24 2007
Added on Aug 8 2006
2 comments
4,807 views