I am developing a desktop app in Java for my project work. I need to print an invoice with sub total and total fields along with tabular data from JTable
. I am able to print the table but not in the same page. i.e JTable prints in first page and subtotal, total prints in next page. Is there a way to print both data in the same page. I dont want to use reporting engines. Just use the inbuilt java printing services. Please guide me.
Print Format as I want:
Following figure shows the GUI
And following figure shows the report i am getting till now. Its not in correct format. Please help
Code is as follows
JLabel title = new JLabel();
title.setText("Invoice");
title.setBounds(300, 200, 80, 30);
JTextField subTotal = new JTextField();
subTotal.setText("Sub Total : Rs. " + SubTotal.getText());
subTotal.setBounds(400, 200, 150, 30);
MyPrintable prt = new MyPrintable();
prt.addComponent(title);
prt.addComponent(billTable); //billTable is the JTable
prt.addComponent(subTotal);
prt.printIt();
And below is the My Printable class
class MyPrintable implements Printable
{
private ArrayList<JComponent> items;
public MyPrintable()
{
items = new ArrayList<>();
}
@Override
public int print(Graphics g, PageFormat pf, int page) throws PrinterException
{
if(page > 0) return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D)g;
g2.translate(pf.getImageableX(), pf.getImageableY());
for(JComponent item : items)
{
item.setLayout(null);
// item.setBounds(500, 500, 200, 200);
item.printAll(g);
g2.translate(0, item.getHeight());
}
return Printable.PAGE_EXISTS;
}
public void printIt()
{
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();;
PrinterJob job = PrinterJob.getPrinterJob();
try
{
job.setPrintable(this);
if(job.printDialog(attributes))
job.print(attributes);
}
catch (PrinterException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
public void addComponent(JComponent component) { items.add(component); }
}
If you want to print all your stuff at the coordinates you've set, you either need to create a new panel, lay out all your component to print in this panel, and than print this panel or you need to translate all the components in your print method to the correct coordinates.
the second way will look like
public int print(Graphics g, PageFormat pf, int page) throws PrinterException
{
if(page > 0) return Printable.NO_SUCH_PAGE;
Graphics2D g2 = (Graphics2D)g;
g2.translate(pf.getImageableX(), pf.getImageableY());
for(JComponent item : items)
{
g2.translate(item.getX(), item.getY());
item.printAll(g);
g2.translate(-item.getX(), -item.getY()); // bring all back to default coordinates
}
return Printable.PAGE_EXISTS;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With