Example usage for javax.print DocPrintJob print

List of usage examples for javax.print DocPrintJob print

Introduction

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

Prototype

public void print(Doc doc, PrintRequestAttributeSet attributes) throws PrintException;

Source Link

Document

Prints a document with the specified job attributes.

Usage

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

/**
 * Prints a barcode for a given patient.
 * /*from w  w w. ja v  a 2 s.  c om*/
 * @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.openmrs.module.pharmacy.page.controller.PharmacyGroupPageController.java

void printOrder(int orderID) {

    try {//from   w  w w. j a v  a 2s.  c o m
        DrugOrder order = (DrugOrder) Context.getOrderService().getOrder(orderID);
        drugorders drugorder = Context.getService(drugordersService.class).getDrugOrderByOrderID(orderID);

        PrintService service = PrintServiceLookup.lookupDefaultPrintService();

        String OrderDetails = drugorder.getDrugName().getDisplayString() + " " + order.getDose() + " "
                + order.getDoseUnits().getDisplayString() + " " + order.getDuration() + " "
                + order.getDurationUnits().getDisplayString() + " " + order.getQuantity() + " "
                + order.getQuantityUnits() + "\n" + "Route: " + order.getRoute().getDisplayString() + " "
                + "Frequency: " + order.getFrequency().getName() + "\n" + "Start Date: "
                + drugorder.getStartDate().toString() + "\n" + "Patient Instructions: "
                + drugorder.getPatientInstructions();

        try (InputStream is = new ByteArrayInputStream(OrderDetails.getBytes())) {
            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
            pras.add(new Copies(1));

            if (service != null) {
                DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
                Doc doc = new SimpleDoc(is, flavor, null);
                DocPrintJob job = service.createPrintJob();

                job.print(doc, pras);
            }
        }

    } catch (IOException | PrintException ex) {
        Logger.getLogger(PharmacyGroupPageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.openmrs.module.pharmacy.page.controller.PharmacySinglePageController.java

void printOrder(int orderID) {

    try {// w w w.  j a  va2s  . c o m
        DrugOrder order = (DrugOrder) Context.getOrderService().getOrder(orderID);
        drugorders drugorder = Context.getService(drugordersService.class).getDrugOrderByOrderID(orderID);

        PrintService service = PrintServiceLookup.lookupDefaultPrintService();

        String OrderDetails = drugorder.getDrugName().getDisplayString() + " " + order.getDose() + " "
                + order.getDoseUnits().getDisplayString() + " " + order.getDuration() + " "
                + order.getDurationUnits().getDisplayString() + " " + order.getQuantity() + " "
                + order.getQuantityUnits() + "\n" + "Route: " + order.getRoute().getDisplayString() + " "
                + "Frequency: " + order.getFrequency().getName() + "\n" + "Start Date: "
                + drugorder.getStartDate().toString() + "\n" + "Patient Instructions: "
                + drugorder.getPatientInstructions();

        InputStream is = new ByteArrayInputStream(OrderDetails.getBytes());

        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        pras.add(new Copies(1));

        if (service != null) {
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            Doc doc = new SimpleDoc(is, flavor, null);
            DocPrintJob job = service.createPrintJob();

            job.print(doc, pras);
        }
        is.close();

    } catch (IOException | PrintException ex) {
        Logger.getLogger(PharmacySinglePageController.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

/**
 * Opens the drawer./*from w  ww .  ja  va2  s  . co 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.reporting.engine.classic.extensions.modules.java14print.Java14PrintUtil.java

public static void printDirectly(final MasterReport report, PrintService printService)
        throws PrintException, ReportProcessingException {
    // with that method we do not use the PrintService UI ..
    // it is up to the user to supply a valid print service that
    // supports the Pageable printing.
    if (printService == null) {
        printService = lookupPrintService();
    } else {//from  w ww.  ja  v  a2 s.c  o m
        if (printService.isDocFlavorSupported(DocFlavor.SERVICE_FORMATTED.PAGEABLE) == false) {
            throw new PrintException("The print service implementation does not support the Pageable Flavor.");
        }
    }

    PrintRequestAttributeSet attributes = Java14PrintUtil.copyConfiguration(null, report);
    attributes = Java14PrintUtil.copyAuxillaryAttributes(attributes, report);

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

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

}

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  ww  w.j  a v  a 2  s  .  c  om*/
    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.springframework.integration.print.outbound.PrintMessageHandler.java

@Override
protected void handleMessageInternal(Message<?> message) throws Exception {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Printing using printer '" + this.printServiceExecutor.getPrintService().getName() + "'.");
    }/*w  w  w . ja v a2s  . com*/

    DocAttributeSet das = new HashDocAttributeSet();
    das.add(Chromaticity.MONOCHROME);

    Object payload = message.getPayload();

    final Doc doc = new SimpleDoc(message.getPayload(), docFlavor, das);

    final DocPrintJob job = this.printServiceExecutor.getPrintService().createPrintJob();

    PrintJobMonitor printJobMonitor = new PrintJobMonitor(job);

    job.print(doc, this.printRequestAttributeSet);

    printJobMonitor.waitForDone();

    if (payload instanceof InputStream) {
        ((InputStream) payload).close();
    }

}

From source file:us.mn.state.health.lims.common.provider.reports.SampleLabelPrintProvider.java

private void runPrintJobs() throws PrintException {
    returnedData += ";;";

    if (masterCount > 0) {
        DocPrintJob masterJob = ps.createPrintJob();

        PrintRequestAttributeSet masterAset = new HashPrintRequestAttributeSet();
        masterAset.add(new Copies(masterCount));

        String masterLabel = "";
        String masterZPL = StringUtil.getMessageForKey("master.label.zpl.prefix"); //"^XA";
        for (Property prop : masterPrintOrder) {
            if (ConfigurationProperties.getInstance().isPropertyValueEqual(prop, "true")) {
                masterLabel += (!GenericValidator.isBlankOrNull(labelData.get(prop.name().toString()))
                        ? labelData.get(prop.name().toString())
                        : "") + "\n";
                if (prop.equals(Property.MASTER_LABELS_ACCESSION)) {
                    masterZPL += StringUtil.getMessageForKey("master.label.zpl.accession.barcode.prefix") //"^FO20,30^BCN,60,N,N,N^FD"
                            + labelData.get(prop.name().toString())
                            + StringUtil.getMessageForKey("master.label.zpl.accession.text.prefix") //"^FS^FO30,90^AEN,12,18^FD"
                            + labelData.get(prop.name().toString())
                            + StringUtil.getMessageForKey("master.label.zpl.accession.suffix"); //"^FS";
                } else {
                    masterZPL += StringUtil.getMessageForKey("master.label.zpl.other.prefix") //"^FO25,195^AEN,12,18^FD"
                            + labelData.get(prop.name().toString())
                            + StringUtil.getMessageForKey("master.label.zpl.other.suffix"); //"^FS";
                }/*from ww  w  .  j av  a  2  s  .co m*/
            }
        }
        masterZPL += StringUtil.getMessageForKey("master.label.zpl.suffix"); //"^XZ";

        // Printing raw ZPL and returning the ZPL string that can be displayed via JavaScript as a simulated label in the browser
        //         System.out.println("Master Label (" + masterCount + " copies):\n" + masterLabel);
        //         System.out.println("Master Label ZPL (" + masterCount + " copies):\n" + masterZPL + "\n");
        returnedData += masterZPL;

        byte[] byt = masterZPL.getBytes();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(byt, flavor, null);
        masterJob.addPrintJobListener(new MyPrintJobListener());
        masterJob.print(doc, masterAset);
    }

    returnedData += ";;";

    for (int j = 1; j <= itemCount; j++) {
        DocPrintJob itemJob = ps.createPrintJob();
        PrintRequestAttributeSet itemAset = new HashPrintRequestAttributeSet();
        itemAset.add(new Copies(1));

        String itemLabel = "";
        String itemZPL = StringUtil.getMessageForKey("item.label.zpl.prefix"); //"^XA";
        for (Property prop : itemPrintOrder) {
            if (ConfigurationProperties.getInstance().isPropertyValueEqual(prop, "true")) {
                itemLabel += !GenericValidator.isBlankOrNull(labelData.get(prop.name().toString()))
                        ? labelData.get(prop.name().toString())
                        : "";
                if (prop.equals(Property.SPECIMEN_LABELS_ACCESSION)) {
                    itemLabel += "-" + j;
                    itemZPL += StringUtil.getMessageForKey("item.label.zpl.accession.barcode.prefix") //"^FO20,30^BCN,60,N,N,N^FD"
                            + labelData.get(prop.name().toString()) + "-" + j
                            + StringUtil.getMessageForKey("item.label.zpl.accession.text.prefix") //"^FS^FO30,90^AEN,12,18^FD"
                            + labelData.get(prop.name().toString()) + "-" + j
                            + StringUtil.getMessageForKey("item.label.zpl.accession.suffix"); //"^FS";
                } else {
                    itemZPL += StringUtil.getMessageForKey("item.label.zpl.other.prefix") //"^FO25,195^AEN,12,18^FD"
                            + labelData.get(prop.name().toString())
                            + StringUtil.getMessageForKey("item.label.zpl.other.suffix"); //"^FS";
                }
                itemLabel += "\n";
            }
        }
        itemZPL += StringUtil.getMessageForKey("item.label.zpl.suffix"); //"^XZ";

        // Printing raw ZPL and returning a ZPL string that can be displayed via JavaScript as a simulated label in the browser
        //         System.out.println("Item Label:\n" + itemLabel);            
        //         System.out.println("Item Label ZPL:\n" + itemZPL + "\n");
        returnedData += "::" + itemZPL;

        byte[] byt = itemZPL.getBytes();
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(byt, flavor, null);
        itemJob.addPrintJobListener(new MyPrintJobListener());
        itemJob.print(doc, itemAset);
    }

    //String label = SystemConfiguration.getInstance()
    //      .getDefaultSampleLabel(accessionNumber);

    //byte[] byt = label.getBytes();
    //DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    //Doc doc = new SimpleDoc(byt, flavor, null);
    //job.addPrintJobListener(new MyPrintJobListener());
    //job.print(doc, aset);
}

From source file:us.mn.state.health.lims.common.provider.reports.SampleLabelPrintProvider.java

public void printBarcodeLabel(String[] accList) {
    try {/* w  w w .  j av a2s .c o m*/

        // Support with 3 labels per row for now
        int itemsperrow = 3;

        String numberOfLabelCopiesString = null;
        int numberOfLabelCopies = 1;
        try {
            numberOfLabelCopiesString = SystemConfiguration.getInstance()
                    .getLabelNumberOfCopies("print.label.numberofcopies");
            numberOfLabelCopies = Integer.parseInt(numberOfLabelCopiesString);
        } catch (NumberFormatException nfe) {
            // System.out.println("numberOfLabelCopies not defined as
            // numeric");
        }

        String accessionNumber = "fail";// (String)

        int labelPerPatient = 1;
        try {
            labelPerPatient = masterCount;
        } catch (NumberFormatException nfe) {
            labelPerPatient = 1;
        }

        if (ps == null) {
            // System.out.println("Zebra printer is not found.");
            return;
        }

        ArrayList listAccessNumber = new ArrayList<>();

        for (int i = 0; i < accList.length; i++) {
            listAccessNumber.add(accList[i]);
        }

        ArrayList<String> newListAccessNumber = new ArrayList<String>();
        Iterator iter = listAccessNumber.iterator();
        while (iter.hasNext()) {
            String element = (String) iter.next();
            for (int i = 0; i < labelPerPatient; i++) {
                newListAccessNumber.add(element);
            }
        }
        int sizeListAcc = newListAccessNumber.size();

        if (sizeListAcc % itemsperrow != 0) {
            for (int i = 0; i < (itemsperrow - (sizeListAcc % itemsperrow)); i++) {
                newListAccessNumber.add("");
            }
        }
        String accessionNumber1 = "";
        String accessionNumber2 = "";
        String accessionNumber3 = "";

        for (int i = 0; i < newListAccessNumber.size(); i = i + itemsperrow) {
            accessionNumber1 = newListAccessNumber.get(i).toString();
            accessionNumber2 = newListAccessNumber.get(i + 1).toString();
            accessionNumber3 = newListAccessNumber.get(i + 2).toString();
            DocPrintJob job = ps.createPrintJob();
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            //aset.add(new Copies(numberOfLabelCopies * labelPerPatient));
            aset.add(new Copies(numberOfLabelCopies * 1));
            String label = "";
            if (itemsperrow == 3) {
                label = SystemConfiguration.getInstance().getAllDefaultSampleLabel(accessionNumber1,
                        accessionNumber2, accessionNumber3);
                returnedData += label;
            } else {
                return;
            }
            System.out.println(returnedData);

            byte[] byt = label.getBytes();
            DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
            Doc doc = new SimpleDoc(byt, flavor, null);
            job.addPrintJobListener(new MyPrintJobListener());
            job.print(doc, aset);
            //System.out.println("success...");
        }

    } catch (Exception e) {
        System.out.println("Error in SampleLabelPrintProvider");
        e.printStackTrace();
    } finally {

    }
}