@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; }
@Override public void actionPerformed(ActionEvent e) { try { if (selectedDriver == null) return; PrintService ps = (PrintService)printers.getSelectedItem(); PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet(); attr.add(new Copies(1)); attr.add((Media)ps.getDefaultAttributeValue(Media.class)); // set to default paper from printer attr.add(OrientationRequested.LANDSCAPE); SimpleDoc doc = new SimpleDoc(activeLabel, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null); ps.createPrintJob().print(doc, attr); } catch (PrintException ex) { log.log(Level.SEVERE, "\bBarcode print failed: " + ex.getMessage(), ex); } }
public static boolean out(BufferedImage image) { try { DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; PrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet(); requestAttributeSet.add(MediaSizeName.ISO_A4); requestAttributeSet.add(new JobName(LSystem.applicationName + LSystem.getTime(), Locale.ENGLISH)); PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, requestAttributeSet); PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService(); PrintService service = ServiceUI.printDialog(null, 100, 100, services, defaultService, flavor, requestAttributeSet); if (service != null) { DocPrintJob job = service.createPrintJob(); SimpleDoc doc = new SimpleDoc(new BufferedImagePrintable(image), flavor, null); job.print(doc, requestAttributeSet); } } catch (Exception e) { return false; } return true; }
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()); } }
/** * 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); } }
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()); } }
public static void main(String[] args) throws Exception { GraphicsEnvironment.getLocalGraphicsEnvironment(); DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE; String mime = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType(); StreamPrintServiceFactory[] factories = StreamPrintServiceFactory. lookupStreamPrintServiceFactories(flavor, mime); if (factories.length == 0) { System.out.println("No print service found."); return; } FileOutputStream output = new FileOutputStream("out.ps"); StreamPrintService service = factories[0].getPrintService(output); SimpleDoc doc = new SimpleDoc(new PrintSEUmlauts(), DocFlavor.SERVICE_FORMATTED.PRINTABLE, new HashDocAttributeSet()); DocPrintJob job = service.createPrintJob(); job.addPrintJobListener(new PrintJobAdapter() { @Override public void printJobCompleted(PrintJobEvent pje) { testPrintAndExit(); } }); job.print(doc, new HashPrintRequestAttributeSet()); }
/** * * @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(); }
/** * * @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; }
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); }
/** 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); }
public final void testGet1() { aset = new HashAttributeSet(); try { aset.get(SimpleDoc.class); fail("get() doesn't throw ClassCastException when given object" + "is not a Class that implements interface Attribute"); } catch (ClassCastException e) { } }
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(); }
/** * 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); }
final public Boolean showPrintJDialog() { final PrintService objLdefaultPrintService = PrintServiceLookup.lookupDefaultPrintService(); final PrintRequestAttributeSet objLprintRequestAttributeSet = new HashPrintRequestAttributeSet(); if (this.objGprintServiceA.length > 0) { int intLdefaultServiceIndex = 0; if (objLdefaultPrintService != null) { for (intLdefaultServiceIndex = 0; intLdefaultServiceIndex < this.objGprintServiceA.length; intLdefaultServiceIndex++) { if (this.objGprintServiceA[intLdefaultServiceIndex].equals(objLdefaultPrintService)) { break; } } } if (intLdefaultServiceIndex == this.objGprintServiceA.length) { intLdefaultServiceIndex = 0; } ServiceUI.printDialog( null, 50, 50, this.objGprintServiceA, this.objGprintServiceA[intLdefaultServiceIndex], null, objLprintRequestAttributeSet); final PrintJDialog objLprintJDialog = new PrintJDialog(this.objGcontrolJFrame, this.objGprintServiceA, intLdefaultServiceIndex); objLprintJDialog.setVisible(); final PrintService objLprintService = objLprintJDialog.getPrintService(); objLprintJDialog.dispose(); if (objLprintService != null) { final DocPrintJob objLdocPrintJob = objLprintService.createPrintJob(); final SimpleDoc objLsimpleDoc = new SimpleDoc(this, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null); try { objLdocPrintJob.print(objLsimpleDoc, objLprintRequestAttributeSet); return new Boolean(true); } catch (final Throwable objPthrowable) {} } else { return null; } } else { new PopUpJDialog( this.objGcontrolJFrame, Constants.bytS_UNCLASS_NO_VALUE, Constants.intS_FILE_ICON_ALERT, this.objGcontrolJFrame.getLanguageString(Language.intS_TITLE_PRINT_PATTERN), Tools.getLocaleString("dialog.noprintermsg"), null, true); } return new Boolean(false); }
/** * 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; }
/************************************************************************ * 打印 */ public void print() throws Exception { try { //搜寻打印机 PrintService printer = this.lookupPrinter(); if (printer == null) { throw new NullPointerException("printer == null. 没有找到默认打印机!!!"); } //日志输出打印机的各项属性 AttributeSet attrs = printer.getAttributes(); logger.info("****************************************************"); for (Attribute attr : attrs.toArray()) { String attributeName = attr.getName(); String attributeValue = attrs.get(attr.getClass()).toString(); logger.info("*"+attributeName + " : " + attributeValue); } logger.info("****************************************************"); //创建打印数据 // DocAttributeSet docAttr = new HashDocAttributeSet();//设置文档属性 // Doc myDoc = new SimpleDoc(psStream, psInFormat, docAttr); DocAttributeSet das = new HashDocAttributeSet(); Object printData = this.prepareData(); logger.info("#print. 开始打印, 数据资源-printData: "+printData); if (printData == null) { throw new NullPointerException("printData == null. 准备数据失败!!!"); } doc = new SimpleDoc(printData, printFormat, das); //创建文档打印作业 long start = System.currentTimeMillis(); logger.info("#print. 开始打印, 请稍候..."); DocPrintJob job = printer.createPrintJob(); job.print(doc, attributeSet); logger.info("#print. 完成打印, 共耗时: "+(System.currentTimeMillis() - start)+" 毫秒."); } catch (Exception e) { // TODO: handle exception logger.error("#print. print error.", e); throw new Exception("打印过程中出现异常情况,打印没有完成,请检查!!!", e); } }
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); } }
@Override public void setPageable(final Pageable document) throws NullPointerException { doc = new SimpleDoc(document, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null); }
@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); }