Create Pdf document from JTable : to PDF « PDF « Java Tutorial






import java.awt.BorderLayout;
import java.awt.Graphics2D;
import java.io.FileOutputStream;

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

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;

public class MainClass extends JFrame {
  private JTable table;

  public static void main(String[] args) throws Exception {
    MainClass frame = new MainClass();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  public MainClass() throws Exception {
    getContentPane().setLayout(new BorderLayout());

    Object[][] data = { { "A", "B", "C", new Integer(5), new Boolean(false) },
        { "D", "E", "F", new Integer(3), new Boolean(true) } };

    String[] columnNames = { "First Name", "Last Name", "Sport", "# of Years", "Vegetarian" };

    table = new JTable(data, columnNames);

    JPanel tPanel = new JPanel(new BorderLayout());
    tPanel.add(table.getTableHeader(), BorderLayout.NORTH);
    tPanel.add(table, BorderLayout.CENTER);

    getContentPane().add(tPanel, BorderLayout.CENTER);

    Document document = new Document();
    PdfWriter writer;

    writer = PdfWriter.getInstance(document, new FileOutputStream("my_jtable_shapes.pdf"));

    // writer = PdfWriter.getInstance(document, new
    // FileOutputStream("my_jtable_fonts.pdf"));

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