调用本地打印机,打印pdf文件功能,可支持远程打印

前言

简单记录打印 PDF 标签功能
相关依赖

<!-- pdf依赖-->
		<dependency>
			<groupId>org.apache.pdfbox</groupId>
			<artifactId>pdfbox</artifactId>
			<version>2.0.24</version>
		</dependency>

		<!-- itextpdf -->
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>kernel</artifactId>
			<version>8.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>io</artifactId>
			<version>8.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>layout</artifactId>
			<version>8.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>forms</artifactId>
			<version>8.0.2</version>
		</dependency>
		<dependency>
			<groupId>com.itextpdf</groupId>
			<artifactId>pdfa</artifactId>
			<version>8.0.2</version>
		</dependency>

一、获取打印机方法

/**
     * 获取本台电脑所有打印机名称
     * @return
     */
    public static Result<List<String>> getPrinterList() {
        Result<List<String>> result = new Result();
        List<String> list = new ArrayList<>();
        HashPrintRequestAttributeSet requestAttributeSet = new HashPrintRequestAttributeSet();
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        //查找所有的可用的打印服务
        PrintService[] printService = PrintServiceLookup.lookupPrintServices(flavor, requestAttributeSet);
        if (printService == null || printService.length == 0) {
            log.info("打印获取失败,未找到可用打印机,请检查。");
            return result.error500("未找到可用打印机,请检查");
        }
        if (printService != null) {
            for (PrintService print : printService) {
                list.add(print.getName());
            }
        }
        result.setResult(list);
        result.setSuccess(true);
        return result;
    }

二、生成pdf文件方法

public static void getPDF(String matnr,String maktx,Integer number,String zhijian,String pinjian) {
        String outputPath = "label.pdf"; // PDF 文件输出路径

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String dateNow = simpleDateFormat.format(new Date());

        try {
            // 创建 PdfWriter 对象来写入 PDF 文件
            PdfWriter writer = new PdfWriter(outputPath);

            // 创建 PdfDocument 对象来管理 PDF 文件
            PdfDocument pdf = new PdfDocument(writer);

            // 设置自定义页面大小为 85mm x 60mm
            PageSize customPageSize = new PageSize((int) (110 / 25.4 * 72), (int) (70 / 25.4 * 72));
            pdf.setDefaultPageSize(customPageSize);

            // 创建 Document 对象来添加内容到 PDF
            Document document = new Document(pdf);

            //设置字体  宋体
            PdfFont font = PdfFontFactory.createFont("C:/Windows/Fonts/simhei.ttf", PdfEncodings.IDENTITY_H);
            document.setFont(font);

            // 调整内容位置
            float xPosition = 40; // X 轴位置
            float yPosition = 145; // Y 轴位置

            // 添加数据到 PDF
            document.add(new Paragraph("品号:"+matnr).setFontSize(14).setFixedPosition(xPosition, yPosition, 300));
            document.add(new Paragraph("品名:"+maktx).setFontSize(14).setFixedPosition(xPosition, yPosition-30, 300));
            document.add(new Paragraph("数量:"+number+"           质检:"+zhijian).setFontSize(14).setFixedPosition(xPosition, yPosition-60, 300));
            document.add(new Paragraph("日期:"+dateNow+"   品检:"+pinjian).setFontSize(14).setFixedPosition(xPosition, yPosition-90, 300));


            // 关闭 Document 对象,将所有内容写入到 PDF 文件中
            document.close();

            System.out.println("PDF 文件生成成功!");
        } catch (FileNotFoundException e) {
            System.err.println("找不到文件:" + e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

调用打印机,打印生成的pdf文件标签方法

public static Result<String> printPDFFile(String printerName, File file, Paper paper,Integer pages) {
        PDDocument document = null;
        Result<String> result = new Result<>();
        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 result.error500("打印失败,未找到可用打印机,请检查。");
                }
                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];
                        break;
                    }
                }
                if(printService!=null){
                    printJob.setPrintService(printService);
                }else{
                    System.out.print("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                    return result.error500("打印失败,未找到名称为" + printerName + "的打印机,请检查。");
                }
            } else {
                return result.error500("打印失败,打印机名称不可为空。");
            }
            //设置纸张及缩放
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.SCALE_TO_FIT);
            //设置多页打印
            Book book = new Book();
            PageFormat pageFormat = new PageFormat();
            //设置打印方向
            pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
            pageFormat.setPaper(paper);//设置纸张
            book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
            printJob.setPageable(book);
            printJob.setCopies(pages);//设置打印份数
            //添加打印属性
            HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
            pars.add(Sides.DUPLEX); //设置单双页
            printJob.print(pars);
        } catch (PrinterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result.success("打印成功");
    }

完整过程,展示

//创建pdf
            PrintUtil.getPDF(productCardVo.getMatnr(),productCardVo.getMaktx(),productCardVo.getNumber(),zhiCategory.getDescription(),pinCategory.getDescription());

            File file = new File("label.pdf");

            //创建纸张对象
            Paper paper = new Paper();
            // 默认为A4纸张,对应像素宽和高分别为 595, 842
            int width = (int) (110 / 25.4 * 72);
            int height = (int) (60 / 25.4 * 72);
            // 设置边距,单位是像素,10mm边距,对应 28px
            int marginLeft = -(int) (4 / 25.4 * 72);
            int marginRight = -(int) (4 / 25.4 * 72);
            int marginTop = -(int) (4 / 25.4 * 72);
            int marginBottom = -(int) (2 / 25.4 * 72);
            paper.setSize(width, height);
            // 设置打印位置
            paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));

            //计算整数量和余数量
            int pages1 = productCardVo.getLmnga() / productCardVo.getNumber();
            int number = productCardVo.getLmnga() % productCardVo.getNumber();

            //打印整数量
            Result<String> result = PrintUtil.printPDFFile(productCardVo.getPrinterName(), file, paper, pages1);

            //如果有余数就打印余数
            if (number > 0){
                //创建pdf
                PrintUtil.getPDF(productCardVo.getMatnr(),productCardVo.getMaktx(),number,zhiCategory.getDescription(),pinCategory.getDescription());
                //打印余数量
                PrintUtil.printPDFFile(productCardVo.getPrinterName(), file, paper, 1);
            }

总结

该代码支持本地打印,如果要远程调用打印机的话,可以将打印机共享给服务器,实现调用远程打印机

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值