关于web页面JApplet打印小票

版权所有

做这个的例子太少,我把我做的示例亮出来

一.先说说需要的版本

  1.我用的浏览器只有ie:

    火狐只支持52版本以下,并且是java7、java8。chrome不支持 

  2.applet客户端打印,需要java6:

    亲自测试,java6需要一些提示是否运行,等都同意后,打印时不用再提示。

           在java7、8,我自己测试控制面板里面没有低级,只有高级和超高级,不管什么时候打印,它都会提示是否同意

    所以,我最终还是选择了在applet里放入jre6

二.applet的打印代码

  1.html,在ie下才可运行

扫描二维码关注公众号,回复: 110832 查看本文章

  因为执行的时候,需要检查有没有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

猜你喜欢

转载自www.cnblogs.com/yzssoft/p/8991971.html
今日推荐