Una breve introducción al entorno operativo:
Idioma: Java
Herramienta: eclipse
Sistema: Windows 7
(El dispositivo de impresión aún no tiene uno, por lo que solo se pueden proporcionar imágenes de vista previa)
Recientemente, el proyecto necesita imprimir recibos de compras para el centro comercial. En la vida diaria, vamos al supermercado a comprar cosas. Al revisar, el cajero imprimirá un recibo. En general, el centro comercial también necesita una función tan pequeña. La demostración dada en este artículo es un ejemplo de una impresora térmica de 58 mm. Si es una impresora de otros tipos de papel, simplemente ajuste el ancho de papel.
prueba de paquete; import java.awt.*; import java.awt.print.*;/*** Clase de prueba de la impresora (58 mm)* 1. La impresora de destino debe establecerse como la impresora predeterminada* 2. El ancho de la página de impresión está relacionado con la impresora específica. Generalmente es el ancho del documento de impresión y debe configurarse como parámetros del sistema* 3. El ancho de un carácter chino es de aproximadamente 12 puntos*/public class PrintTest {public static void main (string [] args) {if (imprinterJob.lookUpPrintServices (). Longitud> 0) {/* impresión de forma de formatio*/PageFormat PageFormat esquina, de izquierda a derecha, de arriba a abajo, pageformat.setorientation (pageformat.portrait);/* Configuración de formato de página de impresión*/Paper Paper = new Paper (); // Establezca el ancho de impresión (fijo, relacionado con la impresora específica) y la altura (relacionado con el contenido de impresión real) Paper.setsize (140, 450); // Establezca el punto de partida específico, la impresión de altura y la altura de la altura. 135, 450); PageFormat.SetPaper (Paper); // Crear un libro de documento impreso Book = nuevo libro (); book.append (new imprimable () {@Override public int imprimir (gráficos gráficos gráficos, pageFormat PageFormat, int PageIndex) lanza PrinterException {if (PageIndex> 0) {return No_Such_Page;} Graphics2d Graphics = (Graphics fuente = nuevo Font ("安体", font.plain, 5); Graphics2d.setFont (Font); Drawstring (Graphics2d, "/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// estás ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// 119, 8); font = new font ("宋体", font.plain, 7); gráfico2d.setfont (font); int yindex = 30; int lineHeight = 10; int linewidth = 120; color defaultcolor = gráfico2d.getcolor (); color gris = new color (145, 145, 145); // recibió información yindex = gráfica (gráfica (); "Consignado: Passerby A", 10, Yindex, LineWidth, LineHeight); yIndex = DrawString (Graphics2d, "Dirección recibida: Baidu Building, No. 10 Shangdi Street, Haidian District, Beijing", 10, Yindex + LineHeight, Linewidth, LineHeight); // BasicsTroke.Cap_Butt, BasicsTroke.Join_Bevel, 0, New Float [] {4, 4}, 0); Graphics2d.setStroke (Stroke); Graphics2d.Drawrect (5, 10, 129, yindex); // Drugstore Namewidth = 129; LineHeight = 8; Graphics2d.setfont ("宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体 宋体" Font.Bold, 8)); Graphics2d.SetColor (DefaultColor); yIndex = DrawString (Graphics2d, "Beijing Pharmacy Ticket Retail", 5, Yindex + LineHeight + 20, LineWidth, 12); Graphics2D.SetFont (New Font ("宋体", Font.Plain, 6)); Graphics2D.Set.Set.Set; drawString(graphics2D, "Operator: Xiaoqing", 5, yIndex + lineHeight + 2, lineWidth, lineHeight);yIndex = drawString(graphics2D, "Date: 2017-01-05", 5 + lineWidth/2, yIndex, lineWidth, lineHeight);yIndex = drawString(graphics2D, "Product Name", 5, yIndex + LineHeight*2 - 5, LineWidth, LineHeight); yindex = DrawString (Graphics2d, "Especificación", (LineWidth/10)*4, yindex, LineWidth, LineHeight); yindex = DrawString (Graphics2D, "Unit Price", ((10)*8, yindex, LineWidth, LineHeHight); drawString(graphics2D, "quantity", (lineWidth/10)*10, yIndex, lineWidth, lineHeight);for (int i=0; i<5; i++){graphics2D.setFont(new Font("宋体", Font.PLAIN, 7));yIndex = drawString(graphics2D, "E Vitamin B Complex Tablets 100 E Vitamin B Complex Tablets 100 Tabletas ", 5, yindex + 15, (lineWidth/10)*7, 10); Graphics2d.setFont (new Font (" 安安 ", font.Plain, 6)); Graphics2d.SetColor (Gray); yindex = DrawString (Graphics2d," 100 Tablets/Box ", 5, YIndex + 11, LineWidth, LineHehight); Drawstring (Graphics2d, "14.50", (LineWidth/10)*8, yIndex, LineWidth, LineHeight); yindex = DrawString (Graphics2d, "2", (LineWidth/10)*10, yindex, LineWidth, LineHeight); Graphics2D.SetFont (New Font ("宋体", Font.plain, 7); yIndex + 2;graphics2D.drawLine(5, yIndex, 5 + lineWidth, yIndex);}graphics2D.setColor(defaultColor);yIndex = drawString(graphics2D, "Member Name: Xiaoqing", 5, yIndex + lineHeight * 2, lineWidth, lineHeight);yIndex = drawString(graphics2D, "Total: 6", 5, yindex + lineheight, linewidth, lineHeight); yindex = drawstring (gráfico2d, "total: 55.30", 5, yindex + lineheight, linewidth, lineHeight); yindex = drawString (gráfico2d, "efectivo: 100.00", 5, yindex + lineHeight, linewidth, lineheight); drawString(graphics2D, "change: 44.70", 5, yIndex + lineHeight, lineWidth, lineHeight);graphics2D.setFont(new Font("宋体", Font.PLAIN, 6));graphics2D.setColor(grey);yIndex = drawString(graphics2D, "Tel: 020-123456", 5, yIndex + lineHeight * 2, LineWidth, LineHeight); yindex = Drawstring (Graphics2d, "Dirección: Baidu Building, No. 10 Shangdi Street, Distrito de Haidian, Beijing", 5, Yindex + LineHeight, LineWidth, LineHeight); yindex = yindex + 20; Graphics2D.Drawline (0, yindex, yindex); Page_Exists;}}, PageFormat); // Obtenga la impresora predeterminada ImpresinterJob PrinterJob = PrinterJob.GetPrinterJob (); printPageable (Libro); Pruebe {ImprinterJob.Print ();} Catch (PrinterException e) {E.PrintStackTraace (); System.out.println ("Print Exception");}}} else {system.out.println ("no se puede descubrir el servicio de impresión");}}/*** salida de cadena* @param gráfico2d pincel* @param text imprima texto* @param x imprimir punto de partida x coordenada* @param y imprimir punto de iniciar y coordenado* @param linewidth línea width* @param lineheight línea altura* @return regresa a final y coordenado privado*/private static stine width linewidth DrawString (Graphics2D Graphics2d, String Text, int x, int y, int LineWidth, int LineHeight) {FontMetrics FontMetrics = Graphics2d.getFontMetrics (); if (FontMetrics.StringWidth (Text) <LineWidth) {Graphics2d.Dawstring (Text, X, Y); text.ToCarArray (); int charswidth = 0; stringBuffer sb = new StringBuffer (); for (int i = 0; i <chars.length; i ++) {if ((charswidth+fontmetrics.charwidth (chars [i])> linewidth) {gráfico2d.drawtring (sb.Tostring (), x, x, x, x, x, x, y); sb.setLength (0); y = y + lineHeight; charswidth = fontMetrics.charwidth (chars [i]); sb.append (chars [i]);} else {charswidth = charswidth + fontmetrics.charwidth (chars [i]); sb.append (chars [i]);}} if (sb.length ()> 0) {gráfico2d.drawstring (sb.ToString (), x, y); y = y + lineHeight;} return y - lineheight;}}}}}}}}}}}}}}}}}}}}}}}}}}}}Resultados de ejecución:
Vista previa del efecto:
Resumir
En pocas palabras, es escribir un programa Java, guardar el resultado de la salida como un archivo de formato "*.xps" y producirlo por la impresora, que es muy simple. Espero que sea útil para todos. Si tiene alguna pregunta, deje un mensaje y lo indique. Gracias amigos por su apoyo para este sitio.