Java PDF: Envoyer le contenu d’une JTable dans un document PDF

Author:

Java PDF: Envoyer le contenu d'une JTable dans un document PDF


/***** Code de MesExemples.com *******/
/**
* @(#)JavaJTableToPDF.java
*
*
* @author
*sakoba(java.mesexemples.com) @version 1.00 2013/4/30
*/

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

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

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfWriter;

public class JavaJTableToPDF extends JFrame {
private JTable table;

public JavaJTableToPDF() {
getContentPane().setLayout(new BorderLayout());
createTable();
}
private void createTable() {
// Le contenu de JTable
Object[][] data = {{ "a", "b", "e", 4, false }
,{ false, 1.4, "b", "e", "J" } };
// Les titres des colonnes
String[] colonnes = { "A", "B", "C", "D", "E" };

table = new JTable(data, colonnes);

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

getContentPane().add(tPanel, BorderLayout.CENTER);
}
private void print() {
Document document = new Document(PageSize.A4.rotate());
try {
PdfWriter pdf_writer = PdfWriter.getInstance(document,
new FileOutputStream("c:/jTable.pdf"));

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

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

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

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

g2.dispose();
cb.restoreState();
JOptionPane.showMessageDialog(null, "JTable exprté vers PDF avec
succès");
} catch (Exception e) {
System.err.println(e.getMessage());
}
document.close();
}
public static void main(String[] args) {
JavaJTableToPDF frame = new JavaJTableToPDF();
frame.pack();
frame.setVisible(true);
frame.print();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *