Exporting jasper report to zebra printer not printing it completely - java

I have the following code for printing an invoice to zt410-300dpi printer:
private static void jasperPrint56(JasperPrint jasperPrint, String printerName) throws JRException, IOException {
PrinterJob job = PrinterJob.getPrinterJob();
PrintRequestAttributeSet printRequestAttributeSet = new HashPrintRequestAttributeSet();
PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet(new PrinterName(printerName, null));
PrintService[] printService = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
int selectedService = 0;
try {
job.setPrintService(printService[selectedService]);
} catch (Exception e) {
System.out.println(e);
}
JRPrintServiceExporter exporter = new JRPrintServiceExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
SimplePrintServiceExporterConfiguration configuration = new SimplePrintServiceExporterConfiguration();
configuration.setPrintService(job.getPrintService());
configuration.setPrintRequestAttributeSet(printRequestAttributeSet);
configuration.setPrintServiceAttributeSet(printServiceAttributeSet);
configuration.setDisplayPageDialog(false);
configuration.setDisplayPrintDialog(false);
exporter.setConfiguration(configuration);
exporter.exportReport();
}
This doesn't print the complete report and is only printing about 30% of it.
In the jrxml file, I have defined page width and height as follows:
pageWidth="288" pageHeight="432"
Which is 4 in x 6 in after converting for 72 dpi of jasper
In the printer properties, I have set the page size as 4x6 as well.

Related

Java Thermal Printer printing QRCode with Text

I am new to Java printing and wanted to to print a QRCode with a small number under it on a Thermal Printer (Brother QL-810W).
With my code I can print my QRCode, but I cannot figure out how to print a number or text, also I can't use ESC/P Commands for formatting.I tried using ByteArrays and escpos-coffe library but it won't work.
Code:
try {
DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
aset.add(MediaSizeName.INVOICE);
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService printService: services) {
if (printService.getName().equals("Brother QL-810W")) {
DocPrintJob pj = printService.createPrintJob();
FileInputStream fis = new FileInputStream("C:/Local/QRCode1.png");
Doc doc = new SimpleDoc(fis, flavor, null);
pj.print(doc, aset);
}
}
} catch (Exception e) {
System.out.println(e);
}
}
Heres the code I tried to work with the escpos-coffe libary:
try {
PrintService[] services = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService printService: services) {
if (printService.getName().equals("Brother QL-810W")) {
PrinterOutputStream printerOutputStream = new PrinterOutputStream(printService);
EscPos escpos = new EscPos(printerOutputStream);
escpos.writeLF("1235");
escpos.feed(5);
escpos.cut(EscPos.CutMode.FULL);
escpos.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
Thanks for helping me!

Dual Side printing with DocPrintJob (Java)

I am having two byte[], one is for front another for back. I want to print a single card, dual sided with those 2 byte arrays. My code looks like as below:-
private void print(byte[] frontSideByte, byte[] backSideByte) {
PrintService printService = getPritnerService();
DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
DocPrintJob job = printService.createPrintJob();
DocAttributeSet das = new HashDocAttributeSet();
das.add(Sides.DUPLEX);
das.add(new PrinterResolution(300, 300, PrinterResolution.DPI));
das.add(new MediaPrintableArea(0.0f, 0, 53.98f*2, 85.6f*2, MediaPrintableArea.MM));
das.add(findOrientation(frontSideByte));
Doc doc = new SimpleDoc(frontSideByte, flavor, das);
try {
job.print(doc, null);
} catch (Exception ex) {
System.out.println(ex);
}
}

Printing plain text files to PDF printer using javax.print results in an empty file

I need to create a pdf file from plain text files. I supposed that the simplest method would be read these files and print them to a PDF printer.
My problem is that if I print to a pdf printer, the result will be an empty pdf file. If I print to Microsoft XPS Document Writer, the file is created in plain text format, not in oxps format.
I would be satisfied with a two or three step solution. (Eg. converting to xps first then to pdf using ghostscript, or something similar).
I have tried a couple of pdf printers such as: CutePDF, Microsoft PDF writer, Bullzip PDF. The result is the same for each one.
The environment is Java 1.7/1.8 Win10
private void print() {
try {
DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
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("Microsoft XPS Document Writer")) { //
myService = printService;
break;
}
}
if (myService == null) {
throw new IllegalStateException("Printer not found");
}
myService.getSupportedDocFlavors();
DocPrintJob job = myService.createPrintJob();
FileInputStream fis1 = new FileInputStream("o:\\k\\t1.txt");
Doc pdfDoc = new SimpleDoc(fis1, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
HashPrintRequestAttributeSet pr = new HashPrintRequestAttributeSet();
pr.add(OrientationRequested.PORTRAIT);
pr.add(new Copies(1));
pr.add(MediaSizeName.ISO_A4);
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(pdfDoc, pr);
pjw.waitForDone();
fis1.close();
} catch (PrintException ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Docparser.class.getName()).log(Level.SEVERE, null, ex);
}
}
class PrintJobWatcher {
boolean done = false;
PrintJobWatcher(DocPrintJob job) {
job.addPrintJobListener(new PrintJobAdapter() {
public void printJobCanceled(PrintJobEvent pje) {
allDone();
}
public void printJobCompleted(PrintJobEvent pje) {
allDone();
}
public void printJobFailed(PrintJobEvent pje) {
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
If you can install LibreOffice, it is possible to use the Java UNO API to do this.
There is a similar example here which will load and save a file: Java Convert Word to PDF with UNO. This could be used to convert your text file to PDF.
Alternatively, you could take the text file and send it directly to the printer using the same API.
The following JARs give access to the UNO API. Ensure these are in your class path:
[Libre Office Dir]/URE/java/juh.jar
[Libre Office Dir]/URE/java/jurt.jar
[Libre Office Dir]/URE/java/ridl.jar
[Libre Office Dir]/program/classes/unoil.jar
[Libre Office Dir]/program
The following code will then take your sourceFile and print to the printer named "Local Printer 1".
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.sun.star.beans.PropertyValue;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.XPrintable;
public class DirectPrintTest
{
public static void main(String args[])
{
// set to the correct name of your printers
String printer = "Local Printer 1";// "Microsoft Print to PDF";
File sourceFile = new File("c:/projects/WelcomeTemplate.doc");
if (!sourceFile.canRead()) {
throw new RuntimeException("Can't read:" + sourceFile.getPath());
}
com.sun.star.uno.XComponentContext xContext = null;
try {
// get the remote office component context
xContext = com.sun.star.comp.helper.Bootstrap.bootstrap();
System.out.println("Connected to a running office ...");
// get the remote office service manager
com.sun.star.lang.XMultiComponentFactory xMCF = xContext
.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext(
"com.sun.star.frame.Desktop", xContext);
com.sun.star.frame.XComponentLoader xCompLoader = (XComponentLoader) UnoRuntime
.queryInterface(com.sun.star.frame.XComponentLoader.class,
oDesktop);
StringBuffer sUrl = new StringBuffer("file:///");
sUrl.append(sourceFile.getCanonicalPath().replace('\\', '/'));
List<PropertyValue> loadPropsList = new ArrayList<PropertyValue>();
PropertyValue pv = new PropertyValue();
pv.Name = "Hidden";
pv.Value = Boolean.TRUE;
loadPropsList.add(pv);
PropertyValue[] loadProps = new PropertyValue[loadPropsList.size()];
loadPropsList.toArray(loadProps);
// Load a Writer document, which will be automatically displayed
com.sun.star.lang.XComponent xComp = xCompLoader
.loadComponentFromURL(sUrl.toString(), "_blank", 0,
loadProps);
// Querying for the interface XPrintable on the loaded document
com.sun.star.view.XPrintable xPrintable = (XPrintable) UnoRuntime
.queryInterface(com.sun.star.view.XPrintable.class, xComp);
// Setting the property "Name" for the favoured printer (name of
// IP address)
com.sun.star.beans.PropertyValue propertyValue[] = new com.sun.star.beans.PropertyValue[2];
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Name";
propertyValue[0].Value = printer;
// Setting the name of the printer
xPrintable.setPrinter(propertyValue);
propertyValue[0] = new com.sun.star.beans.PropertyValue();
propertyValue[0].Name = "Wait";
propertyValue[0].Value = Boolean.TRUE;
// Printing the loaded document
System.out.println("sending print");
xPrintable.print(propertyValue);
System.out.println("closing doc");
((com.sun.star.util.XCloseable) UnoRuntime.queryInterface(
com.sun.star.util.XCloseable.class, xPrintable))
.close(true);
System.out.println("closed");
System.exit(0);
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(1);
}
}
}
Thank you for all. After two days struggling with various type of printers (I gave a chance to CUPS PDF printer too but I could not make it to print in landscape mode) I ended up using the Apache PDFbox.
It's only a POC solution but works and fits to my needs. I hope it will be useful for somebody.
( cleanTextContent() method removes some ESC control characters from the line to be printed. )
public void txt2pdf() {
float POINTS_PER_INCH = 72;
float POINTS_PER_MM = 1 / (10 * 2.54f) * POINTS_PER_INCH;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:m.ss");
PDDocument doc = null;
try {
doc = new PDDocument();
PDPage page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(page);
PDPageContentStream content = new PDPageContentStream(doc, page);
//PDFont pdfFont = PDType1Font.HELVETICA;
PDFont pdfFont = PDTrueTypeFont.loadTTF(doc, new File("c:\\Windows\\Fonts\\lucon.ttf"));
float fontSize = 10;
float leading = 1.1f * fontSize;
PDRectangle mediabox = page.getMediaBox();
float margin = 20;
float startX = mediabox.getLowerLeftX() + margin;
float startY = mediabox.getUpperRightY() - margin;
content.setFont(pdfFont, fontSize);
content.beginText();
content.setLeading(leading);
content.newLineAtOffset(startX, startY);
BufferedReader fis1 = new BufferedReader(new InputStreamReader(new FileInputStream("o:\\k\\t1.txt"), "cp852"));
String inString;
//content.setRenderingMode(RenderingMode.FILL_STROKE);
float currentY = startY + 60;
float hitOsszesenOffset = 0;
int pageNumber = 1;
while ((inString = fis1.readLine()) != null) {
currentY -= leading;
if (currentY <= margin) {
content.newLineAtOffset(0, (mediabox.getLowerLeftX()-35));
content.showText("Date Generated: " + dateFormat.format(new Date()));
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftX()));
content.showText(String.valueOf(pageNumber++)+" lap");
content.endText();
float yCordinate = currentY+30;
float sX = mediabox.getLowerLeftY()+ 35;
float endX = mediabox.getUpperRightX() - 35;
content.moveTo(sX, yCordinate);
content.lineTo(endX, yCordinate);
content.stroke();
content.close();
PDPage new_Page = new PDPage(new PDRectangle(297 * POINTS_PER_MM, 210 * POINTS_PER_MM));
doc.addPage(new_Page);
content = new PDPageContentStream(doc, new_Page);
content.beginText();
content.setFont(pdfFont, fontSize);
content.newLineAtOffset(startX, startY);
currentY = startY;
}
String ss = new String(inString.getBytes(), "UTF8");
ss = cleanTextContent(ss);
if (!ss.isEmpty()) {
if (ss.contains("JAN") || ss.contains("SUMMARY")) {
content.setRenderingMode(RenderingMode.FILL_STROKE);
}
content.newLineAtOffset(0, -leading);
content.showText(ss);
}
content.setRenderingMode(RenderingMode.FILL);
}
content.newLineAtOffset((mediabox.getUpperRightX() / 2), (mediabox.getLowerLeftY()));
content.showText(String.valueOf(pageNumber++));
content.endText();
fis1.close();
content.close();
doc.save("o:\\k\\t1.pdf");
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (doc != null) {
try {
doc.close();
} catch (IOException ex) {
Logger.getLogger(Document_Creation.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}

File rendering for PDF file print

I tried below code for print the PDF file for
public static void main(String args[])
{
FileInputStream psStream = null;
try {
psStream = new FileInputStream("E://ssc exam.pdf");
} catch (FileNotFoundException ffne) {
ffne.printStackTrace();
}
if (psStream == null) {
return;
}
DocFlavor psInFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(psStream, psInFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PrintService[] services = PrintServiceLookup.lookupPrintServices(psInFormat, aset);
// this step is necessary because I have several printers configured
PrintService myPrinter = null;
for (int i = 0; i < services.length; i++){
String svcName = services[i].toString();
System.out.println("service found: "+svcName);
if (svcName.contains("sfg")){
myPrinter = services[i];
System.out.println("my printer found: "+svcName);
break;
}
}
if (myPrinter != null) {
DocPrintJob job = myPrinter.createPrintJob();
try {
job.print(myDoc, aset);
} catch (Exception pe) {
pe.printStackTrace();}
} else {
System.out.println("no printer services found");
}
}
}
but i got "PDF file not printed.128 MB of memory is required to enable direct PDF printing" error,So I decide to use PDF rendering for print the PDF.can anyone to help how to use PDFfile rendering concept in detail.

Can't print file to printer using java applet

i have created java applet class, to print text file to printer, but when i running this program is nothing happend, in my printer status is no activity...
this is my applet code (print function) :
public void testPrintDoPrivileged(){
AccessController.doPrivileged(new PrivilegedAction() {
#Override
public Object run() {
FileInputStream textStream;
try{
textStream = new FileInputStream("D:\\email_address.txt");
DocFlavor myFormat = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc myDoc = new SimpleDoc(textStream, myFormat, null);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new Copies(1));
aset.add(Sides.ONE_SIDED);
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
System.out.println("Printing to default printer: "+ printService.getName());
DocPrintJob job = printService.createPrintJob();
job.print(myDoc, aset);
} catch( FileNotFoundException e1){
e1.printStackTrace(System.out);
System.err.println(e1);
} catch (PrintException ex) {
System.err.println(ex);
}
return null;
}
});
}
and then by accident, i unplug my usb printer, then i try to test print again...
in my printer(offline now) status is show a pending document.
this is the picture :
there something wrong in my code or else..?.
sorry for my english...
thank you before...
Edit :
the problem is in DocFlavor.
my code running well in linux OS...
because linux have much DocFlavor support...
i use this code to check DocFlavor:
PrintService printServices = PrintServiceLookup.lookupDefaultPrintService();
DocFlavor[] docF = printServices.getSupportedDocFlavors();
for(int i = 0; i < docF.length; i++){
System.out.println(docF[i].getMimeType());
}

Categories

Resources