How do I print a JTable in the form: Image + header + table in a single page (Java Swing)

39 views Asked by At

I found this exact question before here but the only answer on it did not work for me, the solution suggested (that linked to this other answer) appended each element that I wanted (Image, title/header and table) to a different pages, while I want them all on he same page. I managed to get the image, the header and the date on the same pintable so the only thing left is appending the JTable to this page. Here's the print function:

public void printDay(){
        Paper p1 = new Paper();
        p1.setImageableArea(0, 0, p1.getWidth(), p1.getHeight());
        PageFormat pf1 = new PageFormat();
        pf1.setPaper(p1);

        PrinterJob pj = PrinterJob.getPrinterJob();
        Book book = new Book();
        book.append(new header(date,table), pf1);
        book.append(table.getPrintable(JTable.PrintMode.FIT_WIDTH,null,null), pf1);
        pj.setPageable(book);
        try{
        pj.print();
        } catch(PrinterException e){
            JOptionPane.showMessageDialog(null,"Printer Error","Error",JOptionPane.ERROR_MESSAGE);
        }
    }

And here's the printable header

public class header implements Printable {

    Font font = new Font("SansSerif", Font.PLAIN, 30);
    Font font1 = new Font("SansSerif", Font.PLAIN, 10);
    ImageIcon icon = new ImageIcon("headerLogo.png");
    Image image = icon.getImage();
    String date;
    JTable table;

    public header(String t,JTable T){
        date=t;
        table=T;
    }
 @Override
    public int print(Graphics g, PageFormat pf, int pageIndex)
        throws PrinterException {
        Graphics2D g2d = (Graphics2D) g;
        g2d.translate(pf.getImageableX(), pf.getImageableY());
        g2d.setColor(Color.BLACK);
        g2d.drawImage(image, 0, 0, null);
        g2d.setFont(font);
        g2d.setColor(Color.black);
        g2d.drawString("Big Title here", 165, 190);
        g2d.setColor(Color.gray);
        g2d.setFont(font1);
        g2d.drawString(date, 450, 210);
        return Printable.PAGE_EXISTS;
    }
}

this is roughly how the pdf comes out after running the code:

I have tried a different approach where I made the JTable a bufferedImage and made it part of the printable, but it had a lot of problems like resizing the image ruining it's resolution making it unreadable (especially in the intended language). So I went back to trying to get the table.getPrintable() to work. this is all I'm looking for in my result:

0

There are 0 answers