Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8376159
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 9, 20262026-06-09T15:21:48+00:00 2026-06-09T15:21:48+00:00

I am having trouble printing to a label printer. The code below prints 4

  • 0

I am having trouble printing to a label printer. The code below prints 4 “labels” on one (Picture of Label Attached).

The code below prints to a brother QL-500 label printer. It prints onto 3.5″ by 1.1″ labels.

It would also be great if someone could help me better understand the code.

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.print.PrintService;



public class DYMOLabelPrintConnector implements Printable {

public static final String PRINTERNAME = "DYMO LabelWriter 400";


public static final boolean PRINTMENU = false;

public static void main(String[] args) {
PrinterJob printerJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = printerJob.defaultPage();
Paper paper = new Paper();

final double widthPaper = (1.2 * 72);
final double heightPaper = (1.5 * 72);

paper.setSize(widthPaper, heightPaper);
paper.setImageableArea(0, 0, widthPaper, heightPaper);

pageFormat.setPaper(paper);

pageFormat.setOrientation(PageFormat.LANDSCAPE);

if (PRINTMENU) {
  if (printerJob.printDialog()) {
    printerJob.setPrintable(new DYMOLabelPrintConnector(), pageFormat); 

    try {
      printerJob.print();
    } catch (PrinterException e) {
      e.printStackTrace();
    }
  }
} else {
  PrintService[] printService = PrinterJob.lookupPrintServices();

  for (int i = 0; i < printService.length; i++) {
    System.out.println(printService[i].getName());

    if (printService[i].getName().compareTo(PRINTERNAME) == 0) {
      try {
        printerJob.setPrintService(printService[i]);
        printerJob.setPrintable(new DYMOLabelPrintConnector(), pageFormat); 
        printerJob.print();
      } catch (PrinterException e) {
        e.printStackTrace();
      }
    }
  }
}

System.exit(0);
 }

  public String getValue(final int elementOnLabel, final int labelCounter) {
  String value = "";

switch (elementOnLabel) {
case 0:
  // what ever you want to have in this line
  value = "SetupX";

  break;

case 1:
    // what ever you want to have in this line
  value = "fiehnlab.ucd";

  break;

case 2:
    // what ever you want to have in this line
  value = "id: " + labelCounter;

  break;

case 3:
    // what ever you want to have in this line
  // TODO - add DB connection
  value = "label:" + elementOnLabel;

  break;

case 4:
    // what ever you want to have in this line
  value = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(new Date());

  break;

default:
  break;
}

return value;
}


public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
System.out.println("printing page: " + pageIndex);

   if (pageIndex < getPageNumbers()) {
    Graphics2D g = (Graphics2D) graphics;

  // g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
  g.translate(20, 10);

  String value = "";
  pageIndex = pageIndex + 1;

  // specific for four circular labels per page
  for (int x = 0; x < 80; x = x + 50) {
    for (int y = 0; y < 80; y = y + 36) {
      int posOnPage = 4; // BottomRight, TopRight, BottomLeft, TopLeft 

      if (x > 0) {
        posOnPage = posOnPage - 2;
      }

      if (y > 0) {
        posOnPage = posOnPage - 1;
      }

      // current counter for the label.
      int id = (posOnPage - 1) + ((pageIndex - 1) * 4);

      // setupx
      g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 3));
      value = this.getValue(0, id);
      g.drawString("      " + value, x, y);

      // fiehnlab
      g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 3));
      value = this.getValue(1, id);
      g.drawString("    " + value, x, y + 4);

      // ID
      g.setFont(new Font(g.getFont().getFontName(), Font.BOLD, 7));
      value = this.getValue(2, id);
      g.drawString("" + value, x, y + 10);

      // label
      g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 5));
      value = this.getValue(3, id);
      g.drawString(" " + value, x, y + 16);

      // date
      g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, 3));
      value = this.getValue(4, id);
      g.drawString("      " + value, x, y + 20);
    }
  }

  return PAGE_EXISTS;
} else {
  return NO_SUCH_PAGE;
}
}

public int getPageNumbers() {
return 5;
 }
 }

enter code here

Here is What it Prints:

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-09T15:21:49+00:00Added an answer on June 9, 2026 at 3:21 pm

    Wow, I can’t tell you how much I love printing in Java, when it works, it’s great…

    .

    public class PrinterTest {
    
        public static void main(String[] args) {
    
            PrinterJob pj = PrinterJob.getPrinterJob();
            if (pj.printDialog()) {
                PageFormat pf = pj.defaultPage();
                Paper paper = pf.getPaper();    
                double width = fromCMToPPI(3.5);
                double height = fromCMToPPI(8.8);    
                paper.setSize(width, height);
                paper.setImageableArea(
                                fromCMToPPI(0.25), 
                                fromCMToPPI(0.5), 
                                width - fromCMToPPI(0.35), 
                                height - fromCMToPPI(1));                
                System.out.println("Before- " + dump(paper));    
                pf.setOrientation(PageFormat.PORTRAIT);
                pf.setPaper(paper);    
                System.out.println("After- " + dump(paper));
                System.out.println("After- " + dump(pf));                
                dump(pf);    
                PageFormat validatePage = pj.validatePage(pf);
                System.out.println("Valid- " + dump(validatePage));                
                //Book book = new Book();
                //book.append(new MyPrintable(), pf);
                //pj.setPageable(book);    
                pj.setPrintable(new MyPrintable(), pf);
                try {
                    pj.print();
                } catch (PrinterException ex) {
                    ex.printStackTrace();
                }    
            }    
        }
    
        protected static double fromCMToPPI(double cm) {            
            return toPPI(cm * 0.393700787);            
        }
    
        protected static double toPPI(double inch) {            
            return inch * 72d;            
        }
    
        protected static String dump(Paper paper) {            
            StringBuilder sb = new StringBuilder(64);
            sb.append(paper.getWidth()).append("x").append(paper.getHeight())
               .append("/").append(paper.getImageableX()).append("x").
               append(paper.getImageableY()).append(" - ").append(paper
           .getImageableWidth()).append("x").append(paper.getImageableHeight());            
            return sb.toString();            
        }
    
        protected static String dump(PageFormat pf) {    
            Paper paper = pf.getPaper();            
            return dump(paper);    
        }
    
        public static class MyPrintable implements Printable {
    
            @Override
            public int print(Graphics graphics, PageFormat pageFormat, 
                int pageIndex) throws PrinterException {    
                System.out.println(pageIndex);                
                int result = NO_SUCH_PAGE;    
                if (pageIndex < 2) {                    
                    Graphics2D g2d = (Graphics2D) graphics;                    
                    System.out.println("[Print] " + dump(pageFormat));                    
                    double width = pageFormat.getImageableWidth();
                    double height = pageFormat.getImageableHeight();    
                    g2d.translate((int) pageFormat.getImageableX(), 
                        (int) pageFormat.getImageableY());                    
                    g2d.draw(new Rectangle2D.Double(1, 1, width - 1, height - 1));                    
                    FontMetrics fm = g2d.getFontMetrics();
                    g2d.drawString("0x0", 0, fm.getAscent());    
                    result = PAGE_EXISTS;    
                }    
                return result;    
            }
        }
    }
    

    I’m aware of a number of inconsistencies with the PrintDialog doing werid and wonderful things if you try and specify Paper sizes and margins, but honestly, that’s a question for another day.

    The code I’ve posted was capable for printing two labels one after the other without issue on my Dymo LabelWriter 400 Turbo

    UPDATED
    Should also mention, I think you were basically missing PageFormat.setPaper

    UPDATED with Barbaque BarCode

    Print from file example…

    Barcode b = BarcodeFactory.createCode128("Hello");
    b.setResolution(72);
    
    File f = new File("mybarcode.png");
    // Let the barcode image handler do the hard work
    BarcodeImageHandler.savePNG(b, f);
    
    .
    .
    .
    
    public static class PrintFromFile implements Printable {
    
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    
            int result = NO_SUCH_PAGE;
            if (pageIndex == 0) {
    
                graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
    
                result = PAGE_EXISTS;
    
                try {
    
                    // You may want to rescale the image to better fit the label??
                    BufferedImage read = ImageIO.read(new File("mybarcode.png"));
                    graphics.drawImage(read, 0, 0, null);
    
                } catch (IOException ex) {
    
                    ex.printStackTrace();
    
                }
    
            }
    
            return result;
    
        }
    
    }
    

    Printing direct to the Graphics context

    Barcode b = BarcodeFactory.createCode128("Hello");
    b.setResolution(72);
    
    .
    .
    .
    
    public static class PrintToGraphics implements Printable {
    
        private Barcode b;
    
        private PrintToGraphics(Barcode b) {
    
            this.b = b;
    
        }
    
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
    
            int result = NO_SUCH_PAGE;
            if (pageIndex == 0) {
    
                result = PAGE_EXISTS;
    
                int x = (int)pageFormat.getImageableX();
                int y = (int)pageFormat.getImageableY();
    
                int width = (int)pageFormat.getImageableWidth();
                int height = (int)pageFormat.getImageableHeight();
    
                graphics.translate(x, y);
                try {
                    b.draw((Graphics2D)graphics, 0, 0);
                } catch (OutputException ex) {
    
                    ex.printStackTrace();
    
                }
    
            }
    
            return result;
    
        }
    
    }
    

    Last but not least, directly from the “examples” directory of the download

    public class PrintingExample
    {
    
        public static void main(String[] args)
        {
            try
            {
                Barcode b = BarcodeFactory.createCode128("Hello");
                PrinterJob job = PrinterJob.getPrinterJob();
                job.setPrintable(b);
                if (job.printDialog())
                {
                    job.print();
                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
    
        }
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am having a trouble with printing on ipad. My code prints the pdf
I'm having trouble printing a string in lines chat contains 60 characters. my code
I'm new to writing assembly code and I'm having trouble printing out the values
This might sound silly but i'm having trouble printing a variable in this code
I'm having trouble printing a web page of information, which should span onto about
Like the title says I'm having some trouble printing out symbol codes and their
I'm having some trouble with Visual Studio 2008. Very simple program: printing strings that
Having trouble with each function... Will try to explain by example... In my code,
Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc
I am almost done with implementing a printing functionality, but I am having trouble

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.