java实现条码打印机打印图片(USB)

客户的电脑访问系统实现打印的功能(打印机是USB没网口),在要打印的电脑要额外的程序

1.根据连接访问服务器,操作系统点击打印标签按钮

java实现条码打印机打印图片(USB)_第1张图片

2.点击打印标签的js代码

//打印标签
function printTag(){
	
	var ids = [];
	var rows = $("#main .selected");
	var length = rows.length;
	if(!length) {
		top.layer.msg("请选择数据");
		return false;
	}
	$.each(rows,function(i,v){
		var id = $(v).find("input").val();
		ids.push(id);
	})
	$.ajax({
		type: 'post',
		url: ctx + "/experiment/plasma/FormsampleReceiveEx/givePrintOrder.action",
		data: {
			ids: ids
		},
		success: function(data){
			var data = JSON.parse(data);
			if(data.success){
				var sampleCode = data.sampleCode;
				var sampleType = data.sampleType;
				var illType = data.illType;
                //访问本地,打开一个窗口,然后关闭
				window.open("http://localhost:8090/Printer/print?sampleCode="+sampleCode+"&sampleType="+sampleType+"&illType="+illType).close();
			}
		}
	})
}

3.将想要打印的数据拼接到链接后面(注意get请求的长度,我的是足够了),然后访问了本地程序的链接,本地程序是将拿到的数据转化为图片然后在进行打印操作的,图片为每个字段显示一行,下面为打印本地程序的代码,一个servlet(注释很重要)

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String sampleCode = request.getParameter("sampleCode");
		String sampleType = request.getParameter("sampleType"); 
		String illType = request.getParameter("illType"); 
		sampleCode = new String(sampleCode.getBytes("ISO-8859-1"),"utf-8");
		sampleType = new String(sampleType.getBytes("ISO-8859-1"),"utf-8");
		illType = new String(illType.getBytes("ISO-8859-1"),"utf-8");
		String[] sampleCodes = sampleCode.split(",");
		String[] sampleTypes = sampleType.split(",");
		String[] illTypes = illType.split(",");
		int length = sampleCodes.length;
		for (int i = 0; i < length; i++) {
			String sc = sampleCodes[i];
			String st = sampleTypes[i];
			String it = illTypes[i];
			String[]verifyCodes = new String[] {sc, st, it};
			//生成图片路径参数:(图片的内容,图片的长,图片的高,显示字体的大小)
			String filePath = WordToPictrue.TextToPic(verifyCodes, 500, 300, 80);
            //打印图片		
			printPicture(filePath);		
            //清除图片	
			clearPicture(filePath);
		}
	}
	
    //清除图片
	private void clearPicture(String filePath) {
		File file = new File(filePath);
		if(file.exists()) {
			file.delete();
		}
	}

    //打印图片
	private void printPicture(String filePath) {
		File file = new File(filePath);
		if(file.exists()) {
			FileInputStream textStream = null;
			try {
				textStream = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			if(textStream!=null) {
				// 指定打印输出格式
	            DocFlavor flavor = DocFlavor.INPUT_STREAM.PNG;//SERVICE_FORMATTED.PRINTABLE
	            // 定位默认的打印服务
	            PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
	            // 创建打印作业
	            DocPrintJob job = printService.createPrintJob();
	            // 设置打印属性
	            PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
	            pras.add(OrientationRequested.PORTRAIT);
	            pras.add(PrintQuality.HIGH);
	            pras.add(Chromaticity.MONOCHROME);
	            DocAttributeSet das = new HashDocAttributeSet();
	            // 指定打印内容
	            Doc doc = new SimpleDoc(textStream, flavor, das);
	            // 不显示打印对话框,直接进行打印工作
	            try {
	                job.print(doc, pras); // 进行每一页的具体打印操作
	            } catch (PrintException pe) {
	                pe.printStackTrace();
	            }
			}else {
				// 如果打印内容为空时,提示用户打印将取消
	            JOptionPane.showConfirmDialog(null,
	                    "Sorry, Printer Job is Empty, Print Cancelled!",
	                    "Empty", JOptionPane.DEFAULT_OPTION,
	                    JOptionPane.WARNING_MESSAGE);
			}
		}
	}

4,将文字转换为图片的方法(注释很重要)

public class WordToPictrue {
	 
		public static int getLength(String text) {
			int length = 0;
			for (int i = 0; i < text.length(); i++) {
				if (new String(text.charAt(i) + "").getBytes().length > 1) {
					length += 2;
				} else {
					length += 1;
				}
			}
			return length / 2;
		}
	 
		public static String TextToPic(String []verifyCodes, int width, int height,int fontSize) {
			try {
				String filepath = "D:/Printer/" + getDate() + ".png";
				File file = new File(filepath);
				if(!file.exists()) {
					file.mkdirs();
				}
				Font font = new Font("楷体", Font.BOLD, fontSize);
				FontMetrics fm = sun.font.FontDesignMetrics.getMetrics(font);
				BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
				Graphics2D g2 = (Graphics2D) bi.getGraphics();
				g2.setBackground(null);
				g2.clearRect(0, 0, width, height);
				g2.setFont(font);
				g2.setPaint(Color.BLACK);
				g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,0.3f));
				g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		        int h = fm.getHeight();
		        for (int i = 0; i < verifyCodes.length; i++) {
//如果你显示图片中的文字缺失了,可以加大第三个参数,就是加大了图片中文字与上边距的距离
		            g2.drawString(verifyCodes[i], 0, i * h + 70);
		        }
				g2.dispose();
				ImageIO.write(bi, "png", file);
				return filepath;
	 
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "";
		}
	 
		public static String getDate() {
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
			return formatter.format(new Date());
		}
	 
}

5.将这个servlet放在tomcat下,设置开机自启动,就不用去手动启动了

6.设置打印机,安装对应的打印机驱动,设置为默认,设置打印的纸张大小

java实现条码打印机打印图片(USB)_第2张图片

7.打印成功,样例,看着模糊可以设置图形的打印算法,希望看到的能得到帮助,不足请告知,谢谢

你可能感兴趣的:(java实现条码打印机打印图片(USB))