1

I have a JTable that has four columns. I am using iText libraries to print PDF documents with data from the JTable. The problem is that the JTable is not showing properly in the PDF. I have searched on Google and came across the same situation here. The code is similar to mine as well as the output. I have also tried this example using Templates, however, the result is not changing.

How do we solve this? Please assist. If the codes are necessary, i will post but they are too many classes -i am working on a big application. The concept I would want is to make the JTable fit on the document.

Community
  • 1
  • 1
CN1002
  • 1,115
  • 3
  • 20
  • 40
  • *I am using iTex libraries* - do you actually mean **iText**? Or is there some other library, maybe in the context of TeX, you refer to? – mkl Feb 11 '15 at 08:16
  • @mkl thanks I missed **t**, let me put it – CN1002 Feb 11 '15 at 09:08

1 Answers1

4

After a long struggle, I managed to make it as shown below. In case someone encounters this, here is the idea that saved me:

public void actionPerformed(ActionEvent e) {

        try {
            Document doc = new Document();
            PdfWriter.getInstance(doc, new FileOutputStream("table.pdf"));
            doc.open();
            PdfPTable pdfTable = new PdfPTable(table.getColumnCount());
            //adding table headers
            for (int i = 0; i < table.getColumnCount(); i++) {
                pdfTable.addCell(table.getColumnName(i));
            }
            //extracting data from the JTable and inserting it to PdfPTable
            for (int rows = 0; rows < table.getRowCount() - 1; rows++) {
                for (int cols = 0; cols < table.getColumnCount(); cols++) {
                    pdfTable.addCell(table.getModel().getValueAt(rows, cols).toString());

                }
            }
            doc.add(pdfTable);
            doc.close();
            System.out.println("done");
        } catch (DocumentException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MainWindow.class.getName()).log(Level.SEVERE, null, ex);
        }

    }
};
CN1002
  • 1,115
  • 3
  • 20
  • 40
  • I tried your code. I got one problem and fixed it by using table.getRowCount() instead of table.getRowCount()-1 . – Junaid Apr 27 '16 at 05:50
  • @Junaid Okay, that is nice. I wrote that code when things could not come out the way I wanted. It was hard and I was a Java junior :)- – CN1002 Apr 30 '16 at 12:23