You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java原生方式打印PDF文件 itextpdf 5生成PDF打印方案咨询

Java实现PDF打印的两种可行方案

方案1:Java原生静默直接打印(无需打开文件)

该方案依赖JDK自带的javax.print打印API,配合PDF渲染库将PDF转换为打印服务可识别的格式,注意itextpdf5本身没有内置PDF渲染打印能力,需搭配轻量渲染库实现:

  • 核心实现步骤:
    1. 枚举系统可用的打印服务,选择目标打印机
    2. 构造打印请求属性集,设置纸张大小、是否双面、打印份数等参数
    3. 用PDF渲染库加载已生成的PDF文件,逐页转换为可打印的Printable对象
    4. 提交打印任务到打印服务
  • 核心代码示例:
import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.MediaSizeName;
import com.sun.pdfview.PDFFile;
import java.awt.print.*;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class PdfPrinter {
    public static void directPrintPdf(File pdfFile, int printCopies) throws Exception {
        // 加载PDF文件
        RandomAccessFile raf = new RandomAccessFile(pdfFile, "r");
        FileChannel channel = raf.getChannel();
        ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
        PDFFile pdfFileObj = new PDFFile(buf);

        // 构造打印属性
        HashPrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
        attributes.add(new Copies(printCopies));
        attributes.add(MediaSizeName.ISO_A4); // 可替换为发票对应自定义纸张尺寸

        // 选择打印服务
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, attributes);
        if (printServices.length == 0) {
            throw new RuntimeException("未找到可用打印机");
        }
        // 此处可根据打印机名称指定目标打印机,默认取第一个可用设备
        PrintService printService = printServices[0];

        // 创建打印任务
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        printerJob.setPrintService(printService);
        printerJob.setPrintable((graphics, pageFormat, pageIndex) -> {
            if (pageIndex >= pdfFileObj.getNumPages()) {
                return Printable.NO_SUCH_PAGE;
            }
            // 渲染PDF页到打印画布
            graphics.translate((int) pageFormat.getImageableX(), (int) pageFormat.getImageableY());
            pdfFileObj.getPage(pageIndex + 1).draw(graphics, (int) pageFormat.getImageableWidth(), (int) pageFormat.getImageableHeight(), null, null);
            return Printable.PAGE_EXISTS;
        });

        // 若需要弹出打印机选择框,可先调用printerJob.printDialog(),用户确认后再执行打印
        printerJob.print(attributes);
        raf.close();
    }
}

说明:打印预览可自行结合PDF渲染能力实现,不需要依赖外部软件

方案2:调用系统默认PDF阅读器打开后触发打印

该方案无额外依赖,直接调用Java自带的java.awt.Desktop类实现,适合需要用户预览确认后再打印的场景:

  • 核心实现步骤:
    1. 检查当前系统是否支持Desktop操作
    2. 调用对应方法打开PDF或者直接调起打印对话框
  • 核心代码示例:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

public class PdfOpenPrint {
    public static void openAndPrint(File pdfFile) throws IOException {
        if (!Desktop.isDesktopSupported()) {
            throw new RuntimeException("当前系统不支持Desktop操作");
        }
        Desktop desktop = Desktop.getDesktop();
        // 仅打开PDF,由用户手动点击打印按钮
        if (desktop.isSupported(Desktop.Action.OPEN)) {
            desktop.open(pdfFile);
        }
        // 若需要直接调起打印对话框,可替换为以下代码,不需要用户手动在阅读器找打印入口
        // if (desktop.isSupported(Desktop.Action.PRINT)) {
        //     desktop.print(pdfFile);
        // }
    }
}

说明:该方案仅适用于桌面端部署的软件,web端服务部署场景下调用该方法只会操作服务端的阅读器,无法触达用户端设备

适配发票打印的注意事项

  • 直接打印方案需提前匹配发票实际尺寸设置打印属性,避免内容偏移、缺边
  • 若需要打印多联发票,需确认打印机支持针打模式,调整打印浓度参数即可

内容的提问来源于stack exchange,提问作者cannierhesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:57:04