Fitting a JTable in an iText PDF Document

前端 未结 1 1230
無奈伤痛
無奈伤痛 2021-01-26 13:47

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 pr

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-26 14:22

    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);
            }
    
        }
    };
    

    0 讨论(0)
提交回复
热议问题