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
  • 相关阅读:
    读理,妙句秒人秒事,二记
    读理,妙句秒人秒事,一记
    (原)DirectX11 深度测试(有点另类)
    游戏编程书籍推荐
    android入门-环境搭建
    Spring||Interview
    JSR-133内存模型手册
    JVM执行引擎
    HIbernate总结
    虚拟机类加载机制
  • 原文地址:https://www.cnblogs.com/xdecode/p/7977324.html
Copyright © 2011-2022 走看看