在网上找了不少通过jdk的printService服务打印pdf的博客,都大同小异,打印调用了但是没有真的打印,最后终于找到一个可用的,这里记录一下。

首先通过maven引入依赖:

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

最后使用工具类:

package com.ruoyi.mrs.utils;import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
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.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;/*** @author fmi110* @description 打印工具类* @date 2021/11/16 14:22*/
public class PrintUtil {private static final Logger log = LoggerFactory.getLogger(PrintUtil.class);/*** 寻找指定的打印机* @param printerName* @return*/public static PrintService lookupPrinter(String printerName) {PrintService service = null;PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);if (printServices == null || printServices.length == 0) {throw new BusinessException("未获取到打印服务");}List<String> printerNames = Arrays.stream(printServices).map(p -> p.getName()).collect(Collectors.toList());log.info(">>>>可选的打印机:{}", printerNames);for (int i = 0; i < printServices.length; i++) {String name = printServices[i].getName().toLowerCase();log.info("printName{}:{}", i, name);if (name.contains(printerName.toLowerCase())) {service = printServices[i];break;}}if (service == null) {throw new BusinessException("未找到指定的打印机:" + printerName + ",可选打印服务:" + printerNames);}return service;}public static void print(String filePath, String printerName, PrintRequestAttributeSet aset) throws Exception {print(new File(filePath), printerName, aset);}/*** 打印指定文件* @param file* @param printerName* @param aset 打印属性,可通过这个设置打印份数* @throws Exception*/public static void print(File file, String printerName, PrintRequestAttributeSet aset) throws Exception {if (file == null) {log.error("传入的文件为空");throw new Exception("传入的文件为空");}if (!file.exists()) {log.error("文件不存在:" + file.getAbsolutePath());throw new Exception("文件不存在:" + file.getAbsolutePath());}PrintService printService = lookupPrinter(printerName);if (null == aset) {aset = getPrintRequestAttributeSet(); // 获取打印参数}PDDocument document = PDDocument.load(file);PrinterJob printJob = PrinterJob.getPrinterJob();printJob.setJobName(file.getName());printJob.setPrintService(printService); // 选择打印机//设置纸张及缩放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);try {printJob.print(aset);} catch (Exception e) {e.printStackTrace();log.error("打印机打印异常:{}", e.getMessage());throw new Exception("打印机打印异常:" + e.getMessage());} finally {IOUtils.closeQuietly(document);}}private static PrintRequestAttributeSet getPrintRequestAttributeSet() {PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();aset.add(new Copies(1)); //份数aset.add(MediaSizeName.ISO_A4); //纸张// aset.add(Finishings.STAPLE);//装订aset.add(Sides.ONE_SIDED);//单双面return aset;}/*** 设置打印份数** @param copy* @return*/public static PrintRequestAttributeSet getPrintRequestAttributeSet(int copy) {PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();aset.add(new Copies(copy)); //份数aset.add(MediaSizeName.ISO_A4); //纸张// aset.add(Finishings.STAPLE);//装订aset.add(Sides.ONE_SIDED);//单双面return aset;}/*** 将图片转换成pdf** @return* @throws Exception*/public static byte[] img2PDF(List<byte[]> images) throws Exception {Document doc = new Document(PageSize.A4, 0, 0, 36.0F, 36.0F);//普通a4ByteArrayOutputStream pdfOut = new ByteArrayOutputStream();PdfWriter.getInstance(doc, pdfOut);doc.open();for (byte[] image : images) {com.itextpdf.text.Image pic = com.itextpdf.text.Image.getInstance(image);pic.setScaleToFitLineWhenOverflow(true);doc.add(pic);}doc.close();byte[] pdf = pdfOut.toByteArray();IOUtils.closeQuietly(pdfOut);return pdf;}/*** 图片缩放成A4尺寸,转换为pdf文件** @param imagePath* @param descfolder* @return* @throws Exception*/public static String img2PDF(String imagePath, String descfolder, String pdfName) {return img2PDF(Arrays.asList(imagePath), descfolder, pdfName);}/*** 图片缩放成A4尺寸,转换为pdf文件** @param imgPaths* @param descfolder* @return* @throws Exception*/public static String img2PDF(List<String> imgPaths, String descfolder) {String pdfName = System.currentTimeMillis() + ".pdf";return img2PDF(imgPaths, descfolder, pdfName);}public static String img2PDF(List<String> imgPaths, String descfolder, String pdfName) {pdfName = StringUtils.isEmpty(pdfName) ? System.currentTimeMillis() + ".pdf" : pdfName;String pdfPath = "";FileOutputStream fos = null;try {File file = new File(descfolder);if (!file.exists()) {file.mkdirs();}pdfPath = descfolder + "/" + pdfName;Document doc = new Document(PageSize.A4, 0, 0, 0, 0);fos = new FileOutputStream(pdfPath);PdfWriter.getInstance(doc, fos);doc.open();for (String imagePath : imgPaths) {com.itextpdf.text.Image image = image = com.itextpdf.text.Image.getInstance(imagePath);image.scaleAbsolute(PageSize.A4.getWidth(), PageSize.A4.getHeight());doc.add(image);}doc.close();log.info("生成pdf成功:{}", pdfPath);} catch (Exception e) {e.printStackTrace();log.error("生成pdf异常:" + e.getMessage());throw new BusinessException("生成pdf异常:" + e.getMessage());} finally {IOUtils.closeQuietly(fos);}return pdfPath;}public static void main(String[] args) throws Exception {File file = new File("D:\\test\\2.pdf");print(file, "HP Las", getPrintRequestAttributeSet(1));//        PDDocument document =  PDDocument.load(file);
//        PrinterJob printJob = PrinterJob.getPrinterJob();
//        printJob.setJobName(file.getName());
//        PrintService printService = lookupPrinter("HP Las");
//        printJob.setPrintService(printService);
//
//        //设置纸张及缩放
//        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.ONE_SIDED); //设置单双页
//        printJob.print(pars);}public static Paper getPaper() {Paper paper = new Paper();// 默认为A4纸张,对应像素宽和高分别为 595, 842int width = 595;int height = 842;// 设置边距,单位是像素,10mm边距,对应 28pxint 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;}}

通过main函数可测试结果。

java 调用打印机相关推荐

  1. java 调用打印机 api_java 调用打印机API无法打印,但是直接打印可以,请问有人遇到过这样的问题吗?...

    java调用打印机的代码如下:publicstaticvoidmain(String[]args){PrintRequestAttributeSetpras=newHashPrintRequestAt ...

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

    Java调用打印机打印(远程.本地皆可用) 背景 准备 MAVEN环境 步骤 获取PrinterJob 设置PrinterJob纸张样式 打印PDF 背景 开发个Java项目需要远程调用共享打印机打印 ...

  3. Java调用打印机读写文件

    最近跟着项目组在做项目,分到了打印机这个任务,顺便记录一下. 首先本地最好安装一下打印机的驱动,然后连上打印机开始测试! Java调用打印机打印图片,文本都是很简单的,如下代码: /*** 通过 IP ...

  4. Java调用打印机打印PDF文档的两种方法

    最近,由于项目需求,需要增加系统调用打印机打印PDF文档功能.以前在Asp.Net项目中做过套打,但是现在的需求直接文档打印,下面是实现代码调用打印机的两种方法. 1.Java Print Servi ...

  5. JAVA 调用打印机输出PDF文件

    想利用java程序打印一些文件.做以下测试: 一.环境 要调用打印机输出文件,首先本地得有一个能正常使用的打印机.我电脑安装的是虚拟打印机. 二.java代码 一).打印输出的实体类 import j ...

  6. java 调用打印机打印

    要在 Java 中调用打印机打印,您可以使用 Java 的打印 API.下面是一个简单的示例,展示了如何使用 Java 打印 API 来打印文本: import java.awt.print.Prin ...

  7. Java调用打印机打印pdf

    要在Java中调用打印机打印PDF,可以使用Java打印API和第三方库,如Apache PDFBox或iText PDF. 以下是使用Java打印API打印PDF的基本步骤: 安装打印机:确保您已经 ...

  8. Java:使用Java调用打印机进行打印(JPG、PDF和Word三种文件格式)

    目录 一.Java的打印简介 二.Java打印实现 2.1 JPG图片文件格式打印实现 2.2 PDF文件格式打印实现 2.3 Word文件格式打印实现 2.3.1 Word文件采用jacob插件进行 ...

  9. JAVA调用打印机,打印PDF文件

    1. 导入maven依赖 <dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdf ...

最新文章

  1. 使用工具类时尽量使用私有的无参构造函数
  2. spring Aop的概念
  3. 用hundred造句子_关于冬至的问候短句,冬至文案唯美句子
  4. linux修改windows注册表,妙招:让修改的注册表立即生效的几种方法
  5. 【Verilog HDL】从逻辑电路图到门级建模——人工翻译的方法论
  6. 通用线程:POSIX 线程详解,第 2部分——称作互斥对象的小玩意
  7. java代码着色_给java代码着色源码
  8. SimpleDateFormat线程不安全了?这里有5种解决方案
  9. Django访问java建立的数据库
  10. php数据库显示+ajax,如何使用PHP和AJAX显示MySQL数据库
  11. 力扣题目——1557. 可以到达所有点的最少点数目
  12. 模块 datetime
  13. CVE-2019-0708 微软补丁更新
  14. 用Netlogo实现病毒传播对经济的影响分析
  15. 你可能不知道的iOS性能优化建议(来自前Apple工程师)
  16. js外链跳转_给网站外链进行重定向跳转
  17. 人工智能——文本分类(大作业必备)
  18. linux批量更新文件夹里,Linux下使用touch批量修改文件夹和文件的时间
  19. pyTorch入门(六)——实战Android Minist OpenCV手写数字识别(附源码地址)
  20. PPT还原苹果12手机的官方海报

热门文章

  1. HDU6848改编题(弱化)——客星璀璨之夜(stars)
  2. 一款Github工具包-快速下载网页上的视频
  3. 预测算法——指数平滑法
  4. 基于kettle实现数据采集
  5. 村庄规划gis基础操作详细步骤
  6. 考试酷c语言程序设计的答案大全,FX-TRN-BEG-C 考试酷 V-MECA组合在PLC项目教学中的运用...
  7. 创建自己免费的论坛、博客网站
  8. 《满庭芳·国色》色号记录
  9. 纸上得来终觉浅,决知此事要躬行
  10. 史上最牛叉的俄罗斯方块--game.cpp/.h