Java 实现打印功能

 一、依赖

     <dependency>
      <groupId>org.apache.pdfbox</groupId>
      <artifactId>pdfbox</artifactId>
      <version>2.0.8</version>
    </dependency>

 二、代码

      1、demo
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSize;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.Sides;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class PrintDemo {
    public static void main(String[] argv) throws Exception {

        // File file = new File("C:/Users/admin/Desktop/5446185be875e006f2f7a5a8c80efbd3.jpeg");
        // String printerName = "HP ColorLaserJet M253-M254";//打印机名包含字串
        // JPGPrint(file, printerName);

        String pdfFile = "C:/Users/admin/Desktop/企业-回避申请书_20240415154113A018.pdf";//文件路径
        File file = new File(pdfFile);
        String printerName = "HP ColorLaserJet M253-M254";//打印机名包含字串
        PDFPrint(file, printerName);

    }


    // 传入文件和打印机名称
    public static void JPGPrint(File file, String printerName) throws PrintException {

        if (file == null) {
            System.err.println("缺少打印文件");
        }

        FileInputStream fis = null;

        try {
            // 设置打印格式,如果未确定类型,可选择autosense
            DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
            // 设置打印参数
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            aset.add(new Copies(1)); //份数
            //aset.add(MediaSize.ISO.A4); //纸张
            // aset.add(Finishings.STAPLE);//装订
            aset.add(Sides.DUPLEX);//单双面
            // 定位打印服务
            PrintService printService = null;
            if (printerName != null) {
                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if (printServices == null || printServices.length == 0) {
                    System.out.print("打印失败,未找到可用打印机,请检查。");
                    return;
                }
                //匹配指定打印机
                for (int i = 0; i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if (printService == null) {
                    System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                    return;
                }
            }

            fis = new FileInputStream(file); // 构造待打印的文件流
            Doc doc = new SimpleDoc(fis, flavor, null);
            DocPrintJob job = printService.createPrintJob(); // 创建打印作业
            job.print(doc, aset);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally {
            // 关闭打印的文件流
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void PDFPrint(File file, String printerName) throws Exception {

        PDDocument document = null;

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

            //设置纸张及缩放
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
            //设置多页打印
            Book book = new Book();
            PageFormat pageFormat = new PageFormat();
            //设置打印方向
            pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
            pageFormat.setPaper(getPaper());//设置纸张
            book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
            printJob.setPageable(book);
            printJob.setCopies(1);//设置打印份数
            //添加打印属性
            HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
            pars.add(Sides.DUPLEX); //设置单双页
            printJob.print(pars);
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Paper getPaper() {
        Paper paper = new Paper();

        // 默认为A4纸张,对应像素宽和高分别为 595, 842
        int width = 595;
        int height = 842;

        // 设置边距,单位是像素,10mm边距,对应 28px
        int marginLeft = 10;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        paper.setSize(width, height);

        // 下面一行代码,解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }

}
         2、utils
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.springframework.stereotype.Component;
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.*;
import java.awt.print.*;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;

public class PrintUtils {

    /**
     * 无驱(通过ip连接打印机)
     *
     * @param pdfPath
     * @param printIp
     */
    public static void printPDF(String pdfPath, String printIp) {

        String ip = printIp; //打印机ip
        int port = 9100; // 打印机端口
        int timeout = 3000; //连接超时时间
        File file = new File(pdfPath);
        Socket socket = new Socket();

        try {
            socket.connect(new InetSocketAddress(ip, port), timeout);
            OutputStream out = socket.getOutputStream();
            FileInputStream fis = new FileInputStream(file);
            System.out.println(file.length());
            //建立数组
            byte[] buf = new byte[1024];
            int len = 0;
            //判断是否读到文件末尾
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            //告诉服务端,文件已传输完毕
            socket.shutdownOutput();
            socket.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 有驱(通过打印机驱动实现打印)
     *
     * @param file
     */
    public static void printPDF2(File file) throws Exception {

        PDDocument document = null;

        try {
            document = PDDocument.load(file);
            // 1.创建一个打印任务,用于处理打印任务。使用PrinterJob类来实现。
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(file.getName());

            // 2.通过PrinterJob类的getPrintService()方法获取默认的打印机。
            PrintService printService = printJob.getPrintService();
            System.out.println(printService);
            if (printService != null) {
                printJob.setPrintService(printService);
            } else {
                // System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                System.out.print("打印失败,名称为" + printService + "的打印机未被设置成系统默认打印机,请检查。");
                return;
            }

            //设置纸张及缩放
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
            //设置多页打印
            Book book = new Book();
            PageFormat pageFormat = new PageFormat();
            //设置打印方向
            pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
            pageFormat.setPaper(getPaper());//设置纸张
            book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
            printJob.setPageable(book);
            printJob.setCopies(1);//设置打印份数
            //添加打印属性
            HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
            pars.add(Sides.DUPLEX); //设置单双页
            printJob.print(pars);
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Paper getPaper() {
        Paper paper = new Paper();

        // 默认为A4纸张,对应像素宽和高分别为 595, 842
        int width = 595;
        int height = 842;

        // 设置边距,单位是像素,10mm边距,对应 28px
        int marginLeft = 10;
        int marginRight = 0;
        int marginTop = 10;
        int marginBottom = 0;
        paper.setSize(width, height);

        // 下面一行代码,解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }

    public static void main(String[] args) throws IOException {
        String docPath = "D:/ass/uploadPath/upload/测试文档.docx";
        String pdfPath = "D:/ass/uploadPath/upload/测试文档.pdf";
        WordToPdf.word2pdf(docPath, pdfPath);
        File file = new File(pdfPath);
        try {
            printPDF2(file);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值