2

我有一个表单,用户可以在其中填写数据字段。此后,他/她将能够将数据导出为我已经编写的 pdf 文件,如下所示:

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);
}

现在,这为我提供了 pdf 导出以及所有数据。我还想创建一个按钮,允许用户打印在这些字段中输入的数据。现在,这应该是表单上的打印按钮,而不是要求用户导出然后打印。

有人可以建议我如何创建此打印按钮吗?我应该只使用 pdf 导出的输出然后将其发送到打印机吗?如果是这样,我该如何在java中编写它?

4

1 回答 1

5

那么您可以通过简单的方式创建一个按钮:

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

然后ActionListener在按钮上添加一个:

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

然后要打印 PDF,您可以使用此方法:

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");
    }
}

附录:

  • 要使其在可能没有“离我最近的打印机”的特定打印机上工作:更改此代码以包含您的打印机名称,或分别使用contains()or的确切打印机名称equals()

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

参考:

于 2012-07-09T13:54:27.637 回答