版權所有 http://www.cnblogs.com/yzssoft/p/8991971.html
做這個的例子太少,我把我做的示例亮出來
一.先說說需要的版本
1.我用的瀏覽器只有ie:
火狐只支持52版本以下,並且是java7、java8。chrome不支持
2.applet客戶端打印,需要java6:
親自測試,java6需要一些提示是否運行,等都同意后,打印時不用再提示。
在java7、8,我自己測試控制面板里面沒有低級,只有高級和超高級,不管什么時候打印,它都會提示是否同意
所以,我最終還是選擇了在applet里放入jre6
二.applet的打印代碼
1.html,在ie下才可運行
因為執行的時候,需要檢查有沒有jre6、請求/接受路徑、一些傳遞的參數,運行的class、需要的jar,代碼如下:
function is_ie(json, print_type) { //){ //項目的根路徑 var req_path = "http://localhost:8080"; //打印機名 var print_name = "Deli DL-888C"; var str = "JRPrinterApplet"; var archive = 'jbarcodebean-1.2.0.jar,json-20160810.jar,print.jar'; var codebase = '/applets' var file = '/applets/jre-6u45-windows-i586.exe'; var scriptable = false; var type = 'application/x-java-applet;version=1.6.0'; var clsid = ""; if (isFamilyVersionSupported()) { clsid = "clsid:CAFEEFAC-0016-0000-FFFF-ABCDEFFEDCBA"; } else { clsid = "clsid:CAFEEFAC-0016-0000-0008-ABCDEFFEDCBA"; } var write = '' + //'<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width = "0" height = "0" codebase="'+file+'" mayscript>' + '<object classid="' + clsid + '" width = "0" height = "0" codebase="' + file + '" mayscript>' + '<param name = "code" value = "' + str + '.class" >' + '<param name = "codebase" value = "' + codebase + '" >' + '<param name = "archive" value = "' + archive + '" >' + '<param name="type" value="' + type + '">' + '<param name="scriptable" value="' + scriptable + '">' + '<param name = "print_type" value ="' + print_type + '">' + '<param name = "print_name" value ="' + print_name + '">' + '<param name = "req_path" value ="' + req_path + '">' + '<param name = "json" value =\'' + json + '\'>' + '<comment>' + '<embed type="' + type + '" code="' + str + '.class" java_codebase="' + codebase + '" archive="' + archive + '" scriptable=' + scriptable + ' pluginspage="' + file + '" >' + '<noembed></noembed>' + '</embed>' + '</comment>' + '</object>'; $("#objectDiv").html(write) if(print_type=='login_test'){ } }
2.jre接受請求
需要的文件
(1)JRPrinterApplet.java,太多了,大家慢慢看吧,應該能理解
import net.sourceforge.jbarcodebean.JBarcodeBean; import net.sourceforge.jbarcodebean.model.Code39; import net.sourceforge.jbarcodebean.model.Ean13; import org.json.JSONArray; import org.json.JSONObject; import javax.print.PrintService; import javax.print.PrintServiceLookup; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.print.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by Administrator on 2018/4/29. */ public class JRPrinterApplet extends JApplet implements Printable { JSONObject jsonObject=new JSONObject(); private int imageWidth = 300; //圖片的寬度 @Override public void init() { String req_path=this.getParameter("req_path"); String print_type=this.getParameter("print_type"); String print_name=this.getParameter("print_name"); String jsonStr=this.getParameter("json"); //鏈接測速 if(print_type.equals("login_test")){ System.out.println("****連接測試"); String get=urlGet(req_path+"/print/print_error?type=login_test"); System.out.println(get); return; }else if(print_type.equals("print")){ System.out.println("****連接打印"); jsonObject=new JSONObject(jsonStr); String id=String.valueOf(jsonObject.get("id")); System.out.println(print_name+" "+req_path+" "+id+" "+print_type+"\n"+jsonStr); Book book = new Book(); // 設置成豎打 PageFormat pf = new PageFormat(); pf.setOrientation(PageFormat.PORTRAIT); // LANDSCAPE表示豎打;PORTRAIT表示橫打;REVERSE_LANDSCAPE表示打印空白 // 通過Paper設置頁面的空白邊距和可打印區域。必須與實際打印紙張大小相符。 Paper p = new Paper(); p.setSize(imageWidth, 300); // 紙張大小(590, 840)表示A4紙 p.setImageableArea(0, 0, imageWidth, 300); // A4(595 X842)設置打印區域,其實0,0應該是72,72 // ,因為A4紙的默認X,Y邊距是72 pf.setPaper(p); // 把 PageFormat 和 Printable 添加到書中,組成一個頁面 book.append(this, pf); // 獲取打印服務對象 PrinterJob.lookupPrintServices(); PrinterJob job = PrinterJob.getPrinterJob(); // 設置打印類 job.setPageable(book); PrintService[] pss = PrintServiceLookup.lookupPrintServices(null,null); //PrintService ps=null; boolean have_ps=false; for(PrintService printService:pss){ System.out.println("****找到打印機:"+printService.toString()); if(printService.toString().contains(print_name)){ try { System.out.println("----找到對應打印機:"+printService.toString()); job.setPrintService(printService); have_ps=true; } catch (PrinterException e) { String services = urlGet(req_path + "/print/print_error?type=Doc_error&id=" + id + "&msg=" + e); System.out.println(services); e.printStackTrace(); return; } } } if(!have_ps){ String var19 = urlGet(req_path + "/print/print_error?type=print_no_find&id=" + id); System.out.println(var19); }else{ try { // 可以用printDialog顯示打印對話框,在用戶確認后打印;也可以直接打印 /*boolean a=job.printDialog(); if(a) { job.print(); }*/ String get=urlGet(req_path + "/print/print_error?type=print_ok&id=" + id); System.out.println(get); job.print(); } catch (PrinterException e) { String get = urlGet(req_path + "/print/print_error?type=print_is_error&id=" + id + "&msg=" + e); System.out.println(get); e.printStackTrace(); } } } } public int print(Graphics gra, PageFormat pf, int pageIndex) throws PrinterException { Component c = null; Graphics2D g2 = (Graphics2D) gra; double x = pf.getImageableX(); double y = pf.getImageableY(); switch (pageIndex) { case 0: g2.drawImage(graphicsGeneration(jsonObject), (int) x, (int) y, c); return PAGE_EXISTS; default: return NO_SUCH_PAGE; } } public BufferedImage graphicsGeneration(JSONObject jsonObject) { String id=String.valueOf(jsonObject.get("id")); String name=String.valueOf(jsonObject.get("name")); JSONArray array=jsonObject.getJSONArray("list"); int title_h=20; int left_long=10; int row=1; int i; int imageHeight=title_h*(row+7)+80; BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); //設置圖片的背景色 Graphics2D main = image.createGraphics(); main.setColor(Color.white); main.fillRect(0, 0, imageWidth, imageHeight); //***********************頁面頭部 Graphics g = image.createGraphics(); g.fillRect(0, 0, imageWidth, title_h); g.setColor(Color.white); Font font = new Font("宋體", Font.BOLD, 14); g.setFont(font); g.setColor(Color.BLACK); g.drawString("***道口義興張祥記燒雞老鋪***", 50, title_h*row+++3); //其他內容 font = new Font("宋體", Font.PLAIN, 12); g.setFont(font); g.drawString("單號:"+id,left_long,title_h*row); g.drawString("時間:"+new SimpleDateFormat("MM月dd日 HH:mm:ss").format(new Date()),imageWidth/2,title_h*row++); g.drawString("收貨人:"+name,left_long,title_h*row++); g.drawLine(5,65,295,65); for(i=0;i<array.length();i++){ JSONObject o= (JSONObject) array.get(i); g.drawString((i+1)+".",left_long,title_h*row); g.drawString(o.get("name")+" x"+o.get("num"),left_long+15,title_h*row); String unit=""; if(o.get("unit")!=null&&!o.get("unit").equals("")){ unit="/"+o.get("unit"); } g.drawString(o.get("money")+unit,240,title_h*row); row++; } //生成條維碼 JBarcodeBean jBarcodeBean = new JBarcodeBean(); // 條形碼類型 //jBarcodeBean.setCodeType(new Ean13()); jBarcodeBean.setCodeType(new Code39()); // 在條形碼下面顯示文字 jBarcodeBean.setLabelPosition(JBarcodeBean.LABEL_BOTTOM); jBarcodeBean.setCode(id); jBarcodeBean.setBarcodeHeight(50); //條維碼 BufferedImage tiao_wei_ma = new BufferedImage(300, 80, BufferedImage.TYPE_INT_RGB); tiao_wei_ma = jBarcodeBean.draw(tiao_wei_ma); //***********************插入圖片 Graphics mainPic = image.getGraphics(); if(tiao_wei_ma!=null){ mainPic.drawImage(tiao_wei_ma,0,title_h*(row-1),null); mainPic.dispose(); } //createImage("F:\\temp/hehe.jpg",image); return image; } /** * 向指定URL發送GET方法的請求 * */ public static String urlGet(String url) { BufferedReader in = null; try { URL realUrl = new URL(url); // 打開和URL之間的連接 URLConnection connection = realUrl.openConnection(); // 設置通用的請求屬性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); // 建立實際的連接 connection.connect(); // 定義 BufferedReader輸入流來讀取URL的響應 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = in.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { System.out.println(e); } // 使用finally塊來關閉輸入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return null; } }
一定要用java6生成class,要不然applet的java6不支持
(1).將class生成jar,我命名print.jar
(2).jar -cvf print.jar *.class (生成jar包),放入applets
5.簽名
1.創建一個證書
keytool -genkey -validity 1800 -keystore applet.store -alias applet
2.導出證書文件
keytool -export -keystore applet.store -alias applet -file applet.cer
3.對jar包進行簽名
jarsigner -keystore applet.store jbarcodebean-1.2.0.jar applet
jarsigner -keystore applet.store json-20160810.jar applet
jarsigner -keystore applet.store print.jar applet
6.將上面圖的那些文件放入applet