zoukankan      html  css  js  c++  java
  • Java调用PDFBox打印自定义纸张PDF

    打印对象

    一份设置为A3纸张, 页面边距为(10, 10, 10, 10)mm的PDF文件.

    PageFormat

     默认PDFPrintable无法设置页面大小.

    1         PDFPrintable printable = new PDFPrintable(document);
    2         PrinterJob job = PrinterJob.getPrinterJob();
    3         job.setPrintable(printable);

    需要把它放到一个Book中, 再设置即可

    1         Book book = new Book();
    2         book.append(printable, pageFormat);
    3         printerJob.setPageable(book);
    4         printerJob.print();

    设置纸张属性

    1         Paper paper = new Paper();
    2         paper.setSize(width, height);
    3         // 设置边距
    4         paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
    5         // 自定义页面设置
    6         PageFormat pageFormat = new PageFormat();
    7         // 设置页面横纵向
    8         pageFormat.setOrientation(PageFormat.PORTRAIT);
    9         pageFormat.setPaper(paper);

    注意: 这边计量单位都是在dpi 72下的尺寸.  

    如果拿到是mm, 需要转为px. 例如10mm转换

    10 * 72 * 10 / 254 = 28px

    如果打印出现了截断, 一般是因为没有添加自定义纸张导致的.

    参考 Java读取打印机自定义纸张.

    完整代码如下

     1         InputStream in = new FileInputStream("d:\a3.pdf");
     2         PDDocument document = PDDocument.load(in);
     3         PDFPrintable printable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);
     4 
     5         PrinterJob printerJob = PrinterJob.getPrinterJob();
     6 
     7         PaperSize a3 = PaperSize.PAPERSIZE_A3;
     8         // A3 纸张在72 dpi下的宽高 841 * 1190
     9         int width = a3.getWidth().toPixI(72);
    10         int height = a3.getHeight().toPixI(72);
    11         // 10mm边距, 对应 28px
    12         int marginLeft = 28;
    13         int marginRight = 28;
    14         int marginTop = 28;
    15         int marginBottom = 28;
    16 
    17         Paper paper = new Paper();
    18         paper.setSize(width, height);
    19         // 设置边距
    20         paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
    21         // 自定义页面设置
    22         PageFormat pageFormat = new PageFormat();
    23         // 设置页面横纵向
    24         pageFormat.setOrientation(PageFormat.PORTRAIT);
    25         pageFormat.setPaper(paper);
    26 
    27         Book book = new Book();
    28         book.append(printable, pageFormat);
    29         printerJob.setPageable(book);
    30         printerJob.print();
    View Code
  • 相关阅读:
    PHP 实现 一致性哈希 算法(转的)
    一致性 hash 算法
    分布式设计与开发---宏观概述
    Lvs+keepalived+nginx+php的session 保持的算法
    从零搭建Web网站
    Java动态代理机制详解(JDK 和CGLIB,Javassist,ASM)
    哪个线程执行 CompletableFuture’s tasks 和 callbacks?
    HTTP 用户认证
    java 发送 HTTP 请求
    Http basic Auth 认证方式帮助类
  • 原文地址:https://www.cnblogs.com/xdecode/p/7977324.html
Copyright © 2011-2022 走看看