Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

java - How can I print JasperPrint directly to printer?

I use Java to create report with JasperReports. What i want to do is that user be able to print directly, without print dialog.
I create JasperPrint and I know name and model of my printer.

I have also looked in the sample here but could not figure out how.
I use Java 1.7 and latest JasperReports library.

Does anyone know how to do it?

public class PrintApp  {

    public static void print() {
        JasperPrint jasperPrint = getJasperPrint();
            String printername = AllPrinter.getDepartmentPrinter("Admin");
             // where should i introduce my printer name to jasperreports?
            JasperPrintManager.printReport(jasperPrint, false);
    }

    private static JasperPrint getJasperPrint() {
            return JasperPrinterCreator.getJasperprint();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solved it as below, hopefully it helps someone else.

public class PrintApp  {

    public static void print() {
            JasperPrint jasperPrint = getJasperPrint();
            String selectedPrinter = AllPrinter.getDepartmentPrinter("Admin");

            PrinterJob printerJob = PrinterJob.getPrinterJob();
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
            PrintService selectedService = null;

            if(services.length != 0 || services != null)
            {
                for(PrintService service : services){
                    String existingPrinter = service.getName().toLowerCase();
                    if(existingPrinter.equals(selectedPrinter))
                    {
                        selectedService = service;
                        break;
                    }
                }

                if(selectedService != null)
                {
                    printerJob.setPrintService(selectedService);
                    boolean printSucceed = JasperPrintManager.printReport(mainPrint, false);
                }
    }

    private static JasperPrint getJasperPrint() {
            return JasperPrinterCreator.getJasperprint();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...