Slow java printing - DocPrintJob - java

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?

Related

JSchException Cannot find message

I want to know some of the reasons that can cause below exception. I am unable to find this message Cannot find message in jsch-0.1.54.jar. There exists some straight forward messages like file not found and others that make sense. But I need more information about this one so that I can reach to the root cause.
SftpException while running get ---> 2: Cannot find message [/destination/file.txt]
at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2289)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1741)
at com.jcraft.jsch.ChannelSftp._stat(ChannelSftp.java:1758)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:786)
at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:750)
at com.iyi.ftp.SFTP.get(SFTP.java:99)
Here is my calling method.
public boolean get(final String remoteFile, final String localFile) throws JSchException {
Vector connection = null;
Session session = null;
ChannelSftp c = null;
boolean status = false;
try {
connection = this.connect();
session = connection.get(0);
c = connection.get(1);
c.get(remoteFile, localFile);
status = true;
}
catch (JSchException e) {
SFTP.LGR.warn((Object)("JSchException in SFTP::get() ---> " + FTPFactory.getStackTrace((Throwable)e)));
throw e;
}
catch (SftpException e2) {
SFTP.LGR.warn((Object)("SftpException while running get ---> " + FTPFactory.getStackTrace((Throwable)e2)));
throw new JSchException(e2.getMessage());
}
catch (CredentialDecryptionException e3) {
SFTP.LGR.error((Object)"##CredentialDecryptionException##", (Throwable)e3);
throw new JSchException(e3.getMessage(), (Throwable)e3);
}
finally {
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
}
if (c != null) {
c.quit();
}
if (session != null) {
session.disconnect();
}
return status;
}
These methods are fetched from jsch-0.1.54.jar which is an open source utility.
public void get(String src, String dst, final SftpProgressMonitor monitor, final int mode) throws SftpException {
boolean _dstExist = false;
String _dst = null;
try {
((MyPipedInputStream)this.io_in).updateReadSide();
src = this.remoteAbsolutePath(src);
dst = this.localAbsolutePath(dst);
final Vector v = this.glob_remote(src);
final int vsize = v.size();
if (vsize == 0) {
throw new SftpException(2, "No such file");
}
final File dstFile = new File(dst);
final boolean isDstDir = dstFile.isDirectory();
StringBuffer dstsb = null;
if (isDstDir) {
if (!dst.endsWith(ChannelSftp.file_separator)) {
dst += ChannelSftp.file_separator;
}
dstsb = new StringBuffer(dst);
}
else if (vsize > 1) {
throw new SftpException(4, "Copying multiple files, but destination is missing or a file.");
}
for (int j = 0; j < vsize; ++j) {
final String _src = v.elementAt(j);
final SftpATTRS attr = this._stat(_src);
if (attr.isDir()) {
throw new SftpException(4, "not supported to get directory " + _src);
}
_dst = null;
if (isDstDir) {
final int i = _src.lastIndexOf(47);
if (i == -1) {
dstsb.append(_src);
}
else {
dstsb.append(_src.substring(i + 1));
}
_dst = dstsb.toString();
if (_dst.indexOf("..") != -1) {
final String dstc = new File(dst).getCanonicalPath();
final String _dstc = new File(_dst).getCanonicalPath();
if (_dstc.length() <= dstc.length() || !_dstc.substring(0, dstc.length() + 1).equals(dstc + ChannelSftp.file_separator)) {
throw new SftpException(4, "writing to an unexpected file " + _src);
}
}
dstsb.delete(dst.length(), _dst.length());
}
else {
_dst = dst;
}
final File _dstFile = new File(_dst);
if (mode == 1) {
final long size_of_src = attr.getSize();
final long size_of_dst = _dstFile.length();
if (size_of_dst > size_of_src) {
throw new SftpException(4, "failed to resume for " + _dst);
}
if (size_of_dst == size_of_src) {
return;
}
}
if (monitor != null) {
monitor.init(1, _src, _dst, attr.getSize());
if (mode == 1) {
monitor.count(_dstFile.length());
}
}
FileOutputStream fos = null;
_dstExist = _dstFile.exists();
try {
if (mode == 0) {
fos = new FileOutputStream(_dst);
}
else {
fos = new FileOutputStream(_dst, true);
}
this._get(_src, fos, monitor, mode, new File(_dst).length());
}
finally {
if (fos != null) {
fos.close();
}
}
}
}
catch (Exception e) {
if (!_dstExist && _dst != null) {
final File _dstFile2 = new File(_dst);
if (_dstFile2.exists() && _dstFile2.length() == 0L) {
_dstFile2.delete();
}
}
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
private SftpATTRS _stat(final byte[] path) throws SftpException {
try {
this.sendSTAT(path);
Header header = new Header();
header = this.header(this.buf, header);
final int length = header.length;
final int type = header.type;
this.fill(this.buf, length);
if (type != 105) {
if (type == 101) {
final int i = this.buf.getInt();
this.throwStatusError(this.buf, i);
}
throw new SftpException(4, "");
}
final SftpATTRS attr = SftpATTRS.getATTR(this.buf);
return attr;
}
catch (Exception e) {
if (e instanceof SftpException) {
throw (SftpException)e;
}
if (e instanceof Throwable) {
throw new SftpException(4, "", e);
}
throw new SftpException(4, "");
}
}
The error message comes from your server. It's indeed quite strange message, but I assume that it's some custom SFTP server that deals with some "messages" rather than plain files.
So the message basically translates to "Cannot find file" error of a traditional SFTP server. Even the error code 2 (SSH_FX_NO_SUCH_FILE) supports that.
Your path in remoteFile is probably wrong.

Printing using tsc ttp-342e pro thermal printer 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;
}

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

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

How do I get all the attachments from a .nsf(lotus notes) file using java

Steps followed :
Took a back of my lotus notes as sample.nsf
And then tried to read the attachments from the sample.nsf
Code snippet :
Database db = session.getDatabase("","C:\\Projects\\NotesToJava\\sample.nsf");
DocumentCollection dc = db.getAllDocuments();
Document doc = dc.getFirstDocument();
while (doc != null) {
RichTextItem body = (RichTextItem) doc.getFirstItem("Body");
if (body.getEmbeddedObject("Request.xlsx") != null)
System.out.println("Found BPM_Dev_Access_Request.xlsx in " + doc.getItemValueString("Subject"));
doc = dc.getNextDocument();
}
No need to use evaluate, look up the extractFile in the Lotus Designer Help
From the Lotus help:
import lotus.domino.*;
import java.util.Vector;
import java.util.Enumeration;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext = session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
DocumentCollection dc = db.getAllDocuments();
Document doc = dc.getFirstDocument();
boolean saveFlag = false;
while (doc != null) {
RichTextItem body =
(RichTextItem)doc.getFirstItem("Body");
System.out.println(doc.getItemValueString("Subject"));
Vector v = body.getEmbeddedObjects();
Enumeration e = v.elements();
while (e.hasMoreElements()) {
EmbeddedObject eo = (EmbeddedObject)e.nextElement();
if (eo.getType() == EmbeddedObject.EMBED_ATTACHMENT) {
eo.extractFile("c:\\extracts\\" + eo.getSource());
eo.remove();
saveFlag = true;
}
}
if (saveFlag) {
doc.save(true, true);
saveFlag = false;
}
doc = dc.getNextDocument();
}
} catch(NotesException e) {
System.out.println(e.id + " " + e.text);
e.printStackTrace();
}
}
}
You need to get the attachments out of each document, as opposed to the EmbeddedObjects. Something like this:
import java.util.Iterator;
import lotus.domino.*;
public final class DocAttachmentParser implements Iterator {
private Session s;
private Document doc;
private Double count ;
private Iterator attIterator = null;
public Double getCount() {
return count;
}
public DocAttachmentParser(Session s, Document doc) throws NotesException {
this.s = s;
this.doc = doc;
if (s!=null && doc !=null){
this.count = (Double) s.evaluate("#Attachments", doc).elementAt(0);
if (count.intValue() > 0){
attIterator = s.evaluate("#AttachmentNames", doc).iterator();
}
}
}
public boolean hasNext() {
return count.intValue() > 0 ? attIterator.hasNext(): false;
}
public Object next() {
return count.intValue() > 0 ? attIterator.next(): null;
}
private String nextAttName(){
return count.intValue() > 0 ? attIterator.next().toString(): null;
}
public void remove() {
if (count.intValue() > 0) attIterator.remove();
}
public String getAll(){
StringBuilder sb = new StringBuilder();
if (count.intValue()>0){
while (hasNext()) {
sb.append(nextAttName());
}
}
return sb.toString();
}
}
To get all attachment from a notes document then i wrote this method(part of my class).
This method takes the document and extract the attachment(Rich Text field)from Notes Document. This class also help you to know consider Example: In two document if there is same Attachment it extracts only one.
Here just you have to set "filePath" where you have to extract your attachment.
public boolean export(Document doc ) throws NotesException {
if (doc.hasEmbedded()) {
Vector<Item> allItems;
allItems = doc.getItems();
HashSet<String> attNames = new HashSet<String>();
for (int i = 0; i < allItems.size(); i++) {
Item item = allItems.get(i);
if (item.getType() == Item.RICHTEXT) {
RichTextItem riItem = (RichTextItem) item;
Vector emb = riItem.getEmbeddedObjects();
String[] doublette = new String[emb.size()];
Set<String> atts = new HashSet<String>();
for (int j = 0; j < emb.size(); j++) {
EmbeddedObject embObj = (EmbeddedObject) emb.get(j);
if (!attNames.contains(embObj.getName())) {
attNames.add(embObj.getName());
StringBuffer test = new StringBuffer(
embObj.getSource());
test.append('-');
test.append(embObj.getName());
test.append('-');
test.append(embObj.getFileSize());
String attDesc = test.toString();
if (atts.contains(attDesc)) {
doublette[j] = attDesc;
} else {
doublette[j] = "";
atts.add(attDesc);
}
}
}
for (int j = 0; j < emb.size(); j++) {
try {
EmbeddedObject embObj = (EmbeddedObject) emb.get(j);
String itemName = riItem.getName();
bOk = extractFile(embObj, itemName);
embObj.recycle();
} catch (NotesException e) {
bOk = false;
if (!"".equals(doublette[j])) {
bOk = true;
System.out.println(" duplicated attachment:")
log.append(doublette[j]);
}
}
}
}
}
}
return bOk;
}
private boolean extractFile(EmbeddedObject embObj, String itemName)
throws NotesException {
boolean bOk = true;
if (embObj.getType() == EmbeddedObject.EMBED_ATTACHMENT) {
String fileName = embObj.getName();
String filePath = this.filesPath + fileName;
// Check if file already exists, then delete
if (FileUtils.killFile(filePath, false, true, true)) {
embObj.extractFile(filePath);
} else {
bOk = false;
System.out.println(", error in kill: " + filePath);
}
}
return bOk;
}
Easy way to get all the attachments from Lotus Notes using Java.
Document doc = dc.getFirstDocument();
for(var att :session.evaluate("#AttachmentNames", doc)){
if (att == null || att.toString().isEmpty()) {
continue;
}
EmbeddedObject eb = doc.getAttachment(att.toString());
System.out.println(eb.getName());
System.out.println(eb.getFileSize());
eb.extractFile("a.txt");// give file name what u want
}

Categories