How can I print the contents of a JTable as a report with title,date/time etc. as a formatted report on a paper?

Sandip Chitale

  1. You can get the the PrintJob.
  2. Get the printed pages dimensions.
  3. Get the graphics from the PrintJob.
  4. Get the Table Model from the JTable
  5. 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 -
    1. Print the header using the java.awt.Graphics classes methods like drawString(...)
    2. 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.
    3. Print the footer
    4. Flush and dispose the graphics
    5. Get new graphics and repeat the process until all the data is printed
  6. 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.