1.后台控制打印代码

/**
• @author Stone
 */
 public class GMMSPrinter implements Printable {
private static final Logger LOGGER = LoggerFactory.getLogger(GMMSPrinter.class);
/**• 客户名称
/
 private String customer;
 /*• 项目名称
/
 private String application;
 /*• 成品名称
/
 private String production;
 /*• 楼层编号
/
 private String floorNumber;
 /*• 订单序号
/
 private String orderNumber;
 /*• 长度
/
 private double length;
 /*• 宽度
/
 private double width;
 /*• 流程卡号
/
 private String apartId;
 /*• 片标记
/
 private String pieceSign;
 /*• 明细备注
/
 private String remark;
 /*• 生产线
 */
 private String line;public GMMSPrinter(String customer, String application, String production, String floorNumber, String orderNumber,
 double length, double width, String apartId, String pieceSign, String remark, String line) {
 super();
 this.customer = customer;
 this.application = application;
 this.production = production;
 this.floorNumber = floorNumber;
 this.orderNumber = orderNumber;
 this.length = length;
 this.width = width;
 this.apartId = apartId;
 this.pieceSign = pieceSign;
 this.remark = remark;
 this.line = line;
 }@Override
 public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
Graphics2D g2 = (Graphics2D) graphics;
 
 //设置打印的颜色
 g2.setPaint(Color.black);
 
 //转换坐标,确定打印边界
 g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
 
 String lengthStr = String.valueOf(length).substring(0, String.valueOf(length).indexOf("."));
 String widthStr = String.valueOf(width).substring(0, String.valueOf(width).indexOf("."));
 
 //设置打印的字体
 Font font = new Font("黑体", Font.BOLD, 11);  
 g2.setFont(font);
 //获得字体的高度
 float height=font.getSize2D();
 //得到第一行打印数据
 g2.drawString(customer, 30, 20);
 
 g2.setFont(font);
 //得到第一行右边数据
 g2.drawString(application, 92, 20);
 
 g2.setFont(font);
 //得到第二行数据
 g2.drawString(production, 4, 25+height);
 
 Font font1 = new Font("黑体", Font.BOLD, 13);  
 g2.setFont(font1);
 g2.drawString(floorNumber, 15, 35+height+height);
 
 g2.setFont(font1);
 float height1=font.getSize2D();
 g2.drawString(orderNumber+")"+lengthStr+"*"+widthStr, 24, 45+height*3);
 
 g2.setFont(font);
 g2.drawString(apartId+"/"+pieceSign+" "+remark, 15, 50+height*3+height1);
 
 return Printable.PAGE_EXISTS;
}
/**
• 打印
• @throws PrinterException
 */
 public void doPrint() {
 LOGGER.debug("> Start doPrint");
//收到光电信号打印机执行打印
 PrinterJob printerJob = PrinterJob.getPrinterJob();
 Book book=new Book();
//设置成竖打
 PageFormat pageFormat=new PageFormat();
 pageFormat.setOrientation(PageFormat.PORTRAIT);
//设置页面的空白边距和可打印区域
 Paper paper=new Paper();
 paper.setSize(220, 115);
 //设置打印区域
 paper.setImageableArea(0, 0, 220,115);
 pageFormat.setPaper(paper);
//把 PageFormat和 Printable 添加到书中
 book.append(new GMMSPrinter(customer, application, production, floorNumber, orderNumber, length, width, apartId, pieceSign, remark, line), pageFormat);
 printerJob.setPageable(book);
 HashAttributeSet hs = new HashAttributeSet();
 String printerName=“ZDesigner ZT410-300dpi ZPL”;
 //将当前打印机添加到打印服务
 hs.add(new PrinterName(printerName,null));
 PrintService [] pss = PrintServiceLookup.lookupPrintServices(null, hs);
 LOGGER.debug(“打印机的个数是:” + pss.length);
try {
 printerJob.print();
 }
 catch (PrinterException e) {
 e.printStackTrace();
 }
LOGGER.debug("> End doPrint");
 }
 }

2.前端控制打印机打印
<%@ page language=“java” contentType=“text/html; charset=UTF-8” pageEncoding=“UTF-8” isELIgnored=“false”%>


首页

.PageNext{page-break-after: always;}

<%-- --%>



起始编号:
结束编号:

    



<%--








王思睿


--%> 
<%@ page language=“java” contentType=“text/html; charset=utf-8” pageEncoding=“utf-8” isELIgnored=“false”%>
 
Insert title here
.PageNext{page-break-after: always;}
<%-- --%>
package servlet;
import java.io.IOException;
 import java.io.PrintWriter;
 import java.lang.reflect.Method;
 import java.util.List;import javax.accessibility.AccessibleRelation;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;import org.hibernate.jpa.criteria.Renderable;
import com.google.gson.Gson;
 import com.google.gson.JsonArray;import dao.BaseDao;
 import model.Exem;
 import net.sf.json.JSONArray;
 import print.BarcodeUtil;
 import util.GridDataModel;public class Barcode extends HttpServlet {
 private static final long serialVersionUID = 1L;@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// String servletPath = req.getServletPath();
 // String actionName = servletPath.substring(1, servletPath.indexOf("."));String actionName = req.getParameter("method");
	try {
		Method method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class);
		method.invoke(this, req, resp);
	} catch (Exception e) {
			e.printStackTrace();
	} 
}

public void barcode(HttpServletRequest request, HttpServletResponse response)throws ServletException{
	String code = request.getParameter("code");
	BarcodeUtil.encode(code, response);
}

public void getData(HttpServletRequest request, HttpServletResponse response)throws ServletException{
	String start = request.getParameter("start");
	String end = request.getParameter("end");
	System.out.println(start + ", " + end);// if(“1”.equals(start)){
 // start = “2”;
 // }BaseDao<Exem> dao = new BaseDao<Exem>();
	String hql = "from Exem where id between ? and ?";
	List<Exem> list = dao.getList(hql, Integer.parseInt(start), Integer.parseInt(end));// JSONArray array = JSONArray.fromObject(list);
 // String result = “{“success”:true,“items”:” + array.toString() + “}”;
 // render(response, result);// String sql = "from Exem where id < " + Integer.parseInt(count);
 // List<Object[]> list = dao.queryForList(sql);Gson gson = new Gson();
	String result = gson.toJson(new GridDataModel<Exem>(list));// String result = gson.toJson(list);
 render(response, result);
 }private void render(HttpServletResponse response, String result){
	//设置为text/html,返回的是json字符串,设置为application/json,获取的是对象
	response.setContentType("text/html; utf-8");
	// Http 1.0 header
	response.setDateHeader("Expires", 1L);
	response.addHeader("Pragma", "no-cache");
	
	// Http 1.1 header
	response.setHeader("Cache-Control", "no-cache, no-store, max-age=0");
	
	//设置中文编码
	response.setCharacterEncoding("UTF-8");
	response.setContentType("UTF-8");
	
	try {
		response.getWriter().write(result);
		response.getWriter().flush();
	} catch (IOException e) {
		throw new RuntimeException(e.getMessage(), e);
	}
}// private void render(HttpServletResponse response, String result){
 // response.setContentType(“text/html; charset=utf-8”);
 // response.setHeader(“Cache-Control”, “no-cache”);
 // PrintWriter out = null;
 // try {
 // out = response.getWriter();
 // out.write(result);
 // } catch (Exception e) {
 // e.printStackTrace();
 // }
 // }
 }import java.awt.Font;
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;import javax.imageio.ImageIO;
 import javax.imageio.stream.ImageOutputStream;
 import javax.servlet.http.HttpServletResponse;import net.sourceforge.jbarcodebean.JBarcodeBean;
 import net.sourceforge.jbarcodebean.model.Code128;
 public class BarcodeUtil {private static final int IMAGE_WIDTH = 160;
private static final int IMAGE_HEIGHT = 34;
private static final int BARCODE_HEIGHT = 34;		
private static final int FONT_SIZE = 12;			
private static final String FONT_FAMILY = "Consolas";	

public static void encode(String str, HttpServletResponse response) {
	
	OutputStream os = null;
	InputStream fis = null;
	ByteArrayOutputStream bs = null;
	ImageOutputStream iout = null;
	
	try {
		JBarcodeBean bean = new JBarcodeBean();
		bean.setCodeType(new Code128());				
		bean.setCode(str);								
		bean.setLabelPosition(JBarcodeBean.LABEL_BOTTOM);
		bean.setShowText(false);							//不显示条码字符
		bean.setFont(new Font(FONT_FAMILY, Font.PLAIN,FONT_SIZE));
		bean.setBarcodeHeight(BARCODE_HEIGHT); 				
		bean.setNarrowestBarWidth(2);
		BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
		image = bean.draw(image);// BarCode barCode = new BarCode();
 // barCode.code = str;
 // barCode.barType = BarCode.CODE128;
 // barCode.resolution = 38;
 // barCode.setBarHeightCM(1.1);
 // barCode.setShowText(false);
 // barCode.setNarrowToWideRatio(2);
 // 
 // 
 // BufferedImage image = new BufferedImage(IMAGE_WIDTH, IMAGE_HEIGHT, BufferedImage.TYPE_INT_RGB);
 // Graphics2D g2 = image.createGraphics();
 // barCode.paint(g2);
 // barCode.invalidate();
 // System.out.println(barCode.getWidth() + ". " + barCode.getHeight());
 // g2.dispose();// JBarcode barcode = JBarcodeFactory.getInstance().createCode128();
 // barcode.setBarHeight(BARCODE_HEIGHT);
 // barcode.setShowText(false);
 // barcode.setWideRatio(20);
 // 
 // BufferedImage image = barcode.createBarcode(str);
 // 
 os = response.getOutputStream();
 bs = new ByteArrayOutputStream();
 iout = ImageIO.createImageOutputStream(bs);
 ImageIO.write(image, “jpg”, iout);
 fis = new ByteArrayInputStream(bs.toByteArray());
//缂撳啿鍖�
		byte[] b = new byte[1024];			
		int i = 0;
		while ((i = fis.read(b)) > 0){
			os.write(b, 0, i);
		}
		os.flush();
	} catch (Exception localException) {
		localException.printStackTrace();
	}finally{
		try{
			if(iout != null) iout.close();
			if(bs != null) bs.close();
			if (fis != null) fis.close();
			if (os != null) os.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}

}

java 选择打印机 java打印机打印_ide