w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Printing on a thermal printer Java

After a lot of research and a applying a little brain, I found out the solution. It was a very small but silly mistake. Read the following source code:

public class printnow {

  public static void printCard(final String bill ){
final PrinterJob job = PrinterJob.getPrinterJob();

Printable contentToPrint = new Printable(){
   public int print(Graphics graphics, PageFormat pageFormat, int
pageIndex) throws PrinterException {

       Graphics2D g2d = (Graphics2D) graphics;

    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.setFont(new Font("Monospaced", Font.BOLD, 7));

       if (pageIndex >0){return NO_SUCH_PAGE;} //Only one page

      String Bill [] = bill.split(";");

      int y = 0;
    for (int i = 0; i < Bill.length; i++) {

        g2d.drawString(Bill[i], 0, y);
        y = y + 15;

    return PAGE_EXISTS;



        PageFormat pageFormat = new PageFormat();
      Paper pPaper = pageFormat.getPaper();

   pPaper.setImageableArea(0, 0, pPaper.getWidth() , pPaper.getHeight()

   job.setPrintable(contentToPrint, pageFormat);

    try {

  } catch (PrinterException e) {

In the previous source code (the wrong one), when the application triggers a print dialog box and the user clicks OK, the default printing preferences are transferred to the Java app and it prints what is required. but when we disable the print dialog box by removing this line: boolean don = job.printDialog();

an unknow PageFormat is transferred which arises out of nowhere. The problem was not with our defined PageFormat, the problem was that the pageFormat is passed to a printing method which we were not doing initially:

job.setPrintable(contentToPrint, pageFormat);

Notice the second parameter being passed to the above method. Hope this helps everyone. :)

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.