2

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?

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
Pita
  • 498
  • 5
  • 11
  • 21

1 Answers1

5

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:

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • only problem is, you have defined a path to the file, but in my case, the pdf is generated on immediately when the export button is clicked, so how shall i define where the pdf is or rather the location to it? is there a way that I can say the generated output (pdf) shall be printed? – Pita Jul 09 '12 at 14:14
  • what do you mean? why not just create and save the PDF in a temp location, print it (using temp location) and delete the temp file after print is done? – David Kroukamp Jul 09 '12 at 14:16
  • Also, I have just created the PDF Class, but its underlining svcName saying svcName cannot be resolved to a variable. could you please explain how i should solve that issue please? – Pita Jul 09 '12 at 14:17
  • @Priya if you investigate further about the PrintService class and this code, you will find that you can send an InputStream (maybe a ByteArrayInputStream filled with your binary data i.e. byte[] generatedPDF), not neccesarily a file. – Luiggi Mendoza Jul 09 '12 at 14:23
  • Ok, many thanks for the info. I shall have a read around this topic :) – Pita Jul 09 '12 at 14:27
  • 1
    @Priya this article is very helpful: [Printing in Java](http://www.javaworld.com/jw-10-2000/jw-1020-print.html) – Luiggi Mendoza Jul 09 '12 at 14:29
  • do you know what i need to replace svcName with? – Pita Jul 09 '12 at 14:39
  • well i dont know. it underlines svcName and says svcName cannot be resolved to a variable – Pita Jul 09 '12 at 15:21
  • 1
    @Priya edited the code see edited code, just had to change the order of the `println` and `svcName` assigning – David Kroukamp Jul 09 '12 at 15:29
  • @DavidKroukamp - i tried it and it all compiles and works, but its not really printing though. as soon as i click on the print button it shows me this, but not doing anything: service found: Win32 Printer : PDF24 PDF service found: Win32 Printer : PDF24 Fax service found: Win32 Printer : Microsoft XPS Document Writer service found: Win32 Printer : Fax service found: Win32 Printer : An OneNote 2010 senden service found: Win32 Printer : \\SMMS001\Multifunktion 3.08 A3 PCL service found: Win32 Printer : \\SMMS001\Multifunktion 3.08 A4 PCL no printer services found – Pita Jul 09 '12 at 15:53