JTable to PDF converter

2019-03-05 22:17发布

问题:

I have a problem in Java code to convert JTable to PDF. It throws NullPointerException and same code works in another page no difference at all in both.

The code

private void print() {
    Document document = new Document();
    try {
    PdfWriter writer = PdfWriter.getInstance(document, 
        new FileOutputStream("jTable.pdf"));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    cb.saveState();
    Graphics2D g2 = cb.createGraphicsShapes(800, 500);
    Shape oldClip = g2.getClip();
    g2.clipRect(0, 0, 800, 500);
    table.print(g2);
    g2.setClip(oldClip);
    g2.dispose();
    cb.restoreState();
    } catch (Exception e) {
    e.printStackTrace();
    }

    document.close();
}