Java Code Examples for javax.print.Doc

The following are top voted examples for showing how to use javax.print.Doc. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: bisis-v4   File: Printer2.java   View source code 8 votes vote down vote up
@Override
public boolean print(Label label, String codePage) {
  if (psBarCode == null) {
    System.err.println("Barcode printer not found");
    return false;
  }
  try {
    byte[] bytes = label.getCommands().getBytes("cp" + codePage);
    DocPrintJob job = psBarCode.createPrintJob();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(bytes, flavor, null);
    job.print(doc, null);
  } catch (Exception e) {
    e.printStackTrace();
    return false;
  }
  return true;
}
 
Example 2
Project: cn1   File: WinPrintJob.java   View source code 6 votes vote down vote up
public void print(final Doc doc, final PrintRequestAttributeSet attributes)
                throws PrintException {
    synchronized (lock) {
        if (printer != null) {
            throw new PrintException("Printer is busy"); //$NON-NLS-1$
        } else {
            final DocFlavor flavor = doc.getDocFlavor();

            if ((flavor == null) || !service.isDocFlavorSupported(flavor)) {
                throw new PrintException("Doc flavor is not supported"); //$NON-NLS-1$
            }

            printer = new Printer(doc, attributes);
            printer.print();
        }
    }
}
 
Example 3
Project: cn1   File: AttributeSetUtilitiesTest.java   View source code 6 votes vote down vote up
public final void testVerifyAttributeCategory3() {

        //fails in "some" invironment
        //see AttributeSetUtilities, line 337-339

        try {
            AttributeSetUtilities.
                verifyAttributeCategory(SimpleDoc.class, Doc.class);
            fail("method doesn't throw ClassCastException if object " +
                    "is a Class that implements interfaceName but " +
                        "interfaceName is not a class that implements " +
                            "interface Attribute");
        } catch (ClassCastException e) {
            //System.out.println("testVerifyAttributeCategory3 - " + e.toString());
        }

    }
 
Example 4
Project: zebra-zpl   File: ZebraUtils.java   View source code 6 votes vote down vote up
/**
 * Function to print code Zpl to local zebra(usb)
 * 
 * @param zpl
 *            code Zpl to print
 * @param ip
 *            ip adress
 * @param port
 *            port
 * @throws ZebraPrintException
 *             if zpl could not be printed
 */
public static void printZpl(String zpl, String printerName) throws ZebraPrintException {
	try {

		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();
			if (sPrinterName.toLowerCase().indexOf(printerName) >= 0) {
				psZebra = services[i];
				break;
			}
		}

		if (psZebra == null) {
			throw new ZebraPrintNotFoundException("Zebra printer not found : " + printerName);
		}
		DocPrintJob job = psZebra.createPrintJob();

		byte[] by = zpl.getBytes();
		DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
		Doc doc = new SimpleDoc(by, flavor, null);
		job.print(doc, null);

	} catch (PrintException e) {
		throw new ZebraPrintException("Cannot print label on this printer : " + printerName, e);
	}
}
 
Example 5
Project: freeVM   File: AttributeSetUtilitiesTest.java   View source code 6 votes vote down vote up
public final void testVerifyAttributeCategory3() {

        //fails in "some" invironment
        //see AttributeSetUtilities, line 337-339

        try {
            AttributeSetUtilities.
                verifyAttributeCategory(SimpleDoc.class, Doc.class);
            fail("metod doesn't throw ClassCastException if object " +
                    "is a Class that implements interfaceName but " +
                        "interfaceName is not a class that implements " +
                            "interface Attribute");
        } catch (ClassCastException e) {
            //System.out.println("testVerifyAttributeCategory3 - " + e.toString());
        }

    }
 
Example 6
Project: freeVM   File: WinPrintJob.java   View source code 6 votes vote down vote up
public void print(final Doc doc, final PrintRequestAttributeSet attributes)
                throws PrintException {
    synchronized (lock) {
        if (printer != null) {
            throw new PrintException("Printer is busy"); //$NON-NLS-1$
        } else {
            final DocFlavor flavor = doc.getDocFlavor();

            if ((flavor == null) || !service.isDocFlavorSupported(flavor)) {
                throw new PrintException("Doc flavor is not supported"); //$NON-NLS-1$
            }

            printer = new Printer(doc, attributes);
            printer.print();
        }
    }
}
 
Example 7
Project: freeVM   File: AttributeSetUtilitiesTest.java   View source code 6 votes vote down vote up
public final void testVerifyAttributeCategory3() {

        //fails in "some" invironment
        //see AttributeSetUtilities, line 337-339

        try {
            AttributeSetUtilities.
                verifyAttributeCategory(SimpleDoc.class, Doc.class);
            fail("method doesn't throw ClassCastException if object " +
                    "is a Class that implements interfaceName but " +
                        "interfaceName is not a class that implements " +
                            "interface Attribute");
        } catch (ClassCastException e) {
            //System.out.println("testVerifyAttributeCategory3 - " + e.toString());
        }

    }
 
Example 8
Project: openjdk-jdk10   File: DummyPrintTest.java   View source code 5 votes vote down vote up
@Override
public void print(Doc doc,
                  PrintRequestAttributeSet printRequestAttributeSet)
      throws PrintException {
    System.out.println("job name: " + printRequestAttributeSet.get(JobName.class));
    System.out.println("copies: " + printRequestAttributeSet.get(Copies.class));
    if(printRequestAttributeSet.get(JobName.class) == null ||
        printRequestAttributeSet.get(Copies.class) == null) {
        throw new RuntimeException("Copies and JobName is not passed correctly");
    }
}
 
Example 9
Project: openjdk9   File: DummyPrintTest.java   View source code 5 votes vote down vote up
@Override
public void print(Doc doc,
                  PrintRequestAttributeSet printRequestAttributeSet)
      throws PrintException {
    System.out.println("job name: " + printRequestAttributeSet.get(JobName.class));
    System.out.println("copies: " + printRequestAttributeSet.get(Copies.class));
    if(printRequestAttributeSet.get(JobName.class) == null ||
        printRequestAttributeSet.get(Copies.class) == null) {
        throw new RuntimeException("Copies and JobName is not passed correctly");
    }
}
 
Example 10
Project: MedicalRS   File: PrintBillFile.java   View source code 5 votes vote down vote up
/**
   *
   * @param path
   * @throws PrintException
   * @throws IOException
   */
  public void print(String path) throws PrintException, IOException {
  String defaultPrinter =lookupDefaultPrintService().getName();
          showMessageDialog(null,"Default printer: " + defaultPrinter);

  PrintService service = lookupDefaultPrintService();
  DocFlavor flavor;
      PrintJobWatcher pjw;
      try (FileInputStream in = new FileInputStream(new File(path))) {
          PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
          pras.add(new Copies(1));
          flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
          Doc doc = new SimpleDoc(in, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
          DocPrintJob job = service.createPrintJob();
          pjw = new PrintJobWatcher(job);
          job.print(doc, pras);
          pjw.waitForDone();
      }

  // send FF to eject the page
  InputStream ff = new ByteArrayInputStream("\f".getBytes());
  Doc docff = new SimpleDoc(ff, flavor, null);
  DocPrintJob jobff = service.createPrintJob();
  pjw = new PrintJobWatcher(jobff);
  jobff.print(docff, null);
  pjw.waitForDone();
}
 
Example 11
Project: accounting_Soft   File: Printer.java   View source code 5 votes vote down vote up
/**
 *
 * @param g Graphic class
 * @param pf page format
 * @param page page count
 * @return 1
 * @throws PrinterException
 *
 * This methos print to pdf
 */
@Override
public int print(Graphics g, PageFormat pf, int page) throws
        PrinterException {

    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
    PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
    patts.add(Sides.DUPLEX);
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
    if (ps.length == 0) {
        //
    }
    //System.out.println("Available printers: " + Arrays.asList(ps));
    PrintService myService = null;
    for (PrintService printService : ps) {
        if (printService.getName().equals("Your printer name")) {
            myService = printService;
            break;
        }
    }
    if (myService == null) {
        //
    }
    try (FileInputStream fis = new FileInputStream(file)) {
        Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
        DocPrintJob printJob = myService.createPrintJob();
        printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
    } catch (Exception e) {
        e.printStackTrace();
        throw new PrinterException("File Not Found!");
    }
    return 1;
}
 
Example 12
Project: code-similarity   File: PrintPostScript.java   View source code 5 votes vote down vote up
public void print() throws IOException, PrintException {
    
    DocFlavor inputFlavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
    
    // Lookup a print factory to convert from desired input to output.
    StreamPrintServiceFactory[] psfactories =
        StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
            inputFlavor, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
    if (psfactories.length == 0) {
        System.err.println("Ack! No StreamPrintFactory found for this job!");
    }
    StreamPrintService printService = 
        psfactories[0].getPrintService(new FileOutputStream("demo.ps"));
    PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
    attrs.add(OrientationRequested.LANDSCAPE);
    attrs.add(MediaSizeName.NA_LETTER);
    attrs.add(new Copies(1));
    attrs.add(new JobName(INPUT_FILE_NAME, null));

    InputStream is = getClass().getResourceAsStream(INPUT_FILE_NAME);
    if (is == null) {
        throw new NullPointerException(
            "Input Stream is null: file not found?");
    }
    Doc doc = new SimpleDoc(is, inputFlavor, null);
    
    DocPrintJob printJob = printService.createPrintJob();
    printJob.print(doc, attrs);
}
 
Example 13
Project: code-similarity   File: PrintServiceDemo.java   View source code 5 votes vote down vote up
/** Print a file by name 
 * @throws IOException
 * @throws PrintException 
 */
public void print(String fileName) throws IOException, PrintException {
    System.out.println("PrintServiceDemo.print(): Printing " + fileName);
    DocFlavor flavor = DocFlavor.INPUT_STREAM.TEXT_PLAIN_UTF_8;
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    //aset.add(MediaSize.NA.LETTER);
    aset.add(MediaSizeName.NA_LETTER);
    //aset.add(new JobName(INPUT_FILE_NAME, null));
    PrintService[] pservices = 
        PrintServiceLookup.lookupPrintServices(flavor, aset);
    int i;
    switch(pservices.length) {
    case 0:
        System.err.println(0);
        JOptionPane.showMessageDialog(PrintServiceDemo.this,
            "Error: No PrintService Found", "Error", 
            JOptionPane.ERROR_MESSAGE);
        return;
    case 1:
        i = 0;    // Only one printer, use it.
        break;
    default:
        i = JOptionPane.showOptionDialog(this, 
            "Pick a printer", "Choice", 
            JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE, 
            null, pservices, pservices[0]);
        break;
    }
    DocPrintJob pj = pservices[i].createPrintJob();
    InputStream is = getClass().getResourceAsStream(INPUT_FILE_NAME);
    if (is == null) {
        throw new NullPointerException("Input Stream is null: file not found?");
    }
    Doc doc = new SimpleDoc(is, flavor, null);
    
    pj.print(doc, aset);
}
 
Example 14
Project: Camel   File: PrinterOperations.java   View source code 5 votes vote down vote up
public void print(Doc doc, int copies, boolean sendToPrinter, String mimeType, String jobName) throws PrintException {
    LOG.trace("Print Service: " + this.printService.getName());
    LOG.trace("About to print " + copies + " copy(s)");
    
    for (int i = 0; i < copies; i++) {
        if (!sendToPrinter) {
            LOG.debug("Print flag is set to false. This job will not be printed until this setting remains in effect."
                    + " Please set the flag to true or remove the setting.");

            File file;
            if (mimeType.equalsIgnoreCase("GIF") || mimeType.equalsIgnoreCase("RENDERABLE_IMAGE")) {
                file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".gif");
            } else if (mimeType.equalsIgnoreCase("JPEG")) {
                file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".jpeg");
            } else if (mimeType.equalsIgnoreCase("PDF")) {
                file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".pdf");
            } else {
                file = new File("./target/TestPrintJobNo" + i + "_" + UUID.randomUUID() + ".txt");
            }

            LOG.debug("Writing print job to file: " + file.getAbsolutePath());
            try {
                InputStream in = doc.getStreamForBytes();
                FileOutputStream fos = new FileOutputStream(file);
                IOHelper.copyAndCloseInput(in, fos);
                IOHelper.close(fos);
            } catch (Exception e) {
                throw new PrintException("Error writing Document to the target file " + file.getAbsolutePath());
            }    
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Issuing Job {} to Printer: {}", i, this.printService.getName());
            }
            print(doc, jobName);
        }
    }
}
 
Example 15
Project: Camel   File: PrinterOperations.java   View source code 5 votes vote down vote up
public void print(Doc doc, String jobName) throws PrintException {
    // we need create a new job for each print 
    DocPrintJob job = getPrintService().createPrintJob();
    PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet(printRequestAttributeSet);
    attrs.add(new JobName(jobName, Locale.getDefault()));
    job.print(doc, attrs);
}
 
Example 16
Project: Camel   File: PrinterPrintTest.java   View source code 5 votes vote down vote up
@Test
public void printerNameTest() throws Exception {
    if (isAwtHeadless()) {
        return;
    }
    // setup javax.print 
    PrintService ps1 = mock(PrintService.class);
    when(ps1.getName()).thenReturn("MyPrinter\\\\remote\\printer1");
    when(ps1.isDocFlavorSupported(any(DocFlavor.class))).thenReturn(Boolean.TRUE);
    boolean res1 = PrintServiceLookup.registerService(ps1);
    assertTrue("The Remote PrintService #1 should be registered.", res1);
    DocPrintJob job1 = mock(DocPrintJob.class);
    when(ps1.createPrintJob()).thenReturn(job1);

    context.addRoutes(new RouteBuilder() {

        public void configure() {
            from("direct:start1").to("lpr://remote/printer1?sendToPrinter=true");
        }
    });
    context.start();

    template.sendBody("direct:start1", "Hello Printer 1");

    context.stop();

    verify(job1, times(1)).print(any(Doc.class), any(PrintRequestAttributeSet.class));
}
 
Example 17
Project: cn1   File: WinPrintJob.java   View source code 5 votes vote down vote up
private void printPrintable(final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final AttributeSet docAttrs = doc.getAttributes();
    final Printable printable = castDoc(doc, Printable.class);
    final PageFormat format = getPageFormat(docAttrs, attributes);
    final PageRanges ranges = getAttribute(PageRanges.class, docAttrs,
                    attributes);
    int res = Printable.PAGE_EXISTS;

    try {
        startJob(pdc, getDocName(printable, docAttrs, attributes),
                        getDestinationPath(attributes));

        for (int i = 0; res == Printable.PAGE_EXISTS; i++) {
            if ((ranges != null) && !ranges.contains(i)) {
                continue;
            }

            res = printPrintable(printable, pdc, format, i);
        }

        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 18
Project: cn1   File: WinPrintJob.java   View source code 5 votes vote down vote up
private void printImage(final Image img, final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final PageFormat format = getPageFormat(attributes);
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final double xRes = WinPrinterFactory.getPixelsPerInchX(pdc) / 72;
    final double yRes = WinPrinterFactory.getPixelsPerInchY(pdc) / 72;
    final Graphics2D g2d = new WinGDIPGraphics2D(pdc, (char) 2,
                    (int) (format.getWidth() * xRes), (int) (format
                                    .getHeight() * yRes));

    try {
        startJob(pdc, getDocName(img, attributes),
                        getDestinationPath(attributes));
        WinPrinterFactory.startPage(pdc);
        g2d.drawImage(img, (int) (format.getImageableX() * xRes),
                        (int) (format.getImageableY() * yRes),
                        (int) (format.getImageableWidth() * xRes),
                        (int) (format.getImageableHeight() * yRes),
                        Color.WHITE, null);
        WinPrinterFactory.endPage(pdc);
        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 19
Project: cn1   File: WinPrintJob.java   View source code 5 votes vote down vote up
private <T> T castDoc(final Doc doc, final Class<T> c)
                throws PrintException {
    try {
        return c.cast(doc.getPrintData());
    } catch (final IOException ex) {
        throw new PrintException(ex);
    }
}
 
Example 20
Project: cn1   File: DefaultPrintJob.java   View source code 5 votes vote down vote up
/**
 * job - parent DefaultPrintJob doc - doc to print attributeset -
 * attributes set spsDocPrintJob - stream print service's print job
 */
PrintJobThread(DefaultPrintJob job, Doc doc,
        PrintRequestAttributeSet attributeset, StreamPrintService sps) {
    this.printJob = job;
    this.printDoc = doc;
    this.printAttributeSet = attributeset;
    this.streamservice = sps;
    this.exception = null;
    this.exceptionisnotnull = false;
}
 
Example 21
Project: SyncRunner-Pub   File: PlainJavaPrint.java   View source code 5 votes vote down vote up
public static void main(String[] args) throws PrintException, IOException {
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
    PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
    //patts.add(Sides.DUPLEX);
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
    if (ps.length == 0) {
        throw new IllegalStateException("No Printer found");
    }
    System.out.println("Available printers: " + Arrays.asList(ps));

    PrintService myService = null;
    for (PrintService printService : ps) {
        if (printService.getName().equals("UPS Thermal 2844")) {
            myService = printService;
            break;
        }
    }

    if (myService == null) {
        throw new IllegalStateException("Printer not found");
    }

    FileInputStream fis = new FileInputStream("C:\\Users\\B2E_2\\workspace\\QuickInventory\\barcodes.pdf");
    Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    DocPrintJob printJob = myService.createPrintJob();
    printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
    fis.close();        
}
 
Example 22
Project: freeVM   File: DefaultPrintJob.java   View source code 5 votes vote down vote up
/**
 * job - parent DefaultPrintJob doc - doc to print attributeset -
 * attributes set spsDocPrintJob - stream print service's print job
 */
PrintJobThread(DefaultPrintJob job, Doc doc,
        PrintRequestAttributeSet attributeset, StreamPrintService sps) {
    this.printJob = job;
    this.printDoc = doc;
    this.printAttributeSet = attributeset;
    this.streamservice = sps;
    this.exception = null;
    this.exceptionisnotnull = false;
}
 
Example 23
Project: freeVM   File: WinPrintJob.java   View source code 5 votes vote down vote up
private void printPrintable(final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final AttributeSet docAttrs = doc.getAttributes();
    final Printable printable = castDoc(doc, Printable.class);
    final PageFormat format = getPageFormat(docAttrs, attributes);
    final PageRanges ranges = getAttribute(PageRanges.class, docAttrs,
                    attributes);
    int res = Printable.PAGE_EXISTS;

    try {
        startJob(pdc, getDocName(printable, docAttrs, attributes),
                        getDestinationPath(attributes));

        for (int i = 0; res == Printable.PAGE_EXISTS; i++) {
            if ((ranges != null) && !ranges.contains(i)) {
                continue;
            }

            res = printPrintable(printable, pdc, format, i);
        }

        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 24
Project: freeVM   File: WinPrintJob.java   View source code 5 votes vote down vote up
private void printImage(final Image img, final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final PageFormat format = getPageFormat(attributes);
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final double xRes = WinPrinterFactory.getPixelsPerInchX(pdc) / 72;
    final double yRes = WinPrinterFactory.getPixelsPerInchY(pdc) / 72;
    final Graphics2D g2d = new WinGDIPGraphics2D(pdc, (char) 2,
                    (int) (format.getWidth() * xRes), (int) (format
                                    .getHeight() * yRes));

    try {
        startJob(pdc, getDocName(img, attributes),
                        getDestinationPath(attributes));
        WinPrinterFactory.startPage(pdc);
        g2d.drawImage(img, (int) (format.getImageableX() * xRes),
                        (int) (format.getImageableY() * yRes),
                        (int) (format.getImageableWidth() * xRes),
                        (int) (format.getImageableHeight() * yRes),
                        Color.WHITE, null);
        WinPrinterFactory.endPage(pdc);
        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 25
Project: freeVM   File: WinPrintJob.java   View source code 5 votes vote down vote up
private <T> T castDoc(final Doc doc, final Class<T> c)
                throws PrintException {
    try {
        return c.cast(doc.getPrintData());
    } catch (final IOException ex) {
        throw new PrintException(ex);
    }
}
 
Example 26
Project: freeVM   File: DefaultPrintJob.java   View source code 5 votes vote down vote up
/**
 * job - parent DefaultPrintJob doc - doc to print attributeset -
 * attributes set spsDocPrintJob - stream print service's print job
 */
PrintJobThread(DefaultPrintJob job, Doc doc,
        PrintRequestAttributeSet attributeset, StreamPrintService sps) {
    this.printJob = job;
    this.printDoc = doc;
    this.printAttributeSet = attributeset;
    this.streamservice = sps;
    this.exception = null;
    this.exceptionisnotnull = false;
}
 
Example 27
Project: fop   File: ExampleFO2JPSPrint.java   View source code 5 votes vote down vote up
/**
 * Prints an FO file using JPS.
 * @param fo the FO file
 * @throws IOException In case of an I/O problem
 * @throws FOPException In case of a FOP problem
 * @throws TransformerException In case of a problem during XSLT processing
 * @throws PrintException If an error occurs while printing
 */
public void printFO(File fo)
        throws IOException, FOPException, TransformerException, PrintException {

    //Set up DocPrintJob instance
    DocPrintJob printJob = createDocPrintJob();

    //Set up a custom user agent so we can supply our own renderer instance
    FOUserAgent userAgent = fopFactory.newFOUserAgent();

    PageableRenderer renderer = new PageableRenderer(userAgent);
    userAgent.setRendererOverride(renderer);

    // Construct FOP with desired output format
    Fop fop = fopFactory.newFop(userAgent);

    // Setup JAXP using identity transformer
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(); // identity transformer

    // Setup input stream
    Source src = new StreamSource(fo);

    // Resulting SAX events (the generated FO) must be piped through to FOP
    Result res = new SAXResult(fop.getDefaultHandler());

    // Start XSLT transformation and FOP processing
    transformer.transform(src, res);

    Doc doc = new SimpleDoc(renderer, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
    printJob.print(doc, null);
}
 
Example 28
Project: openbravo-pos   File: DevicePrinterPrinter.java   View source code 4 votes vote down vote up
/**
 * Method that is responsible for ending and printing a ticket<br>
 * It manages to get a printerJob, set the name of the job, get a Book object<br>
 * and print the receipt
 */
@Override
public void endReceipt() {

    try {

        PrintService ps;

        if (printservice == null) {
            String[] printers = ReportUtils.getPrintNames();
            if (printers.length == 0) {
                logger.warning(AppLocal.getIntString("message.noprinters"));
                ps = null;
            } else {
                SelectPrinter selectprinter = SelectPrinter.getSelectPrinter(parent, printers);
                selectprinter.setVisible(true);
                if (selectprinter.isOK()) {
                    ps = ReportUtils.getPrintService(selectprinter.getPrintService());
                } else {
                    ps = null;
                }
            }
        } else {
            ps = printservice;
        }

        if (ps != null)  {

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(OrientationRequested.PORTRAIT);
            aset.add(new JobName(AppLocal.APP_NAME + " - Document", null));
            aset.add(media);

            DocPrintJob printjob = ps.createPrintJob();
            Doc doc = new SimpleDoc(new PrintableBasicTicket(m_ticketcurrent, imageable_x, imageable_y, imageable_width, imageable_height), DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

            printjob.print(doc, aset);
        }

    } catch (PrintException ex) {
        logger.log(Level.WARNING, AppLocal.getIntString("message.printererror"), ex);
        JMessageDialog.showMessage(parent, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.printererror"), ex));
    }

    //ticket is not needed any more
    m_ticketcurrent = null;
}
 
Example 29
Project: Camel   File: PrinterOperations.java   View source code 4 votes vote down vote up
public Doc getDoc() {
    return doc;
}
 
Example 30
Project: Camel   File: PrinterOperations.java   View source code 4 votes vote down vote up
public void setDoc(Doc doc) {
    this.doc = doc;
}
 
Example 31
Project: Camel   File: PrinterPrintTest.java   View source code 4 votes vote down vote up
@Test
public void moreThanOneLprEndpoint() throws Exception {

    if (isAwtHeadless()) {
        return;
    }

    int numberOfPrintservicesBefore = PrintServiceLookup.lookupPrintServices(null, null).length;

    // setup javax.print 
    PrintService ps1 = mock(PrintService.class);
    when(ps1.getName()).thenReturn("printer1");
    when(ps1.isDocFlavorSupported(any(DocFlavor.class))).thenReturn(Boolean.TRUE);
    PrintService ps2 = mock(PrintService.class);
    when(ps2.getName()).thenReturn("printer2");
    boolean res1 = PrintServiceLookup.registerService(ps1);
    assertTrue("PrintService #1 should be registered.", res1);
    boolean res2 = PrintServiceLookup.registerService(ps2);
    assertTrue("PrintService #2 should be registered.", res2);
    PrintService[] pss = PrintServiceLookup.lookupPrintServices(null, null);
    assertEquals("lookup should report two PrintServices.", numberOfPrintservicesBefore + 2, pss.length);

    DocPrintJob job1 = mock(DocPrintJob.class);
    when(ps1.createPrintJob()).thenReturn(job1);

    context.addRoutes(new RouteBuilder() {

        public void configure() {
            from("direct:start1").to("lpr://localhost/printer1?sendToPrinter=true");
            from("direct:start2").to("lpr://localhost/printer2?sendToPrinter=false");
        }
    });
    context.start();

    // Are there two different PrintConfigurations?
    Map<String, Endpoint> epm = context().getEndpointMap();
    assertEquals("Four endpoints", 4, epm.size());
    Endpoint lp1 = null;
    Endpoint lp2 = null;
    for (Map.Entry<String, Endpoint> ep : epm.entrySet()) {
        if (ep.getKey().contains("printer1")) {
            lp1 = ep.getValue();
        }
        if (ep.getKey().contains("printer2")) {
            lp2 = ep.getValue();
        }
    }
    assertNotNull(lp1);
    assertNotNull(lp2);
    assertEquals("printer1", ((PrinterEndpoint) lp1).getConfig().getPrintername());
    assertEquals("printer2", ((PrinterEndpoint) lp2).getConfig().getPrintername());

    template.sendBody("direct:start1", "Hello Printer 1");

    context.stop();

    verify(job1, times(1)).print(any(Doc.class), any(PrintRequestAttributeSet.class));
}
 
Example 32
Project: opensim-gui   File: ChartPanel.java   View source code 4 votes vote down vote up
private void createChartPrintPostScriptJob() {
// Use the pre-defined flavor for a Printable from an InputStream 
	DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;

		// Specify the type of the output stream 
	String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();

	// Locate factory which can export a GIF image stream as Postscript 
	StreamPrintServiceFactory[] factories =
	StreamPrintServiceFactory.lookupStreamPrintServiceFactories(
				flavor, psMimeType);
	if (factories.length == 0) {
		System.err.println("No suitable factories");
		System.exit(0); // FIXME too
	}
               // Obtain file name from user
               JFileChooser fileChooser = new JFileChooser();
               ExtensionFileFilter filter = new ExtensionFileFilter(
                       localizationResources.getString("PostScript_Files"), ".eps");
               fileChooser.addChoosableFileFilter(filter);
               String filename="";
               int option = fileChooser.showSaveDialog(this);
               if (option == JFileChooser.APPROVE_OPTION) {
                  filename = fileChooser.getSelectedFile().getPath();
                  if (isEnforceFileExtensions()) {
                     if (!filename.endsWith(".eps")) {
                        filename = filename + ".eps";
                     }
                  } else
                     return;
               }

	try {
		// Create a file for the exported postscript
		FileOutputStream fos = new FileOutputStream(filename);

		// Create a Stream printer for Postscript 
		StreamPrintService sps = factories[0].getPrintService(fos);

		// Create and call a Print Job 
		DocPrintJob pj = sps.createPrintJob();
		PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();

		Doc doc = new SimpleDoc(this, flavor, null);

		pj.print(doc, aset);
		fos.close();

	} catch (PrintException pe) { 
		System.err.println(pe);
	} catch (IOException ie) { 
		System.err.println(ie);
	}

  }
 
Example 33
Project: cn1   File: WinPrintJob.java   View source code 4 votes vote down vote up
Printer(final Doc doc, final PrintRequestAttributeSet attributes) {
    super(WinPrintService.DEFAULT_JOB_NAME.getValue());
    this.doc = doc;
    this.attributes = attributes;
}
 
Example 34
Project: cn1   File: WinPrintJob.java   View source code 4 votes vote down vote up
private void printPageable(final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final Pageable pageable = castDoc(doc, Pageable.class);
    final PageFormat defaultFormat = getPageFormat(doc.getAttributes(),
                    attributes);
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final AttributeSet docAttrs = doc.getAttributes();
    int pages = pageable.getNumberOfPages();
    final PageRanges ranges = getAttribute(PageRanges.class, docAttrs,
                    attributes);

    if (pages == Pageable.UNKNOWN_NUMBER_OF_PAGES) {
        pages = Integer.MAX_VALUE;
    }

    try {
        startJob(pdc, getDocName(pageable, docAttrs, attributes),
                        getDestinationPath(attributes));

        for (int i = 0; i < pages; i++) {
            if ((ranges != null) && !ranges.contains(i)) {
                continue;
            }

            final Printable printable = pageable.getPrintable(i);
            final PageFormat format = null;

            if (printable == null) {
                throw new PrintException("No such page: " + i); //$NON-NLS-1$
            }

            if (printPrintable(printable, pdc, format != null ? format
                            : defaultFormat, i) == Printable.NO_SUCH_PAGE) {
                break;
            }
        }

        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 35
Project: nordpos   File: DevicePrinterPrinter.java   View source code 4 votes vote down vote up
/**
 * Method that is responsible for ending and printing a ticket<br>
 * It manages to get a printerJob, set the name of the job, get a Book object<br>
 * and print the receipt
 */
@Override
public void endReceipt() {

    try {

        PrintService ps;

        if (printservice == null) {
            String[] printers = ReportUtils.getPrintNames();
            if (printers.length == 0) {
                logger.warning(AppLocal.getIntString("message.noprinters"));
                ps = null;
            } else {
                SelectPrinter selectprinter = SelectPrinter.getSelectPrinter(parent, printers);
                selectprinter.setVisible(true);
                if (selectprinter.isOK()) {
                    ps = ReportUtils.getPrintService(selectprinter.getPrintService());
                } else {
                    ps = null;
                }
            }
        } else {
            ps = printservice;
        }

        if (ps != null)  {

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(OrientationRequested.PORTRAIT);
            aset.add(new JobName(AppLocal.APP_NAME + " - Document", null));
            aset.add(media);

            DocPrintJob printjob = ps.createPrintJob();
            Doc doc = new SimpleDoc(new PrintableBasicTicket(m_ticketcurrent, imageable_x, imageable_y, imageable_width, imageable_height), DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

            printjob.print(doc, aset);
        }

    } catch (PrintException ex) {
        logger.log(Level.WARNING, AppLocal.getIntString("message.printererror"), ex);
        JMessageDialog.showMessage(parent, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.printererror"), ex));
    }

    //ticket is not needed any more
    m_ticketcurrent = null;
}
 
Example 36
Project: freeVM   File: WinPrintJob.java   View source code 4 votes vote down vote up
Printer(final Doc doc, final PrintRequestAttributeSet attributes) {
    super(WinPrintService.DEFAULT_JOB_NAME.getValue());
    this.doc = doc;
    this.attributes = attributes;
}
 
Example 37
Project: freeVM   File: WinPrintJob.java   View source code 4 votes vote down vote up
private void printPageable(final Doc doc,
                final PrintRequestAttributeSet attributes)
                throws PrintException {
    final Pageable pageable = castDoc(doc, Pageable.class);
    final PageFormat defaultFormat = getPageFormat(doc.getAttributes(),
                    attributes);
    final long pdc = WinPrinterFactory.getPrinterDC(
                    service.printerName, service.getPrinterProps()
                                    .getStructPtr());
    final AttributeSet docAttrs = doc.getAttributes();
    int pages = pageable.getNumberOfPages();
    final PageRanges ranges = getAttribute(PageRanges.class, docAttrs,
                    attributes);

    if (pages == Pageable.UNKNOWN_NUMBER_OF_PAGES) {
        pages = Integer.MAX_VALUE;
    }

    try {
        startJob(pdc, getDocName(pageable, docAttrs, attributes),
                        getDestinationPath(attributes));

        for (int i = 0; i < pages; i++) {
            if ((ranges != null) && !ranges.contains(i)) {
                continue;
            }

            final Printable printable = pageable.getPrintable(i);
            final PageFormat format = null;

            if (printable == null) {
                throw new PrintException("No such page: " + i); //$NON-NLS-1$
            }

            if (printPrintable(printable, pdc, format != null ? format
                            : defaultFormat, i) == Printable.NO_SUCH_PAGE) {
                break;
            }
        }

        endJob(pdc);
    } finally {
        WinPrinterFactory.releasePrinterDC(pdc);
    }
}
 
Example 38
Project: OpenbravoPOS   File: DevicePrinterPrinter.java   View source code 4 votes vote down vote up
/**
 * Method that is responsible for ending and printing a ticket<br>
 * It manages to get a printerJob, set the name of the job, get a Book object<br>
 * and print the receipt
 */
@Override
public void endReceipt() {

    try {

        PrintService ps;

        if (printservice == null) {
            String[] printers = ReportUtils.getPrintNames();
            if (printers.length == 0) {
                logger.warning(AppLocal.getIntString("message.noprinters"));
                ps = null;
            } else {
                SelectPrinter selectprinter = SelectPrinter.getSelectPrinter(parent, printers);
                selectprinter.setVisible(true);
                if (selectprinter.isOK()) {
                    ps = ReportUtils.getPrintService(selectprinter.getPrintService());
                } else {
                    ps = null;
                }
            }
        } else {
            ps = printservice;
        }

        if (ps != null)  {

            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(OrientationRequested.PORTRAIT);
            aset.add(new JobName(AppLocal.APP_NAME + " - Document", null));
            aset.add(media);

            DocPrintJob printjob = ps.createPrintJob();
            Doc doc = new SimpleDoc(new PrintableBasicTicket(m_ticketcurrent, imageable_x, imageable_y, imageable_width, imageable_height), DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);

            printjob.print(doc, aset);
        }

    } catch (PrintException ex) {
        logger.log(Level.WARNING, AppLocal.getIntString("message.printererror"), ex);
        JMessageDialog.showMessage(parent, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.printererror"), ex));
    }

    //ticket is not needed any more
    m_ticketcurrent = null;
}
 
Example 39
Project: jqm   File: PrintServiceImpl.java   View source code 4 votes vote down vote up
@Override
public void print(String printQueueName, String jobName, Object data, DocFlavor flavor, String endUserName) throws PrintException
{
    // Arguments tests
    if (printQueueName == null || printQueueName.isEmpty())
    {
        throw new IllegalArgumentException("printQueueName must be non null and non empty");
    }
    if (data == null)
    {
        throw new IllegalArgumentException("data must be non null");
    }
    if (flavor == null)
    {
        throw new IllegalArgumentException("flavor must be non null");
    }
    if (jobName == null || jobName.isEmpty())
    {
        throw new IllegalArgumentException("job name must be non null and non empty");
    }
    if (endUserName != null && endUserName.isEmpty())
    {
        throw new IllegalArgumentException("endUserName can be null but cannot be empty is specified");
    }

    // Find the queue
    AttributeSet set = new HashPrintServiceAttributeSet();
    set.add(new PrinterName(printQueueName, null));
    javax.print.PrintService[] services = PrintServiceLookup.lookupPrintServices(null, set);

    if (services.length == 0 || services[0] == null)
    {
        throw new IllegalArgumentException("There is no printer queue defined with name " + printQueueName
                + " supporting document flavour " + flavor.toString());
    }
    javax.print.PrintService queue = services[0];

    // Create job
    DocPrintJob job = queue.createPrintJob();
    PrintRequestAttributeSet jobAttrs = new HashPrintRequestAttributeSet();
    jobAttrs.add(new JobName(jobName, null));
    if (endUserName != null && queue.isAttributeCategorySupported(RequestingUserName.class))
    {
        jobAttrs.add(new RequestingUserName(endUserName, null));
    }

    // Create payload
    Doc doc = new SimpleDoc(data, flavor, null);

    // Do it
    job.print(doc, jobAttrs);
}
 
Example 40
Project: Camel   File: PrinterOperationsInterface.java   View source code 2 votes vote down vote up
/**
 * Prints the document.
 *
 * @param doc document to print
 * @throws PrintException is thrown if printing failed
 */
void print(Doc doc, String jobName) throws PrintException;