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
  • 相关阅读:
    挺喜欢的一幅摄影作品,不知道作者 不知道出处...
    使用触发器来监控表的使用情况
    SQL Server 针对表的只读权限分配
    tnslsnr.exe进程占用大量内存的解决.
    记录一次MYSQL的备份(浅尝辄止型)
    记录temp被撑爆的一次SQL tuning
    Bug 5880921 V$SYSMETRIC_HISTORY 的时间错乱
    sqlite3学习记录
    指针 数组指针 指针数组 函数指针等说明。
    c/c++ 运算符 优先级 结合性 记录
  • 原文地址:https://www.cnblogs.com/xdecode/p/7977324.html
Copyright © 2011-2022 走看看