Printing using tsc ttp-342e pro thermal printer java - java

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;
}

Related

Open office sdk create xls, doc,ppt files in Java

How to create a xls file using open office sdk? Please give Java example source code. Also needed to create word and power point files. I’m not able to get any examples
Below is the code I tried. It tries to open in Open office App, that I don't want. I want to generate the .ods file in the WebSphere App Server under AIX environment, using Java. I'm using it to generate a report and download it to front end (web app).
import ooo.connector.BootstrapSocketConnector;
import com.sun.star.beans.PropertyValue;
import com.sun.star.comp.helper.BootstrapException;
import com.sun.star.container.XIndexAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.sheet.XSpreadsheetDocument;
import com.sun.star.sheet.XSpreadsheets;
import com.sun.star.table.XCell;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
XComponentContext xContext = null;
// get the remote office component context
try {
String folder = "C:\\Program Files (x86)\\OpenOffice 4\\program";
xContext = BootstrapSocketConnector.bootstrap(folder);
} catch (BootstrapException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
XSpreadsheetDocument myDoc = null;
System.out.println("Opening an empty Calc document");
myDoc = openCalc(xContext);
XSpreadsheet xSheet = null;
try {
System.out.println("Getting spreadsheet");
XSpreadsheets xSheets = myDoc.getSheets();
XIndexAccess oIndexSheets = (XIndexAccess) UnoRuntime
.queryInterface(XIndexAccess.class, xSheets);
xSheet = (XSpreadsheet) UnoRuntime.queryInterface(
XSpreadsheet.class, oIndexSheets.getByIndex(0));
} catch (Exception e) {
System.out.println("Couldn't get Sheet " + e);
e.printStackTrace(System.err);
}
System.out.println("Creating the Header") ;
insertIntoCell(1,0,"JAN",xSheet,"");
insertIntoCell(2,0,"FEB",xSheet,"");
insertIntoCell(3,0,"MAR",xSheet,"");
insertIntoCell(4,0,"APR",xSheet,"");
insertIntoCell(5,0,"MAI",xSheet,"");
insertIntoCell(6,0,"JUN",xSheet,"");
insertIntoCell(7,0,"JUL",xSheet,"");
insertIntoCell(8,0,"AUG",xSheet,"");
insertIntoCell(9,0,"SEP",xSheet,"");
insertIntoCell(10,0,"OCT",xSheet,"");
insertIntoCell(11,0,"NOV",xSheet,"");
insertIntoCell(12,0,"DEC",xSheet,"");
insertIntoCell(13,0,"SUM",xSheet,"");
System.out.println("Fill the lines");
insertIntoCell(0,1,"Smith",xSheet,"");
insertIntoCell(1,1,"42",xSheet,"V");
insertIntoCell(2,1,"58.9",xSheet,"V");
insertIntoCell(3,1,"-66.5",xSheet,"V");
insertIntoCell(4,1,"43.4",xSheet,"V");
insertIntoCell(5,1,"44.5",xSheet,"V");
insertIntoCell(6,1,"45.3",xSheet,"V");
insertIntoCell(7,1,"-67.3",xSheet,"V");
insertIntoCell(8,1,"30.5",xSheet,"V");
insertIntoCell(9,1,"23.2",xSheet,"V");
insertIntoCell(10,1,"-97.3",xSheet,"V");
insertIntoCell(11,1,"22.4",xSheet,"V");
insertIntoCell(12,1,"23.5",xSheet,"V");
insertIntoCell(13,1,"=SUM(B2:M2)",xSheet,"");
insertIntoCell(0,2,"Jones",xSheet,"");
insertIntoCell(1,2,"21",xSheet,"V");
insertIntoCell(2,2,"40.9",xSheet,"V");
insertIntoCell(3,2,"-57.5",xSheet,"V");
insertIntoCell(4,2,"-23.4",xSheet,"V");
insertIntoCell(5,2,"34.5",xSheet,"V");
insertIntoCell(6,2,"59.3",xSheet,"V");
insertIntoCell(7,2,"27.3",xSheet,"V");
insertIntoCell(8,2,"-38.5",xSheet,"V");
insertIntoCell(9,2,"43.2",xSheet,"V");
insertIntoCell(10,2,"57.3",xSheet,"V");
insertIntoCell(11,2,"25.4",xSheet,"V");
insertIntoCell(12,2,"28.5",xSheet,"V");
insertIntoCell(13,2,"=SUM(B3:M3)",xSheet,"");
insertIntoCell(0,3,"Brown",xSheet,"");
insertIntoCell(1,3,"31.45",xSheet,"V");
insertIntoCell(2,3,"-20.9",xSheet,"V");
insertIntoCell(3,3,"-117.5",xSheet,"V");
insertIntoCell(4,3,"23.4",xSheet,"V");
insertIntoCell(5,3,"-114.5",xSheet,"V");
insertIntoCell(6,3,"115.3",xSheet,"V");
insertIntoCell(7,3,"-171.3",xSheet,"V");
insertIntoCell(8,3,"89.5",xSheet,"V");
insertIntoCell(9,3,"41.2",xSheet,"V");
insertIntoCell(10,3,"71.3",xSheet,"V");
insertIntoCell(11,3,"25.4",xSheet,"V");
insertIntoCell(12,3,"38.5",xSheet,"V");
insertIntoCell(13,3,"=SUM(A4:L4)",xSheet,"");
}
public static void insertIntoCell(int CellX, int CellY, String theValue,
XSpreadsheet TT1, String flag) {
XCell xCell = null;
try {
xCell = TT1.getCellByPosition(CellX, CellY);
} catch (com.sun.star.lang.IndexOutOfBoundsException ex) {
System.err.println("Could not get Cell");
ex.printStackTrace(System.err);
}
if (flag.equals("V")) {
xCell.setValue((new Float(theValue)).floatValue());
} else {
xCell.setFormula(theValue);
}
}
public static XSpreadsheetDocument openCalc(XComponentContext xContext) {
// define variables
XMultiComponentFactory xMCF = null;
XComponentLoader xCLoader;
XSpreadsheetDocument xSpreadSheetDoc = null;
XComponent xComp = null;
try {
// get the servie manager rom the office
xMCF = xContext.getServiceManager();
// create a new instance of the the desktop
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
// query the desktop object for the XComponentLoader
xCLoader = (XComponentLoader) UnoRuntime.queryInterface(
XComponentLoader.class, oDesktop);
PropertyValue[] szEmptyArgs = new PropertyValue[0];
String strDoc = "private:factory/scalc";
xComp = xCLoader.loadComponentFromURL(strDoc, "_blank", 0,
szEmptyArgs);
xSpreadSheetDoc = (XSpreadsheetDocument) UnoRuntime.queryInterface(
XSpreadsheetDocument.class, xComp);
} catch (Exception e) {
System.err.println(" Exception " + e);
e.printStackTrace(System.err);
}
return xSpreadSheetDoc;
}
}

how to set target printer in PrinterJob in javafx

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

Slow java printing - DocPrintJob

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?

Java, how to find out if printerjob has finished

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;
}

MediaTray doesn't work

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

Categories