Saltar al contenido

Impresión en Java en una impresora de etiquetas

Solución:

Vaya, no puedo decirte cuánto me encanta imprimir en Java, cuando funciona, es genial …

.

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("https://foroayuda.es/").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;    
        }
    }
}

Soy consciente de una serie de inconsistencias con PrintDialog haciendo cosas maravillosas y maravillosas si intenta especificar tamaños de papel y márgenes, pero honestamente, esa es una pregunta para otro día.

El código que publiqué fue capaz de imprimir dos etiquetas una tras otra sin problemas en mi Dymo LabelWriter 400 Turbo

ACTUALIZADO
También debería mencionar, creo que básicamente te estabas perdiendo PageFormat.setPaper

ACTUALIZADO con Barbaque BarCode

Ejemplo de impresión desde archivo …

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;

    }

}

Impresión directa en el contexto de gráficos

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;

    }

}

Por último, pero no menos importante, directamente desde el directorio de “ejemplos” de la descarga.

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();
        }

    }

}
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *