Issue with printing long receipts with java print() on thermal printer - java

I cannot print a thermal receipt (8cm) beyond (almost) A4 height paper size. Program only prints till (some default almost) A4 size is reached. and rest of receipt is lost.
Everything works fine with smaller receipts. problem occurs only with long receipts, where bill is cut short. I dynamically set paper height counting the lines to print. I also tried setting paper size and imageablearea to big size manually but in vain.
I tried to use Print.Book class object as well with no improvement.
(Note: Another program written in another language, prints same bill fine on same printer)
Please let me know if I am missing something or how to remove this limitation.
public void printReciept()
{
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(new BillPrintable(),getPageFormat(pj));
try {
pj.print();
}
catch (PrinterException ex) {
ex.printStackTrace();
}
}
public PageFormat getPageFormat(PrinterJob pj)
{
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
double middleHeight =this.productList.size()*1.0; //dynamic----->change with the row count of jtable
double headerHeight = 5.0; //fixed----->but can be mod
double footerHeight = 5.0; //fixed----->but can be mod
double width = convert_CM_To_PPI(8); //printer know only point per inch.default value is 72ppi
double height = convert_CM_To_PPI(headerHeight+middleHeight+footerHeight);
paper.setSize(width, height);
paper.setImageableArea(
0,
10,
width,
height - convert_CM_To_PPI(1)
); //define boarder size after that print area width is about 180 points
pf.setOrientation(PageFormat.PORTRAIT); //select orientation portrait or landscape but for this time portrait
pf.setPaper(paper);
return pf;
}
public class BillPrintable implements Printable {
#Override
public int print(Graphics graphics, PageFormat pageFormat,int pageIndex)
throws PrinterException
{
String title[] = {"Product Name","Disc","Rate","Qty","AMT"};
int result = NO_SUCH_PAGE;
if (pageIndex == 0) {
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate((int) pageFormat.getImageableX(),(int) pageFormat.getImageableY());
***** Below will be Code to print bill records *****
}
}

Related

how to adjust print JFrame print according to billing printer size

Hey I'm trying to make an invoice software everything is fine while I'm printing bill then it is printing according to standard printer size but I want to print it through billing printer I'm not using jesper report or any other reporting software I'm just print JFrame by swing code.
Here is my code. . .
final Component comp;
public testing(Component comp){
this.comp=comp;
}
#Override
public int print(Graphics g, PageFormat format, int page_index)
throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = comp.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
comp.paint(g2);
return Printable.PAGE_EXISTS;
}
//_____________________________________pint Method
public static void printing(){
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.defaultPage();
//If user does not hit cancel then print.
if (preformat != postformat) {
//Set print component
pjob.setPrintable(new testing(frame), postformat);
// if (pjob.printDialog()) {
try {
pjob.print();
} catch (PrinterException ex) {
Logger.getLogger(testing.class.getName()).log(Level.SEVERE, null, ex);
}
//}
}
}
Is there any Idea how to print it fit the printer roll because there is no any option to print paper fit to printing roll paper.
Thnkx in advance.

Java: Setting printable width (Pageformat)

I am attempting to print from my java application to a receipt printer,
the width of the receipt is 58mm, it seems that the margin is incorrect and printing with a margin of 1 inch on either side. This results in only 3 letters/numbers being printed and not the full line.
I can print from notepad successfully as I have manually adjusted the margin to 1.97mm on either side which seems to do the trick.
My code is as follows;
public int print(Graphics g, PageFormat pf, int pageIndex)
throws PrinterException {
Font font = new Font("MONOSPACED", Font.PLAIN, 10);
FontMetrics metrics = g.getFontMetrics(font);
int lineHeight = metrics.getHeight();
if (pageBreaks == null) {
initTextLines();
int linesPerPage = (int)(pf.getImageableHeight()/lineHeight);
int numBreaks = (textLines.length-1)/linesPerPage;
pageBreaks = new int[numBreaks];
for (int b=0; b<numBreaks; b++) {
pageBreaks[b] = (b+1)*linesPerPage;
}
}
if (pageIndex > pageBreaks.length) {
return NO_SUCH_PAGE;
}
/* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
* Since we are drawing text we
*/
Graphics2D g2d = (Graphics2D)g;
g2d.setFont(new Font("MONOSPACED", Font.PLAIN, 10));
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Draw each line that is on this page.
* Increment 'y' position by lineHeight for each line.
*/
int y = 0;
int start = (pageIndex == 0) ? 0 : pageBreaks[pageIndex-1];
int end = (pageIndex == pageBreaks.length)
? textLines.length : pageBreaks[pageIndex];
for (int line=start; line<end; line++) {
y += lineHeight;
g.drawString(textLines[line], 0, y);
}
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
}
I would also be grateful if you could help me align the text to the right hand side of the receipt to keep it uniformed with out other systems, however my main issue is the margin if that is sorted I will be over the moon :)
Thank You!
p.s. I am new to printing from java and have struggled, might have redundant code from copying online sources. I have adjusted the font so it is smaller, that did not help much.
I have figured out a workaround to get the desired results, just adding spaces before the text seems to work out well, I have also adjusted the code as follows;
public void print() throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
InputStream is = new ByteArrayInputStream(printableAmounts.getBytes("UTF8"));
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new Copies(1));
DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
Doc doc = new SimpleDoc(is, flavor, null);
DocPrintJob job = service.createPrintJob();
PrintJobWatcher pjw = new PrintJobWatcher(job);
job.print(doc, pras);
pjw.waitForDone();
is.close();
}
Seems to be a temporary solution but if nothing else comes up it will become permanent.

java PrinterJob not printing to fit paper

i am stuck currently when printing a jpeg file with the default printer. In my program when i select an image from a folder, i need to print it using the printer default settings (paper size, margins, orientation).
Currently i got this:
PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
final BufferedImage image = ImageIO.read(new File("car.jpg"));
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintService(printService);
printJob.setPrintable(new Printable(){
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException{
if (pageIndex == 0) {
graphics.drawImage(image, 0, 0, (int)pageFormat.getWidth(), (int)pageFormat.getHeight(), null);
return PAGE_EXISTS;
else return NO_SUCH_PAGE;
}
}
printJob.print();
The default settings for my printer right now for size is: 10 x 15 cm (4 x 6 in)
but when i set my program to print the given image, it displays only a small section of the paper.
Please help me out.
EDIT
thanks everyone for their help, i managed to find the answer posted by another user at Borderless printing
Make sure that you are, first, translating the Graphics context to fit within inthe imagable area...
g2d.translate((int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());
Next, make sure you are using the imageableWidth and imageableHeight of the PageFormat
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
and not the width/height properties. Many of these things get translated from different contexts...
graphics.drawImage(image, 0, 0, (int)width, (int)height, null);
The getImageableWidth/Height returns the page size within the context of the page orientation
Printing pretty much assumes a dpi of 72 (don't stress, the printing API can handle much higher resolutions, but the core API assumes 72dpi)
This means that a page of 10x15cm should translate to 283.46456664x425.19684996 pixels. You can verify this information by using a System.out.println and dumping the results of getImageableWidth/Height to the console.
If you're getting different settings, it's possible that Java has overridden the default page properties
For example...
Fit image into the printing area
Setting print size of a jLabel and put a jRadiobutton on the print
You have two choices...
You could...
Show the PrintDialog and ensure that the correct page settings are selected
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(new PrinterResolution(300, 300, PrinterResolution.DPI));
aset.add(new MediaPrintableArea(0, 0, 150, 100, MediaPrintableArea.MM));
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setPrintable(new PrintTask()); // You Printable here
if (pj.printDialog(aset)) {
try {
pj.print(aset);
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
Or you could...
Just manually set the paper/page values manually...
public static void main(String[] args) {
PrinterJob pj = PrinterJob.getPrinterJob();
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
// 10x15mm
double width = cmsToPixel(10, 72);
double height = cmsToPixel(15, 72);
paper.setSize(width, height);
// 10 mm border...
paper.setImageableArea(
cmsToPixel(0.1, 72),
cmsToPixel(0.1, 72),
width - cmsToPixel(0.1, 72),
height - cmsToPixel(0.1, 72));
// Orientation
pf.setOrientation(PageFormat.PORTRAIT);
pf.setPaper(paper);
PageFormat validatePage = pj.validatePage(pf);
pj.setPrintable(new Printable() {
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
// Your code here
return NO_SUCH_PAGE;
}
}, validatePage);
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
// The number of CMs per Inch
public static final double CM_PER_INCH = 0.393700787d;
// The number of Inches per CMs
public static final double INCH_PER_CM = 2.545d;
// The number of Inches per mm's
public static final double INCH_PER_MM = 25.45d;
/**
* Converts the given pixels to cm's based on the supplied DPI
*
* #param pixels
* #param dpi
* #return
*/
public static double pixelsToCms(double pixels, double dpi) {
return inchesToCms(pixels / dpi);
}
/**
* Converts the given cm's to pixels based on the supplied DPI
*
* #param cms
* #param dpi
* #return
*/
public static double cmsToPixel(double cms, double dpi) {
return cmToInches(cms) * dpi;
}
/**
* Converts the given cm's to inches
*
* #param cms
* #return
*/
public static double cmToInches(double cms) {
return cms * CM_PER_INCH;
}
/**
* Converts the given inches to cm's
*
* #param inch
* #return
*/
public static double inchesToCms(double inch) {
return inch * INCH_PER_CM;
}
It looks like you are printing the image with dimensions based on the PageFormat, rather than the actual image's dimensions, your drawImage() method should look something like this
graphics.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null)

Fix text stretching when printing to a receipt printer with Java

I am printing to some Epson receipt printers by implementing the Java Printable and placing my code into the print method. To draw the text to the printer I use Graphics2D.drawString. I am also drawing a rect to the printer to see how to compares to the text size when printing to other printers. When printing to the receipt printer the text on the paper is about double the width of printing to a laser printer or the XPS writer virtual print. Is this a problem with the way Java draws text to the Graphics2D object? I have the newest version of Java installed of 6 update 20.
Any Ideas of what to look into would be helpful.
Thanks.
Here the code I am using. With this example I am seeing the letter 'c' on the right edge of the rect when sending it to a XPS writer and if I print it to my receipt printer the 6 is on the right edge of the rect and you can tell the text is much wider then it should be. The rect seems to be the correct size.
I have tried changing the page and margin sizes but it does not seem to fix my text problem. I got these paper sizes and margins from how Microsoft Word is auto detecting the printer. Word prints the text correctly to the receipt printer.
public static void main(String[] args) {
PageFormat format = new PageFormat();
Paper paper = new Paper();
double paperWidth = 3.25;
double paperHeight = 11.69;
double leftMargin = 0.19;
double rightMargin = 0.25;
double topMargin = 0;
double bottomMargin = 0.01;
paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
paper.setImageableArea(leftMargin * 72.0, topMargin * 72.0,
(paperWidth - leftMargin - rightMargin) * 72.0,
(paperHeight - topMargin - bottomMargin) * 72.0);
format.setPaper(paper);
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(OrientationRequested.PORTRAIT);
PrinterJob printerJob = PrinterJob.getPrinterJob();
Printable printable = new ReceiptPrintTest();
format = printerJob.validatePage(format);
printerJob.setPrintable(printable, format);
try {
printerJob.print(aset);
}
catch (Exception e) {
e.printStackTrace();
}
}
public class ReceiptPrintTest implements Printable {
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
if (pageIndex < 0 || pageIndex >= 1) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
Font font = new Font("Arial",Font.PLAIN, 14);
g2d.setFont(font);
g2d.drawString("1234567890abcdefg", 50, 70);
g2d.drawRect(50, 0, 100, 50);
return Printable.PAGE_EXISTS;
}
Have you tried setting the font using setFont?

How do I get hold of the margins of the Paper when using java printing?

I'm trying to print a JPanel with some painted graphics on it (overriding paintComponent). The graphics is so big that they wont fit on a single page and therefor I'm letting it span across multiple pages. My problem lies within the fact that if I let the user choose the pageFormat/Paper type by calling:
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
PageFormat pf = printJob.pageDialog(aset);
printJob.setPrintable(canvas, pf);
When I'm writing my print() method (implementing Printable) in my JPanel class I can't seem to get the hold of the margins? I use graphics.translate(pageFormat.getImageableX(), pageFormat.getImageableY()); to make it start drawing in the correct topleft corner (0;0) and it takes the margins into consideration (i.e.,starting more at (80; 100) or so). But then it prints over the bottom and right margin which I don't want it to do since that negates the user's wishes.
Here is the code of my print() method as a reference, which works fine when you don't let the user set the paper (using the default instead):
Rectangle[] pageBreaks;
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
//Calculate how many pages our print will be
if(pageBreaks == null){
double pageWidth = pageFormat.getPaper().getWidth();
double pageHeight = pageFormat.getPaper().getHeight();
//Find out how many pages we need
int numberOfPagesHigh = (int) Math.ceil(size.getHeight()/pageHeight);
int numberOfPagesWide = (int) Math.ceil(size.getWidth()/pageWidth);
pageBreaks = new Rectangle[numberOfPagesHigh*numberOfPagesWide];
double x = 0;
double y = 0;
int curXPage = 0;
//Calculate what we will print on each page
for (int i = 0; i < pageBreaks.length; i++){
double xStart = x;
double yStart = y;
x += pageWidth;
pageBreaks[i] = new Rectangle((int)xStart, (int)yStart, (int)pageWidth, (int)pageHeight);
curXPage++;
if (curXPage > numberOfPagesWide){
curXPage = 0;
x = 0;
y += pageHeight;
}
}
}
if (pageIndex < pageBreaks.length){
//Cast graphics to Graphics2D for richer API
Graphics2D g2d = (Graphics2D) graphics;
//Translate into position of the paper
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
//Setup our current page
Rectangle rect = pageBreaks[pageIndex];
g2d.translate(-rect.x, -rect.y);
g2d.setClip(rect.x, rect.y, rect.width, rect.height);
//Paint the component on the graphics object
Color oldBG = this.getBackground();
this.setBackground(Color.white);
util.PrintUtilities.disableDoubleBuffering(this);
this.paintComponent(g2d);
util.PrintUtilities.enableDoubleBuffering(this);
this.setBackground(oldBG);
//Return
return PAGE_EXISTS;
}
else {
return NO_SUCH_PAGE;
}
}
After posting this question and tabbing back into my IDE I pretty easily found the answer. Instead of using
double pageWidth = pageFormat.getPaper().getWidth();
double pageHeight = pageFormat.getPaper().getHeight();
use
double pageWidth = pageFormat.getImageableWidth();
double pageHeight = pageFormat.getImageableHeight();
The getImageableWidth() returns the totalPaperWidth-totalMargins whereas getWidth() just returns totalPaperWidth. This makes the print() method not draw more that it can on each page!

Categories