Example usage for javax.print PrintService createPrintJob

List of usage examples for javax.print PrintService createPrintJob

Introduction

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

Prototype

public DocPrintJob createPrintJob();

Source Link

Document

Creates and returns a PrintJob capable of handling data from any of the supported document flavors.

Usage

From source file:ru.trett.cis.services.PrinterServiceImpl.java

@Override
public String print(String file) throws ApplicationException, FileNotFoundException, PrintException {
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.ISO_A4);
    PrintService printServices = PrintServiceLookup.lookupDefaultPrintService();
    if (printServices == null)
        throw new ApplicationException("Default printer not found");
    LOGGER.info("Default printer is " + printServices.getName());
    DocPrintJob printJob = printServices.createPrintJob();
    FileInputStream fis = new FileInputStream(file);
    Doc doc = new SimpleDoc(fis, flavor, null);
    printJob.print(doc, aset);//from   w w  w.j ava  2  s  .c o m
    return printServices.getName();
}

From source file:JuliaSet3.java

public void printToService(PrintService service, PrintRequestAttributeSet printAttributes) {
    // Wrap ourselves in the PrintableComponent class defined by JuliaSet2.
    String title = "Julia set for c={" + cx + "," + cy + "}";
    Printable printable = new PrintableComponent(this, title);

    // Now create a Doc that encapsulate the Printable object and its type
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    Doc doc = new SimpleDoc(printable, flavor, null);

    // Java 1.1 uses PrintJob.
    // Java 1.2 uses PrinterJob.
    // Java 1.4 uses DocPrintJob. Create one from the service
    DocPrintJob job = service.createPrintJob();

    // Set up a dialog box to monitor printing status
    final JOptionPane pane = new JOptionPane("Printing...", JOptionPane.PLAIN_MESSAGE);
    JDialog dialog = pane.createDialog(this, "Print Status");
    // This listener object updates the dialog as the status changes
    job.addPrintJobListener(new PrintJobAdapter() {
        public void printJobCompleted(PrintJobEvent e) {
            pane.setMessage("Printing complete.");
        }/*  w  w w  .  j  ava  2s . c  o m*/

        public void printDataTransferCompleted(PrintJobEvent e) {
            pane.setMessage("Document transfered to printer.");
        }

        public void printJobRequiresAttention(PrintJobEvent e) {
            pane.setMessage("Check printer: out of paper?");
        }

        public void printJobFailed(PrintJobEvent e) {
            pane.setMessage("Print job failed");
        }
    });

    // Show the dialog, non-modal.
    dialog.setModal(false);
    dialog.show();

    // Now print the Doc to the DocPrintJob
    try {
        job.print(doc, printAttributes);
    } catch (PrintException e) {
        // Display any errors to the dialog box
        pane.setMessage(e.toString());
    }
}

From source file:org.apache.camel.component.printer.PrinterProducer.java

private DocPrintJob assignPrintJob(PrintService printService) {
    return printService.createPrintJob();
}

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

/**
 * @param args// www  . j a  va  2  s  . 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.openmrs.module.jembiregistration.api.impl.JembiRegistrationServiceImpl.java

/**
 * Prints a barcode for a given patient.
 * //from w  w w.j  a va2 s  .  co  m
 * @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 {/* w  w w . ja va  2s  . c om*/
        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.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 w  w  .  ja va2  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);/*w w w .ja  va2  s . c o  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;
}