Example usage for javax.print PrintServiceLookup lookupPrintServices

List of usage examples for javax.print PrintServiceLookup lookupPrintServices

Introduction

In this page you can find the example usage for javax.print PrintServiceLookup lookupPrintServices.

Prototype

public static final PrintService[] lookupPrintServices(DocFlavor flavor, AttributeSet attributes) 

Source Link

Document

Locates print services capable of printing the specified DocFlavor .

Usage

From source file:org.efaps.tests.Printer.java

/**
 * @param args/* w w w . j a  v a  2s .co m*/
 */
public static void main(final String[] args) {
    final AttributeSet aset = new HashAttributeSet();
    aset.add(new PrinterName("HP-LaserJet-100-colorMFP-M175nw", null));
    final PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, aset);
    for (final PrintService serv : pservices) {
        System.out.println(serv);
    }

    try {
        final PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        // pras.add(new Copies(2));

        final PrintService pservice = getPrintService4Name("HP-LaserJet-100-colorMFP-M175nw");
        pservice.getSupportedDocFlavors();
        final DocPrintJob job = pservice.createPrintJob();

        final DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        final String filename = "/home/janmoxter/Downloads/Notas_de_Pedido_null.DOCX";
        final FileInputStream fis = new FileInputStream(filename);
        final DocAttributeSet das = new HashDocAttributeSet();
        final Doc doc = new SimpleDoc(fis, flavor, das);
        job.print(doc, pras);
    } catch (final FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final PrintException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.efaps.tests.Printer.java

static PrintService getPrintService4Name(final String _name) {
    PrintService ret = null;//  w  ww.  jav  a  2 s.c o  m
    final PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);
    if (!ArrayUtils.isEmpty(pservices)) {
        for (final PrintService serv : pservices) {
            if (serv.getName().equals(_name)) {
                ret = serv;
                break;
            }
        }
    }
    return ret;
}

From source file:org.nuclos.server.report.ejb3.ReportFacadeBean.java

public NuclosReportRemotePrintService lookupDefaultPrintService() throws NuclosReportException {
    PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
    if (ps == null) {
        String defprinter = System.getProperty("javax.print.defaultPrinter");
        if (defprinter != null) {
            PrintService[] prservices = PrintServiceLookup.lookupPrintServices(null, null);
            if (null == prservices || 0 >= prservices.length) {
                throw new NuclosReportException(
                        "Es ist kein passender Print-Service installiert. " + defprinter); // @todo
            }/*from w  ww .  j  a  v a 2 s.c  om*/

            for (int i = 0; i < prservices.length; i++) {
                PrintService printService = prservices[i];
                if (printService.getName().equals(defprinter)) {
                    return new NuclosReportRemotePrintService(printService);
                }
            }
            throw new NuclosReportException(
                    "Es ist kein passender Default Print-Service installiert. " + defprinter); // @todo
        }
        throw new NuclosReportException("Es ist kein passender Default Print-Service installiert."); // @todo
    }
    return new NuclosReportRemotePrintService(ps);
}

From source file:org.nuclos.server.report.ejb3.ReportFacadeBean.java

public NuclosReportRemotePrintService[] lookupPrintServices(DocFlavor flavor, AttributeSet as)
        throws NuclosReportException {
    PrintService prservDflt = PrintServiceLookup.lookupDefaultPrintService();
    PrintService[] prservices = PrintServiceLookup.lookupPrintServices(flavor, as);
    if (null == prservices || 0 >= prservices.length) {
        if (null != prservDflt) {
            prservices = new PrintService[] { prservDflt };
        } else {/*from w w w . j ava 2 s.c  o  m*/
            throw new NuclosReportException("Es ist kein passender Print-Service installiert."); // @todo
        }
    }

    NuclosReportRemotePrintService[] rprservices = new NuclosReportRemotePrintService[prservices.length];
    for (int i = 0; i < prservices.length; i++) {
        rprservices[i] = new NuclosReportRemotePrintService(prservices[i]);
    }
    return rprservices;
}

From source file:org.openmrs.module.jembiregistration.api.impl.JembiRegistrationServiceImpl.java

/**
 * Prints a barcode for a given patient.
 * // ww  w .  j  a  v a2  s  .  com
 * @param patient
 *            The patient for whom the barcode should be printed
 * @return
 */
public void printPatientBarcode(Patient patient) {
    String label = LABEL_TEMPLATE;

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Context.getLocale());

    try {
        /* handle null case */
        if (patient == null) {
            throw new APIException("No patient passed to printPatientBarcode method.");
        }

        log.info("Printing Barcode for patient: " + patient.getId());

        /* Get service and initialize some parameters from global properties */
        String printerName = Context.getAdministrationService()
                .getGlobalProperty("jembiregistration.PrinterName");
        Integer copies, idType;

        try {
            copies = Integer.parseInt(
                    Context.getAdministrationService().getGlobalProperty("jembiregistration.LabelPrintCount"));
            idType = Integer.parseInt(
                    Context.getAdministrationService().getGlobalProperty("jembiregistration.LabelIdType"));
        } catch (NumberFormatException n) {
            log.error("Global property is not valid: " + n.getMessage());

            copies = 1;
            idType = 0;
        }

        /* Name (Only print first and last name */
        String name = (patient.getPersonName().getGivenName() != null ? patient.getPersonName().getGivenName()
                : "") + " "
                + (patient.getPersonName().getFamilyName() != null ? patient.getPersonName().getFamilyName()
                        : "");
        /* Name (Only print first and last name */

        /* Birthdate */
        String birthDateLabel = Context.getMessageSourceService()
                .getMessage("jembiregistration.birthDateShort");
        String birthDate = (df.format(patient.getBirthdate()) + " "
                + (patient.getBirthdateEstimated() ? "(*)" : " "));

        /* Gender */
        String genderLabel = Context.getMessageSourceService().getMessage("Patient.gender");
        String gender = (patient.getGender().equalsIgnoreCase("M")
                ? Context.getMessageSourceService().getMessage("Patient.gender.male")
                : Context.getMessageSourceService().getMessage("Patient.gender.female"));

        /* Primary identifier */
        PatientIdentifier primaryIdentifier = (idType == 0) ? patient.getPatientIdentifier()
                : patient.getPatientIdentifier(Context.getPatientService().getPatientIdentifierType(idType));

        if (primaryIdentifier != null) {
            String nidLabel = primaryIdentifier.getIdentifierType().getName();
            String nid = primaryIdentifier.getIdentifier();

            label = label.replace("*NIDL*", nidLabel);
            label = label.replace("*NID*", nid);
        }

        /* Populate template */
        label = label.replace("*PN*", name);
        label = label.replace("*BDL*", birthDateLabel);
        label = label.replace("*BD*", birthDate);
        label = label.replace("*GL*", genderLabel);
        label = label.replace("*G*", gender);

        try {
            /* Find printer */
            PrintService psZebra = null;
            String sPrinterName = null;
            PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);

            for (int i = 0; i < services.length; i++) {
                PrintServiceAttribute attr = services[i].getAttribute(PrinterName.class);

                sPrinterName = ((PrinterName) attr).getValue();

                log.info("Looking for printer: " + sPrinterName);

                if (sPrinterName.toLowerCase().indexOf(printerName.toLowerCase()) >= 0) {
                    psZebra = services[i];
                    break;
                }
            }

            if (psZebra == null) {
                log.error(
                        "Zebra printer is not found. Barcode could not be printed. Check your global properties to make sure printer names match.");

            }

            /* Send label data to printer */
            for (int i = 1; i <= copies; i++) {

                DocPrintJob job = psZebra.createPrintJob();

                byte[] by = label.getBytes();
                DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
                Doc doc = new SimpleDoc(by, flavor, null);
                job.print(doc, null);
            }
        } catch (PrintException e) {
            log.error("Unable to find or initialise printer.");
            e.printStackTrace();
        }
    } catch (Exception e) {
        log.error("An error occured while attempting to print a barcode.");
        e.printStackTrace();
    }
}

From source file:org.openvpms.web.component.im.till.CashDrawer.java

/**
 * Opens the drawer.//  w ww .j a v a2 s  .c  o m
 *
 * @throws PrintException if the drawer cannot be opened
 */
public void open() throws PrintException {
    AttributeSet attrSet = new HashPrintServiceAttributeSet(new PrinterName(printer, null));
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, attrSet);
    if (printServices.length == 0) {
        throw new PrintException(Messages.format("till.drawerCommand.printernotfound", printer));
    }
    DocPrintJob job = printServices[0].createPrintJob();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(command, flavor, null);
    job.print(doc, null);
}

From source file:org.pentaho.platform.plugin.action.jfreereport.JFreeReportComponent.java

public boolean print(final MasterReport report, final String jobName, final String printerName) {
    boolean result = false;
    if (jobName != null) {
        report.getReportConfiguration().setConfigProperty(PrintUtil.PRINTER_JOB_NAME_KEY,
                String.valueOf(jobName));
    }/*from   w  w  w  .j  av a2 s  .  co m*/

    PrintService printer = null;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE,
            null);
    for (final PrintService service : services) {
        if (service.getName().equals(printerName)) {
            printer = service;
        }
    }
    if ((printer == null) && (services.length > 0)) {
        printer = services[0];
    }

    try {
        Java14PrintUtil.printDirectly(report, printer);
        result = true;
    } catch (PrintException e) {
        //ignore
    } catch (ReportProcessingException e) {
        //ignore
    }
    return result;
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.java14print.Java14PrintUtil.java

private static PrintService lookupPrintService() throws PrintException {
    final PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    if (defaultService != null && defaultService.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE)) {
        return defaultService;
    }/*from   w  w  w  . j ava  2s  .  c  o  m*/

    final PrintService printService;
    final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE,
            null);
    if (services.length == 0) {
        throw new PrintException("Unable to find a matching print service implementation.");
    }
    printService = services[0];
    return printService;
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.java14print.Java14PrintUtil.java

public static boolean print(final MasterReport report, final ReportProgressListener progressListener)
        throws PrintException, ReportProcessingException {
    final PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE,
            null);/*from  w w w .j av  a2  s .co  m*/
    if (services.length == 0) {
        throw new PrintException("Unable to find a matching print service implementation.");
    }
    PrintRequestAttributeSet attributes = Java14PrintUtil.copyConfiguration(null, report);
    attributes = Java14PrintUtil.copyAuxillaryAttributes(attributes, report);

    final PrintService service = ServiceUI.printDialog(null, 50, 50, services, lookupPrintService(),
            DocFlavor.SERVICE_FORMATTED.PAGEABLE, attributes);
    if (service == null) {
        return false;
    }

    final PrintReportProcessor reportPane = new PrintReportProcessor(report);
    if (progressListener != null) {
        reportPane.addReportProgressListener(progressListener);
    }

    try {
        reportPane.fireProcessingStarted();

        final DocPrintJob job = service.createPrintJob();
        final SimpleDoc document = new SimpleDoc(reportPane, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);

        job.print(document, attributes);
    } finally {
        reportPane.fireProcessingFinished();
        reportPane.close();

        if (progressListener != null) {
            reportPane.removeReportProgressListener(progressListener);
        }
    }
    return true;
}

From source file:org.pentaho.reporting.platform.plugin.SimpleReportingAction.java

/**
 * Perform the primary function of this component, this is, to execute. This method will be invoked immediately following a successful validate().
 *
 * @return true if successful execution//from  w w  w .  j a va2 s  . com
 * @throws Exception
 */
public boolean _execute() throws Exception {
    final MasterReport report = getReport();

    try {
        final DefaultParameterContext parameterContext = new DefaultParameterContext(report);
        // open parameter context
        final ValidationResult vr = applyInputsToReportParameters(parameterContext, null);
        if (vr.isEmpty() == false) {
            return false;
        }
        parameterContext.close();

        if (isPrint()) {
            // handle printing
            // basic logic here is: get the default printer, attempt to resolve the user specified printer, default back as needed
            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
            if (StringUtils.isEmpty(getPrinter()) == false) {
                final PrintService[] services = PrintServiceLookup
                        .lookupPrintServices(DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
                for (final PrintService service : services) {
                    if (service.getName().equals(printer)) {
                        printService = service;
                    }
                }
                if ((printer == null) && (services.length > 0)) {
                    printService = services[0];
                }
            }
            Java14PrintUtil.printDirectly(report, printService);
            return true;
        }

        final String outputType = computeEffectiveOutputTarget();
        final ReportOutputHandler reportOutputHandler = createOutputHandlerForOutputType(outputType);
        if (reportOutputHandler == null) {
            log.warn(Messages.getInstance().getString("ReportPlugin.warnUnprocessableRequest", outputType));
            return false;
        }
        synchronized (reportOutputHandler.getReportLock()) {
            try {
                pageCount = reportOutputHandler.generate(report, acceptedPage, outputStream, getYieldRate());
                return pageCount != -1;
            } finally {
                reportOutputHandler.close();
            }
        }
    } catch (Throwable t) {
        log.error(Messages.getInstance().getString("ReportPlugin.executionFailed"), t); //$NON-NLS-1$
    }
    // lets not pretend we were successfull, if the export type was not a valid one.
    return false;
}