Краткое введение в операционную среду:
Язык: Java
Инструмент: Eclipse
Система: Windows 7
(Устройство печати еще нет, поэтому можно предоставить только изображения предварительного просмотра)
Недавно проект должен печатать квитанции по магазинам для торгового центра. В повседневной жизни мы идем в супермаркет, чтобы купить вещи. При проверке кассир распечатает квитанцию. Как правило, торговый центр также нуждается в такой небольшой функции. Демонстрация, приведенная в этой статье, является примером 58 -мм теплового принтера. Если это принтер других типов бумаги, просто отрегулируйте ширину бумаги.
Пакет Test; импорт java.awt.*; import java.awt.print.*;/*** Класс тестирования принтера (58 мм)* 1. It is generally the width of the printing paper and needs to be configured as system parameters* 3. The width of a Chinese character is about 12 points*/public class PrintTest {public static void main(String[] args){if(PrinterJob.lookupPrintServices().length>0){/* Print format*/PageFormat pageFormat = new PageFormat();//Set the print starting point starts from the upper left Угол, слева направо, сверху вниз, Pageformat.Setorientation (pageformat.portrait);/* Настройки формата страницы печати*/Paper Paper = New Paper (); // Установите ширину печати (фиксированная, связанная с конкретным принтером) и высотой (связанный с фактическим содержимым печати) Paper.setize (140, 450); // Установить координату печатной точки, печать и высота. 135, 450); Pageformat.setpaper (Paper); // Создать печатную книгу документов Book = new Book (); Book.Append (new Printable () {@Override public int print (Graphics Graphics, Pageformat page -format, int pageIndex) throws graphics2 graphics2 raphics2 raphics2 raphics2 = (pageindex> 0) {return no_such_page; font = new Font ("安体", font.plain, 5); Graphics2d.setfont (Font); ShishString (Graphics2d, "///////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// 119, 8); font = новый шрифт ("宋体", font.plain, 7); Graphics2d.setfont (font); int yindex = 30; int lineHeight = 10; int linewidth = 120; Color DefaultColor = Graphics2d.GetColor (); Color Grey Color (145, 145, 145); // полученная информация yIndex = 2 -й навесок = 2 -й навесок = 2 -й навесок. «Справочник: прохожие A», 10, Yindex, Linewidth, Lineheight); yindex = школьник (Graphics2d, «Получен адрес: Baidu Building, № 10 Shangdi Street, Haidian District, Beijing», 10, Yindex + Lineheight, Linewidth, LineHeight);//Полученная пограничная инсульта = New BasicStroke (0.5f, 0.5f, 0.5f, 0. BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL,0,new float[]{4, 4},0);graphics2D.setStroke(stroke);graphics2D.drawRect(5, 10, 129, yIndex);//Drugstore name lineWidth = 129;lineHeight = 8;graphics2D.setFont(new Font("宋体", Font.BOLD, 8); Graphics2d.setcolor (defaultcolor); yindex = шнур (Graphics2d, «Пекинский аптечный билет», 5, Yindex + Lineheight + 20, Linewidth, 12); Graphics2d.setfont (New Font («宋体», Font.Plain, 6); «Оператор: xiaoqing», 5, yindex + lineheight + 2, linewidth, lineheight); yindex = шнур (Graphics2d, «Дата: 2017-01-05», 5 + linewidth/2, yindex, linewidth, lineheight); yindex = trawstring (graphics2d, name nemex 5, yindex); LineWidth, LineHeight); yIndex = завязок (Graphics2d, «Speciation», (LineWidth/10)*4, Yindex, LineWidth, LineHeight); yIndex = Brashics2d, «единица цена», (LineWidth/10)*8, yindex, lineWidth, LineHeight); (linewidth/10)*10, yindex, linewidth, lineheight); для (int i = 0; i <5; i ++) {graphics2d.setfont (новый шрифт («宋体», Font.plain, 7); yIndex = защелки (Graphics2d, «E -vitamin b -комплекс 100 Ebletemin B. (linewidth/10)*7, 10); Graphics2d.setfont (новый шрифт («安安», font.plain, 6)); графика2d.setcolor (grey); yindex = штрих (Graphics2d, «100 таблетки/коробка», 5, Yindex + 11, LineWidth, LineHeight); (linewidth/10)*8, yindex, linewidth, lineheight); yindex = завязывание (Graphics2d, "2", (LineWidth/10)*10, Yindex, LineWidth, LineHeight); Graphics2d.setfont (new Font ("宋体", font.plain, 7); yindex = yindex + 2; yindex, 5 + linewidth, yindex);} graphics2d.setcolor (defaultcolor); yindex = завязка на шнур (Graphics2d, «Имя члена: xiaoqing», 5, yindex + lineheight * 2, linewidth, lineheight); yindex = trawstring (graphics2d, ”total: 6" LineHeight); yIndex = завязка на шнур (Graphics2d, «Total: 55,30», 5, Yindex + LineHeight, LineWidth, LineHeight); yindex = Шуфтя (Graphics2d, «Денежный: 100,00», 5, yindex + lineHeight, linewidth, lineHeight); Yindex = ShorString (Graphics2d, «44.7 yindex + lineheight, linewidth, lineheight); graphics2d.setfont (new Font ("宋体", font.plain, 6)); Graphics2d.setcolor (Grey); yindex = ShoreSting (Graphics2d, "Тел: 020-12346", 5, yindex + lineHight * 2, lineWidth, lineheHex); ShishString (Graphics2d, «Адрес: Baidu Building, № 10 Shangdi Street, Haidian District, Beijing», 5, Yindex + LineHeight, LineWidth, LineHeight); yIndex = yindex + 20; Graphics2d.drawline (0, yindex, 140, yindex); return Page_exists;}}, pageform, prepormatm, printrat, printrej, printrej, printrej, gaterhobsform); printerjob = printerjob.getprinterjob (); printpagable (book); try {printerjob.print ();} catch (printerexception e) {e.printstacktrace (); System.out.println ("print Exception");}} use {system.out.println ("print service не может быть обнаружен"); Graphics2d Brush* @param Текст текст печати* @param x Печать отправленная точка x x координата* @param y print prently point y координата* @param linewidth ширина* @param lineheight height* @retun = graphics2d.getfontmetrics (); if (fontmetrics.stringwidth (text) <linewidth) {graphics2d.drawstring (text, x, y); return y;} else {char [] chars = text.tochararray (); int charswidth = 0; stringbuffer sb = new StringBuffer (); i ++) {if ((charswidth + fontmetrics.charwidth (chars [i]))> linewidth) {graphics2d.drawstring (sb.tostring (), 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) {graphics2d. y); y = y + lineheight;} return y - lineheight;}}}Результаты работы:
Предварительный просмотр эффекта:
Суммировать
Проще говоря, это написать программу Java, сохранить результат вывода как файл формата «*.xps» и вывести ее на принтер, что очень просто. Надеюсь, это будет полезно для всех. Если у вас есть какие -либо вопросы, пожалуйста, оставьте сообщение и укажите его. Спасибо, друзья, за вашу поддержку на этом сайте.