JAVA实现服务器端查找指定打印机并且实现模板套打的功能

简介: JAVA实现服务器端查找指定打印机并且实现模板套打的功能,依据的需求是打印准考证,录取通知书或者奖状等

package com.example.demo;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import org.apache.commons.lang3.StringUtils;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.print.*;
import java.io.IOException;
import java.util.ArrayList;

public class PdfTaoDaPrinterDemo implements Printable{

    private static String printerName = "Microsoft Print to PDF";
    private String[] value = {"测试","信息与计算科学","数学物理学院","2023年9月1日","XX校区","2023","7","24","1234567890","1234567890"};

    private int[][] positions = {{70,220},{150,400},{300,400},{150,420},{300,420},{490,375},{530,375},{560,375},{560,100},{585,142}};
    public static void main(String []args) throws Exception {
        PrintService printService = getPrintService();
        if(printService==null){
            //无可用的打印机
            System.out.println("打印失败,未找到可用打印机,请检查。");
        }else{
            PdfTaoDaPrinterDemo pdfTaoDaPrinterDemo = new PdfTaoDaPrinterDemo();
            printReport(pdfTaoDaPrinterDemo,printService);
        }
    }

    public int print(Graphics g,PageFormat pf,int pageIndex){
        if(pageIndex>0){
            return Printable.NO_SUCH_PAGE;
        }

        Graphics2D g2d = (Graphics2D) g;
        for(int i=0;i<value.length;i++){
            String str = value[i];
            int temp[] = positions[i];
            int x = temp[0];
            int y = temp[1];
            if(i==0){
                Font font = new Font("微软雅黑",Font.PLAIN,16);
                g2d.setFont(font);
                g2d.drawString(str,x,y);
            }else if((i>=5 && i<=7)){
                Font font = new Font("宋体",Font.PLAIN,12);
                g2d.setFont(font);
                g2d.drawString(str,x,y);
            }else if(i>0 && i<5 && i!=2){
                Font font = new Font("宋体",Font.PLAIN,16);
                g2d.setFont(font);
                g2d.drawString(str,x,y);
            }else if(i==2){
                if(str.contains("(") || str.contains("(")){
                    Font font = new Font("宋体",Font.PLAIN,14);
                    g2d.setFont(font);
                    java.util.List<String> line_list = new ArrayList<String>();
                    if(str.contains("(")){
                        String preStr = str.substring(0,str.indexOf("("));
                        String affStr = str.substring(str.indexOf("(")+1);
                        line_list.add(preStr);
                        line_list.add(affStr);
                    }else if(str.contains("(")){
                        String preStr = str.substring(0,str.indexOf("("));
                        String affStr = str.substring(str.indexOf("("));
                        line_list.add(preStr);
                        line_list.add(affStr);
                    }
                    for(int j = 0;j<line_list.size();j++){
                        String line_str = line_list.get(j);
                        int strWidth = g2d.getFontMetrics().stringWidth(line_str);
                        int wordStartX=x+(+150 - strWidth) / 2;
                        g.drawString(line_str, wordStartX, y+(j-1)*14) ;//35为每行的高度
                    }
                }else {
                    Font font = new Font("宋体",Font.PLAIN,16);
                    g2d.setFont(font);
                    g2d.drawString(str, x, y);
                }
            } else if(i==8){
                BufferedImage logoImg = null;
                try {
                    logoImg = insertWords(getBarcode(str),str);
                    g2d.drawImage(logoImg, x, y, logoImg.getWidth(), logoImg.getHeight(), null);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(logoImg!=null){
                        logoImg.flush();
                    }
                }
            }

        }
        return Printable.PAGE_EXISTS;
    }

    private void setColorWhite(Graphics2D g2d){
        g2d.setColor(Color.WHITE);
        //填充整个屏幕
        g2d.fillRect(0,0,600,600);
        //设置笔刷
        g2d.setColor(Color.BLACK);
    }

    public BufferedImage insertWords(BufferedImage image, String words){
        // 新的图片,把带logo的二维码下面加上文字
        if (StringUtils.isNotEmpty(words)) {
            BufferedImage outImage = new BufferedImage(image.getWidth(), image.getHeight()+20, BufferedImage.TYPE_INT_RGB);

            Graphics2D g2d = outImage.createGraphics();
            setColorWhite(g2d);

            // 画条形码到新的面板
            g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 画文字到新的面板
            Color color=new Color(0, 0, 0);
            g2d.setColor(color);
            // 字体、字型、字号
            g2d.setFont(new Font("新宋体", Font.PLAIN, 10));
            //文字长度
            int strWidth = g2d.getFontMetrics().stringWidth(words);
            //总长度减去文字长度的一半  (居中显示)
            int wordStartX=(image.getWidth() - strWidth) / 2;
            int wordStartY=image.getHeight()+10;
            // 画文字
            g2d.drawString(words, wordStartX, wordStartY);
            g2d.dispose();
            outImage.flush();
            return outImage;
        }
        return null;
    }

    public BufferedImage getBarcode(String s) throws IOException {
        try {
            Code128Writer writer = new Code128Writer();
            BitMatrix bar = writer.encode(s, BarcodeFormat.CODE_128, 80, 50, null);
            return MatrixToImageWriter.toBufferedImage(bar);
        }
        catch (WriterException e){ throw new RuntimeException(e); }
    }
    private static void printReport(PdfTaoDaPrinterDemo pdfTaoDaModel, PrintService printService){
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        try {
            printerJob.setPrintService(printService);
            PageFormat pf = printerJob.defaultPage();
            Paper paper = pf.getPaper();
            double pageWidth = 496;
            double pageHeight = 765;
            paper.setSize(pageWidth,pageHeight);
            paper.setImageableArea(0,0,pageWidth,pageHeight);
            pf.setOrientation(PageFormat.LANDSCAPE);
            pf.setPaper(paper);
            printerJob.setPrintable(pdfTaoDaModel,pf);
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(new Copies(1)); //份数
            printerJob.print(aset);
        } catch (PrinterException e) {
            e.printStackTrace();
            System.out.println("PrinterException:"+e.getLocalizedMessage());
        }
    }

    private static PrintService getPrintService(){
        if (printerName != null) {
            // 查找并设置打印机
            //获得本台电脑连接的所有打印机
            PrintService[] printServices = PrinterJob.lookupPrintServices();
            if(printServices == null || printServices.length == 0) {
                System.out.println("打印失败,未找到可用打印机,请检查。");
                return null;
            }
            PrintService printService = null;
            //匹配指定打印机
            for (int i = 0;i < printServices.length; i++) {
                System.out.println(printServices[i].getName());
                if (printServices[i].getName().contains(printerName)) {
                    printService = printServices[i];
                }
            }
            if(printService!=null){
                return printService;
            }else{
                System.out.println("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                return null;
            }
        }
        return null;
    }

    public String[] getValue() {
        return value;
    }

    public void setValue(String[] value) {
        this.value = value;
    }

    public int[][] getPositions() {
        return positions;
    }

    public void setPositions(int[][] positions) {
        this.positions = positions;
    }
}
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.0.0</version>
</dependency>

printerName替换为实际的打印机名称,这里面需要服务器跟打印机网络互联,本例子是本机的Microsoft Print to PDF,即可导出为pdf。value是套打的内容,positions为套打的点位,主要是调整这三个地方,根据套打的模板去定位。字体颜色和大小可以修改print方法里的相应位置,也可以自己针对特定的位置调整,二维码采用的是zxing第三方库,引入相应的依赖以后,代码可以直接运行看到输出效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现服务器远程调用本地打印机,可以使用Java提供的远程方法调用(RMI)技术。以下是一些步骤: 1. 定义打印机接口Printer,其中包含打印方法print(String content)。 ```java public interface Printer extends java.rmi.Remote { public void print(String content) throws java.rmi.RemoteException; } ``` 2. 实现打印机类LocalPrinter,实现Printer接口,并实现打印方法。 ```java public class LocalPrinter extends java.rmi.server.UnicastRemoteObject implements Printer { public LocalPrinter() throws java.rmi.RemoteException { super(); } public void print(String content) throws java.rmi.RemoteException { System.out.println("Printing: " + content); // 在本地打印机打印 } } ``` 3. 创建服务器端程序,将LocalPrinter对象注册到RMI注册表中。 ```java public class PrinterServer { public static void main(String[] args) { try { Printer printer = new LocalPrinter(); java.rmi.registry.LocateRegistry.createRegistry(1099); java.rmi.Naming.rebind("//localhost/Printer", printer); System.out.println("Printer server ready."); } catch (Exception e) { System.err.println("Printer server exception: " + e.getMessage()); e.printStackTrace(); } } } ``` 4. 创建客户端程序,从RMI注册表中查找Printer对象,并调用其打印方法。 ```java public class PrinterClient { public static void main(String[] args) { try { Printer printer = (Printer) java.rmi.Naming.lookup("//localhost/Printer"); printer.print("Hello, world!"); } catch (Exception e) { System.err.println("Printer client exception: " + e.getMessage()); e.printStackTrace(); } } } ``` 5. 运行服务器端程序和客户端程序,即可实现服务器远程调用本地打印机
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ok060

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值