I have a situation that need to print order bill in cash counter and packing area(warehouse ).
Technically, how to print javafx.print.PrinterJob by saying printer name.
1) Sample print
public static void PrintSample() {
Label lbl = new Label("This is sample \n\n\n\n\n\nprint");
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null ) {
boolean success = job.printPage(lbl);
if (success) {
job.endJob();
}
}
}
2) Get list of printers
public static void GetListOfPrinters() {
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
System.out.println("Number of print services: " + printServices.length);
for (PrintService printer : printServices) {
System.out.println("Printer: " + printer.getName());
}
}
The answer is too late but any one need the answer for the same question:
you can use this class to print file(not node)....
public static void print(String imageName, PagesManager pagesManager) {
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout
= printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
PrinterAttributes attr = printer.getPrinterAttributes();
PrinterJob job = PrinterJob.createPrinterJob();
if (job.showPrintDialog(pagesManager.getScene().getWindow())) {
String selectedPrinter = job.getPrinter().getName();
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
PrintService pss[] = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.GIF, pras);
if (pss.length == 0) {
throw new RuntimeException("No printer services available.");
}
int i = 0;
for (i = 0; i < pss.length; i++) {
if (pss[i].getName().equals(selectedPrinter)) {
break;
}
}
PrintService ps = pss[i];
System.out.println("Printing to " + ps);
DocPrintJob docPrintJob = ps.createPrintJob();
FileInputStream fin = null;
try {
fin = new FileInputStream(imageName);
} catch (FileNotFoundException ex) {
System.out.println(ex);
}
Doc doc = new SimpleDoc(fin, DocFlavor.INPUT_STREAM.GIF, null);
try {
docPrintJob.print(doc, pras);
} catch (PrintException ex) {
System.out.println(ex);
}
try {
fin.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
The method 'createPrinterJob' with no-args creates a printer job for the default printer. You can use the other version of the method 'createPrinterJob(Printer printer)' to create a printer job for the specified printer.
First get instance of printer like below:
Printer myPrinter;
ObservableSet<Printer> printers = Printer.getAllPrinters();
for(Printer printer : printers){
if(printer.getName().matches("spefic printer name")){
myPrinter = printer;
}
}
Now Create a printer job for 'myPrinter' like this:
PrinterJob job = PrinterJob.createPrinterJob(myPrinter);
PrinterJob job = PrinterJob.createPrinterJob(myPrinter);
this line is not working give error The method createPrinterJob(Printer) is undefined for the type PrinterJob
Related
I am trying to print a label with printer TSC TTP-342E Pro industrial thermal printer. But unable to make a print. I use same program to print in laser printer HP LaserJet M1530 and its work fine. In both case the print is initiated from a pdf. The program is communicating with the printer but it is not printing anything.
I have used pdfbox, should I go with something like bartenter?
In below program, the program will read pdf from a location and communicate with the printer to generate a printout.
Code
public static PrintService choosePrinter(String printerName) {
PrintService[] services = PrinterJob.lookupPrintServices(); // list of printers
PrintService printService = null;
for(PrintService service : services) {
String availablePrinterName = service.getName();
System.out.println(availablePrinterName);
if(service.getName().contains(printerName)) {
printService = service;
break;
}
}
return printService;
}
public static void main(String[] args) {
try {
LOGGER.info("===== PRINT JOB 2 STARTED =======");
Properties prop = getProperty();
String printerName = prop.getProperty("printername");
//String fileLocation = prop.getProperty("filelocation");
String printStatus = prop.getProperty("enableprint");
Double height = Double.valueOf(prop.getProperty("height"));
Double width = Double.valueOf(prop.getProperty("width"));
Boolean enablePrintPageSetup = Boolean.valueOf(prop.getProperty("enablePrintPageSetup"));
PDDocument pdf = PDDocument.load(new File(location));
PrinterJob job = PrinterJob.getPrinterJob();
Paper paper = new Paper();
paper.setSize((width*72), (height*72)); // 1/72 inch
paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
PageFormat pageFormat = new PageFormat();
if(enablePrintPageSetup) {
pageFormat.setPaper(paper);
}
pageFormat.setOrientation(PageFormat.PORTRAIT);
Book book = new Book();
PDFPrintable pdfPrintable = new PDFPrintable(pdf, Scaling.SHRINK_TO_FIT);
book.append(pdfPrintable, pageFormat, pdf.getNumberOfPages());
job.setPageable(book);
PrintService printService = choosePrinter(printerName);
if(printService != null) {
if(Boolean.parseBoolean(printStatus)) {
LOGGER.info("Print enabled ");
job.setPrintService(printService);
job.print();
} else {
LOGGER.info("Print disbaled ");
}
} else {
System.out.println("No PDF printer available.");
LOGGER.info("===== No PDF printer available. =======");
}
System.out.println("===== PRINT JOB 2 STOPPED =======");
LOGGER.info("===== PRINT JOB 2 STOPPED =======");
} catch (Exception e) {
// TODO Auto-generated catch block
LOGGER.error("Error : ", e);
e.printStackTrace();
}
}
private static Properties getProperty() {
Properties prop = new Properties();
try {
File jarPath=new File(App_1.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String propertiesPath=jarPath.getParentFile().getAbsolutePath();
System.out.println(" propertiesPath-"+propertiesPath);
prop.load(new FileInputStream(propertiesPath+"/config.properties"));
location = propertiesPath + "/printpdf.pdf";
} catch (Exception e) {
e.printStackTrace();
LOGGER.error("Error : ", e);
}
return prop;
}
I developed a Java desktop program that uses a thermal printer with the following code:
/**
* printableObject extends Printable
*/
public static boolean print(Object printableObject, String printer_name) throws InterruptedException {
InputStream printerTest = new ByteArrayInputStream("".getBytes());
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(printableObject, DocFlavor.SERVICE_FORMATTED.PRINTABLE, null);
Doc docTest = new SimpleDoc(printerTest, flavor, null);
HashPrintServiceAttributeSet aset = new HashPrintServiceAttributeSet();
PrintRequestAttributeSet rset = new HashPrintRequestAttributeSet();
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
PrinterName printer = new PrinterName(printer_name, null);
rset.add(OrientationRequested.PORTRAIT);
rset.add(MediaSizeName.INVOICE);
aset.add(printer);
services = PrintServiceLookup.lookupPrintServices(null, aset);
if (!priterIsReady(services[0], 5)) {
return false;
}
if (services != null) {
try {
DocPrintJob docPrintJobTest = services[0].createPrintJob();
docPrintJobTest.print(docTest, rset);
if (!priterIsReady(services[0], 5)) {
return false;
}
DocPrintJob job = services[0].createPrintJob();
job.print(myDoc, rset);
Thread.sleep(300);
if (priterIsReady(services[0], 5)) {
DocPrintJob job2 = services[0].createPrintJob();
job2.print(docTest, rset);
return priterIsReady(services[0], 5);
} else {
return false;
}
} catch (ArrayIndexOutOfBoundsException ex) {
ex.printStackTrace();
} catch (PrintException pe) {
pe.printStackTrace();
}
}
return false;
}
public static boolean priterIsReady(PrintService printer, int max) throws InterruptedException {
int count = 0;
while (count < max) {
AttributeSet att = printer.getAttributes();
for (Attribute a : att.toArray()) {
String attributeName;
String attributeValue;
attributeName = a.getName();
attributeValue = att.get(a.getClass()).toString();
if (attributeName.equals("queued-job-count")) {
if (Integer.valueOf(attributeValue) == 0) {
return true;
} else {
System.err.println(">>> queued-job-count: " + Integer.valueOf(attributeValue));
}
}
}
Thread.sleep(600 + 600 / 5 * count);
count = count + 1;
}
return false;
}
The code works perfectly in my IDE or using the jar (java 1.8.0_73). The printing is fast. But using another notebook with similar configuration (i7, 8GB, Windows10) I have problem: the printing takes more than 10 seconds to start. The same JAR and the same printer, but java 1.8.0_101. In this period the document is in the print queue.
I used another notebook (i5, 8GB, Windows10) and I had the same delay.
I changed the above code and I tried to print without check if the printer is ready or print test, but the problem persists.
Has someone gone through this problem?
Is there another way that I can print a Printable Object?
I'm printing a filled form PDF with PDFBox and PrinterJob. I can create and print just fine but with the PrinterJob I cannot seem to follow the progress or even check if it is finished or not.
I have found that I can count the queued printerjobs but without a name/id I cannot link them to the pdf I'm printing.
I would like to know if there is a way to either check the progress or at least know if a specific (named) PrinterJob is finished.
public void print(PDDocument document, String printerName, boolean silentPrint) throws Exception
{
PrintService printService = getPrinter(printerName);
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintService(printService);
PDFPrintable pageable = new PDFPrintable(document,Scaling.ACTUAL_SIZE);
PageFormat format = printJob.defaultPage();
format.setOrientation(PageFormat.PORTRAIT);
printJob.setPrintable(pageable, format);
printJob.print();
}
private static PrintService getPrinter(String printerName) throws Exception
{
PrintService[] services = PrinterJob.lookupPrintServices();
PrintService myPrinter = null;
if(services.length == 0)
throw new Exception("Cannot find printer");
for (int i = 0; i < services.length; i++)
{
String svcName = services[i].toString();
System.out.println("service found: "+svcName);
if (svcName.contains(printerName))
{
myPrinter = services[i];
System.out.println("my printer found: "+svcName);
break;
}
}
return myPrinter;
}
public static int getPrinterJobCount(String printerName) throws Exception
{
PrintService service = getPrinter(printerName);
Attribute[] attrs = service.getAttributes().toArray();
for (int j=0; j<attrs.length; j++) {
// Get the name of the category of which this attribute value is an instance.
String attrName = attrs[j].getName();
// get the attribute value
String attrValue = attrs[j].toString();
if(attrName.equals("queued-job-count"))
return Integer.parseInt(attrValue);
}
return -1;
}
I'm trying to print from differents printer trays using javax.print with no luck, I have a printer HP Officejet Pro X476dw with 2 paper trays numbered 1 and 2.
My code is this:
public class ImprimeSide{
public static void main (String [] args) {
try {
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, null);
//Acquire Printer
PrintService printer = null;
for(PrintService serv: pservices){
if(serv.getName().contains("HP Officejet")){
printer = serv;
}
}
if(printer != null){
//Open File
FileInputStream fis = new FileInputStream("Documento2.pdf");
//Create Doc out of file, autosense filetype
Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
//Create job for printer
DocPrintJob printJob = printer.createPrintJob();
//Create AttributeSet
PrintRequestAttributeSet pset = new HashPrintRequestAttributeSet();
//Add MediaTray to AttributeSet
pset.add(MediaTray.SIDE);
//Print using Doc and Attributes
printJob.print(pdfDoc, pset);
//Close File
fis.close();
}
}catch (Throwable t) {
t.printStackTrace();
}
}
}
Changing the line pset.add(MediaTray.SIDE) for every constant in the class MediaTray (TOP, BOTTOM, MANUAL.. etc) doesn't change anything, it will print taking paper from the default tray.
Any sugestion will be appreciated.
you must declare a MediaTray after mapping all media in a hashmap
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
for (PrintService service : services)
{
System.out.println(service);
// we retrieve all the supported attributes of type Media
// we can receive MediaTray, MediaSizeName, ...
Object o = service.getSupportedAttributeValues(Media.class, flavor, null);
if (o != null && o.getClass().isArray())
{
for (Media media : (Media[]) o)
{
// we collect the MediaTray available
if (media instanceof MediaTray)
{
System.out.println(media.getValue() + " : " + media + " - " + media.getClass().getName());
trayMap.put(media.getValue(), media);
}
}
}
}
MediaTray selectedTray = (MediaTray) trayMap.get(Integer.valueOf(mediaId));
and after you add it to the PrintRequestAttributeSet
PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
attributes.add(selectedTray);
And when you print you use this PrintRequestAttributeSet
DocPrintJob job = services[0].createPrintJob();
job.print(doc, attributes);
Jorge
I'm trying to write a Java program that will run an OpenOffice Macro. I'm getting this error:
java.lang.RuntimeException:
com.sun.star.script.provider.ScriptFrameworkErrorException: Incorrect
format for Script URI: vnd.sun.star.script:Name of macro
I believe it has something to do with the way that I'm calling the macro (String cmd)
I've searched high and low but can't seem to find any information on this. There are a few posts on the OO forums but none of them seemed to help. Here is some of the code:
public static void main(String[] args) throws BootstrapException {
if(args.length == 0)
{
System.out.println("Must enter a filename");
System.exit(1);
}
try
{
String param = args[0];
//String cmd = "Standard.Conversion.ConvertHTMLToWord?langauge=Basic&location=application";
String cmd = "Name.Of.Macro?langauge=Basic&location=Document";
System.out.println("Running macro on " + param);
Macro macObj = new Macro();
macObj.executeMacro(cmd, new Object[]{param}]);
System.out.println("Completed");
}
catch(Exception e)
{
System.out.println(e.toString());
//e.printStackTrace();
}
Macro Class:
class Macro {
private static final String ooExecPath = "C:/Program Files/OpenOffice.org 3/program";
public Object executeMacro(String strMacroName, Object[] aParams) throws BootstrapException
{
try
{
com.sun.star.uno.XComponentContext xContext;
System.out.println("Connecting to OpenOffice");
xContext = BootstrapSocketConnector.bootstrap(ooExecPath);
System.out.println("Connected to a running instance of OpenOffice");
System.out.println("Trying to execute macro...");
com.sun.star.text.XTextDocument mxDoc = openWriter(xContext);
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, mxDoc);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+strMacroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
return xScript.invoke(aParams, aOutParamIndex, aOutParam);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static com.sun.star.text.XTextDocument openWriter(com.sun.star.uno.XComponentContext xContext)
{
com.sun.star.frame.XComponentLoader xCLoader;
com.sun.star.text.XTextDocument xDoc = null;
com.sun.star.lang.XComponent xComp = null;
try {
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF =
xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
xCLoader = (com.sun.star.frame.XComponentLoader)
UnoRuntime.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
com.sun.star.beans.PropertyValue [] szEmptyArgs =
new com.sun.star.beans.PropertyValue [0];
/*
ArrayList<PropertyValue> props = new ArrayList<PropertyValue>();
PropertyValue p = new PropertyValue();
p.Name = "Hidden";
p.Value = new Boolean(true);
props.add(p);
PropertyValue[] properties = new PropertyValue[props.size()];
props.toArray(properties);
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, properties);
*/
String strDoc = "private:factory/swriter";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0, szEmptyArgs);
xDoc = (com.sun.star.text.XTextDocument)
UnoRuntime.queryInterface(com.sun.star.text.XTextDocument.class,
xComp);
} catch(Exception e){
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xDoc;
}
}
I suppose your problem is in the "Name.Of.Macro": it must be: Library.Module.NameOfMacro.
"langauge=Basic" of course sets the language name, and "location=application" means the macro library should be searched in the opened document, and not in global OO libraries.
As far as parameters are involved, I use:
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
XScriptProvider xScriptProvider = xScriptPS.getScriptProvider();
XScript xScript = xScriptProvider.getScript("vnd.sun.star.script:"+macroName);
short[][] aOutParamIndex = new short[1][1];
Object[][] aOutParam = new Object[1][1];
Object[] aParams = new String[2];
aParams[0] = myFirstParameterName;
aParams[1] = mySecondParameterName;
#SuppressWarnings("unused")
Object result = xScript.invoke(aParams, aOutParamIndex, aOutParam);
System.out.println("xScript invoke macro " + macroName);
Hope it can be useful, after such long time... :-(
XScriptProviderSupplier xScriptPS = (XScriptProviderSupplier) UnoRuntime.queryInterface(XScriptProviderSupplier.class, xComponent);
What is xComponent in the above code?
Compare: ?langauge=Basic&location=Document"
to: ?language=Basic&location=Document"
wring is: "langauge" :D, swap "au" to "ua". :)