How can I print the contents of a JTable as a report with title,date/time etc. as a formatted report on a paper?
- You can get the the PrintJob.
- Get the printed pages dimensions.
- Get the graphics from the PrintJob.
- Get the Table Model from the JTable
Cycle though the rows and columns of the table model asking for the values using getValueAt(row, col)and print them. While printing do the following -
- Print the header using the java.awt.Graphics classes methods like drawString(...)
Print as many rows of data as will fit on the page leaving enough room for the footer.
You will have to obviously take care of
formatting the data yourself in terms of
tabbing, right/left/center justification based on data type, decimal point etc. You will also have to deal with keeping track of X and Y coordinates of each row and column.
- Print the footer
- Flush and dispose the graphics
- Get new graphics and repeat the process until all the data is printed
- call end() on the PrintJob to actually print it.
This is the procedure for JDK1.1. For JDK1.2 use the PrinterJob, PageAttributes and JobAttributes classes. They give better control over formating of page in terms of margin etc.
You can always use third party tools for this.