Java调用打印机打印(远程、本地皆可用)

Java调用打印机打印(远程、本地皆可用)

  • 背景
  • 准备
  • MAVEN环境
  • 步骤
    • 获取PrinterJob
    • 设置PrinterJob纸张样式
    • 打印PDF

背景

开发个Java项目需要远程调用共享打印机打印

准备

环境 内容
JDK 1.8.0_212
开发工具 IDEA
打印机端和服务器端配置 配置参考链接

MAVEN环境

一般打印都生成PDF然后打印,PDF常用API有两个,pdfbox和itextpdf,依赖如下
pdfbox依赖

		<dependency>
            <groupId>org.apache.pdfboxgroupId>
            <artifactId>pdfboxartifactId>
            <version>2.0.21version>
        dependency>

itextpdf依赖

		<dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itextpdfartifactId>
            <version>5.5.13version>
        dependency>
        <dependency>
            <groupId>com.itextpdfgroupId>
            <artifactId>itext-asianartifactId>
            <version>5.2.0version>
        dependency>

步骤

获取PrinterJob

一般都用PrinterJob.lookupPrintServices()来获取本地配置的打印机列表

    public static PrinterJob getPrintServiceByName(String printerName) throws Exception{
        PrinterJob job = PrinterJob.getPrinterJob();
        // 遍历查询打印机名称
        boolean flag = false;
        for (PrintService ps : PrinterJob.lookupPrintServices()) {
            String psName = ps.toString();
            // 选用指定打印机,需要精确查询打印机就用equals,模糊查询用contains
            if (psName.contains(printerName)) {
                flag = true;
                job.setPrintService(ps);
                break;
            }
        }
        if(!flag){
            throw new RuntimeException("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
        }
        return job;
    }

设置PrinterJob纸张样式

    public static void setPageStyle(PDDocument document, PrinterJob job) {
        job.setPageable(new PDFPageable(document));
        Paper paper = new Paper();
        int width = 215;
        int height = 170;
        // 设置打印纸张大小
        paper.setSize(width,height); // 1/72 inch
        // 设置边距,单位是像素,10mm边距,对应 28px
        int marginLeft = 1;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        // 设置打印位置 坐标
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        // custom page format
        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        // override the page format
        Book book = new Book();
        // append all pages 设置一些属性 是否缩放 打印张数等
        book.append(new PDFPrintable(document, Scaling.ACTUAL_SIZE), pageFormat, 1);
        job.setPageable(book);
    }

打印PDF

	public static PDDocument printPdf(String pdfPath, String printerName) throws Exception {
        File file = new File(pdfPath);
        PDDocument document = PDDocument.load(file);
        PrinterJob job = getPrintServiceByName(printerName);
        setPageStyle(document, job);
        // 开始打印
        job.print();
        return document;
    }

你可能感兴趣的:(技术知识,开发实例)