Search code examples
javaswingprintingjbutton

Printing Data in Java


I have a form where the user can fill in the fields with data. Thereafter, he/she shall be able to export the data as a pdf which I have written already as it can be seen below:

public void onSubmit() {
try {
    ManagerModel manager = managerDao.getManager(person);
    PictureModel picture = new PictureModel();
    if (person.getPhotoId() != null) {
        picture = new PictureModel(pictureDao.findPictureById(person.getPhotoId()));
    }
    getRequestCycle().setRequestTarget( new FileRequestTarget(Exporter.exportFile(person, manager, picture), person.getPdfName()));
} catch (Exception e) {
    Log.warn(e);
}

now this provides me with a pdf export along with all data. i like to also create a button which allows the user to print the data which has been entered in those fields. now, that should be a print button on the form rather than requiring the user to export then print.

can someone advise how i can create this print button? should i just use the output from the pdf export then send that to the printer? if so, how do i write that in java?


Solution

  • Well you can create a button by simple:

     import javax.swing.*;
     ....
     JButton button = new JButton("Print");
    

    then add an ActionListener to the button:

    import java.awt.*;
    ....
    button.addActionListener(new ActionListener() {
                @override
                public void actionPerformed(ActionEvent e)
                {
                    //Execute when button is pressed
                    printPDF("path/to/file/.pdf");
                }
            });   
    

    then to print the PDF you could use this method:

    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import javax.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    ....
    public static void printPDF(String file) {
    
        FileInputStream psStream = null;
        try {
            psStream = new FileInputStream(file);
        } catch (FileNotFoundException ffne) {
            ffne.printStackTrace();
        }
        if (psStream == null) {
            return;
        }
        DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
    
        // this step is necessary because I have several printers configured  
        PrintService myPrinter = null;
        for (int i = 0; i < services.length; i++) {
            String svcName = services[i].toString();
            System.out.println("service found: " + svcName);
            if (svcName.contains("printer closest to me")) {
                myPrinter = services[i];
                System.out.println("my printer found: " + svcName);
                break;
            }
        }
        if (myPrinter != null) {
            DocPrintJob job = myPrinter.createPrintJob();
            try {
                job.print(myDoc, aset);
    
            } catch (Exception pe) {
                pe.printStackTrace();
            }
        } else {
            System.out.println("no printer services found");
        }
    }
    

    Addendum:

    • To make this work on a specific printer that might not have "printer closest to me": change this code to include your printers name, or the exact printer name using contains() or equals() respectively:

      String printerName="";
      ....
      if (svcName.contains(printerName)||svcName.equals(printerName)) {
                          myPrinter = services[i];
                          System.out.println("my printer found: " + svcName);
                          break;
      }
      

    References: