java操作打印机demo

package com.example.demo.easyexcel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.bean.LanguageTable;
import com.example.demo.server.CommonService;
import com.example.demo.uitils.ApplicationContextHolder;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.print.*;
import javax.print.attribute.Attribute;
import javax.print.attribute.AttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import java.awt.*;
import java.awt.print.*;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * 直接用map接收数据
 *
 * @author pengxin
 */
public class test  {
    protected static final String DIAN_MING = "java";
    public static void main(String[] args) {

//        String st = "\"语音邮件发件人 \"";
//        System.out.println(st.replaceAll("\"","").replaceAll(" ",""));
//        List<Integer> list = new ArrayList<>();
//        list.add(1);
//        list.add(3);
//        list.add(8);
//        list.add(3);
//        list.add(8);
//        list.add(19);
//        list.add(3);
//        list.add(90);
//        list.add(14);
//        Collections.sort(list);
//        int tag =0;
//        for (int i=0;i<list.size();i++){
//            System.out.println(i-++tag);
//        }

        /*
         * 打印格式
         */
        PageFormat pageFormat = new PageFormat();
        // 设置打印起点从左上角开始,从左到右,从上到下打印
        pageFormat.setOrientation(PageFormat.PORTRAIT);
        /*
         * 打印页面格式设置
         */
        Paper paper = new Paper();
        // 设置打印宽度(固定,和具体的打印机有关)和高度(跟实际打印内容的多少有关)
        paper.setSize(140, 450);
        // 设置打印区域 打印起点坐标、打印的宽度和高度
        paper.setImageableArea(0, 0, 135, 450);
//          paper.setImageableArea(0, 0, 135, 450);
        pageFormat.setPaper(paper);
        // 创建打印文档
        Book book = new Book();
        book.append(new Printable() {
            @Override
            public int print(Graphics graphics, PageFormat pageFormat,
                             int pageIndex) throws PrinterException {
                if (pageIndex > 0) {
                    return NO_SUCH_PAGE;
                }
                Graphics2D graphics2D = (Graphics2D) graphics;
                Font font = new Font("宋体", Font.PLAIN, 5);
                graphics2D.setFont(font);
                drawString(graphics2D, "//",
                        10, 17, 119, 8);
                font = new Font("宋体", Font.PLAIN, 7);
                graphics2D.setFont(font);
                int yIndex = 30;
                int lineHeight = 10;
                int lineWidth = 120;
                Color defaultColor = graphics2D.getColor();
                Color grey = new Color(145, 145, 145);
                // 收货信息
                // yIndex = drawString(graphics2D,
                // "发件人:"+DIAN_MING+"(微信:yichenbaby0)", 10, yIndex,
                // lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "收货人:", 10,
                        yIndex, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "收货人备注信息:" , 10, yIndex + lineHeight,
                        lineWidth, lineHeight);
                // 收货信息边框
                Stroke stroke = new BasicStroke(0.5f, BasicStroke.CAP_BUTT,
                        BasicStroke.JOIN_BEVEL, 0, new float[] { 4, 4 }, 0);
                graphics2D.setStroke(stroke);
                graphics2D.drawRect(5, 10, 129, yIndex);
                // 商品名称
                lineWidth = 129;
                lineHeight = 8;
                graphics2D.setFont(new Font("宋体", Font.BOLD, 8));
                graphics2D.setColor(defaultColor);
                yIndex = drawString(graphics2D, DIAN_MING, 5, yIndex
                        + lineHeight + 20, lineWidth, 12);
                graphics2D.setFont(new Font("宋体", Font.PLAIN, 6));
                graphics2D.setColor(grey);
//                  yIndex = drawString(graphics2D, "操作员:金豆        "
//                          + getCurrDate(), 5, yIndex + lineHeight + 2,
//                          lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "时间:"
                                + getCurrDate(), 5, yIndex + lineHeight + 2,
                        lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "商品名", 5, yIndex
                        + lineHeight * 2 - 5, lineWidth, lineHeight);
                // yIndex = drawString(graphics2D, "尺码", (lineWidth/10)*4,
                // yIndex, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "单价", (lineWidth / 10) * 8,
                        yIndex, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "数量",
                        (lineWidth / 10) * 10, yIndex, lineWidth,
                        lineHeight);

                //总合计价格
                int total = 0;
                double totalPrice = 0;
                graphics2D.setFont(new Font("宋体", Font.PLAIN, 7));
                //商品名称
                yIndex = drawString(graphics2D, "num", 5,
                        yIndex + 15, (lineWidth / 10) * 7, 10);
                graphics2D.setFont(new Font("宋体", Font.PLAIN, 6));
                graphics2D.setColor(grey);
//                      yIndex = drawString(graphics2D, "尺码:" + "100M", 5,
//                              yIndex + 11, lineWidth, lineHeight);// 尺码
                //单价
                yIndex = drawString(graphics2D, "11",
                        (lineWidth / 10) * 8, yIndex, lineWidth,
                        lineHeight);
                //数量
                yIndex = drawString(graphics2D, "11",
                        (lineWidth / 10) * 10, yIndex, lineWidth,
                        lineHeight);
                graphics2D.setFont(new Font("宋体", Font.PLAIN, 7));
                yIndex = yIndex + 2;
                graphics2D.drawLine(5, yIndex, 5 + lineWidth, yIndex);

                graphics2D.setColor(defaultColor);
                // yIndex = drawString(graphics2D, "会员名称:小清新", 5, yIndex +
                // lineHeight * 2, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "总  数:"+total, 5, yIndex
                        + lineHeight, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "总  计:"+totalPrice, 5, yIndex
                        + lineHeight, lineWidth, lineHeight);
//                  yIndex = drawString(graphics2D, "收  款:100.00", 5, yIndex
//                          + lineHeight, lineWidth, lineHeight);
//                  yIndex = drawString(graphics2D, "找  零:44.70", 5, yIndex
//                          + lineHeight, lineWidth, lineHeight);
                graphics2D.setFont(new Font("宋体", Font.PLAIN, 6));
                graphics2D.setColor(grey);
//                  yIndex = drawString(graphics2D, "微信:"+orderVo.getWxno(), 5, yIndex
//                          + lineHeight * 2, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "微信:", 5, yIndex
                        + lineHeight * 2, lineWidth, lineHeight);
//                  yIndex = drawString(graphics2D, "地址:" + orderVo.getAddress(), 5,
//                          yIndex + lineHeight, lineWidth, lineHeight);
                yIndex = drawString(graphics2D, "地址:", 5,
                        yIndex + lineHeight, lineWidth, lineHeight);
                yIndex = yIndex + 20;
                graphics2D.drawLine(0, yIndex, 140, yIndex);
                return PAGE_EXISTS;
            }

            private String getCurrDate() {
                Date currDate = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");
                return sdf.format(currDate);
            }
        }, pageFormat);

        //设置打印属性 构造一个新的空打印请求属性集。
        PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
        //设置打印数据的格式        DocFlavor.BYTE_ARRAY.PNG     MIME 类型 = "image/png",打印数据表示形式类名 = "[B"(byte 数组)的 DocFlavor。
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PNG;
        //创建打印数据
//        Doc myDoc = new SimpleDoc(new File(""), flavor, null);
        //查找所有符合条件的打印服务                         lookupPrintServices(flavor, pras);查找能够打印指定 DocFlavor 的 PrintService。
        PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, pras);
        for (PrintService printService1:printService){
            System.out.println("printService1="+printService1.getName());
            if (printService1.getName().equals("HP LaserJet 5200 Series PCL 5")){
                PrinterJob job=PrinterJob.getPrinterJob();
                try {
                    job.setPrintService(printService1);
                    job.setPageable(book);
                    job.print();
                } catch (PrinterException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 字符串输出
     *
     * @param graphics2D
     *            画笔
     * @param text
     *            打印文本
     * @param x
     *            打印起点 x 坐标
     * @param y
     *            打印起点 y 坐标
     * @param lineWidth
     *            行宽
     * @param lineHeight
     *            行高
     * @return 返回终点 y 坐标
     */
    private static int drawString(Graphics2D graphics2D, String text, int x,
                                  int y, int lineWidth, int lineHeight) {
        FontMetrics fontMetrics = 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();
            for (int i = 0; i < chars.length; 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.drawString(sb.toString(), x, y);
                y = y + lineHeight;
            }
            return y - lineHeight;
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值