JavaFX8 Print API:如何正确设置Printable区域

Kac*_*Sys 6 printing javafx

在我的javafx应用程序中,我使用JavaFX 8打印API来打印节点,我遇到了打印区域的问题,尽管我已经用A4纸设置了pageLayout ....这是我的代码:

public static  void printNode(final Node node) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        Printer printer = Printer.getDefaultPrinter();   
        PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, 0,0,0,0 );      
        PrinterJob job = PrinterJob.createPrinterJob();
        if (job != null  && job.showPrintDialog(node.getScene().getWindow()) ) { 
            boolean success = job.printPage(pageLayout, node);                   
            if (success) {
                job.endJob();
            }
        }
Run Code Online (Sandbox Code Playgroud)

以下是我要打印的节点的快照: 在此输入图像描述

这是我打印节点时得到的内容 在此输入图像描述

aw-*_*ink 8

在您的方法中,您需要获得硬件边距.即使您将边距设置为0,您的打印机在工作表周围也有一个不可打印的边距.

如果打印出来,可以查看边距:

System.out.println("PageLayout: " + pageLayout.toString());
Run Code Online (Sandbox Code Playgroud)

而且您无法将边距设置为小于零的值.因此,您需要扩展将要打印的节点.节点将缩放,打印,然后不缩放.

  public static void printNode(final Node node) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Printer printer = Printer.getDefaultPrinter();
    PageLayout pageLayout
        = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
    PrinterAttributes attr = printer.getPrinterAttributes();
    PrinterJob job = PrinterJob.createPrinterJob();
    double scaleX
        = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
    double scaleY
        = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
    Scale scale = new Scale(scaleX, scaleY);
    node.getTransforms().add(scale);

    if (job != null && job.showPrintDialog(node.getScene().getWindow())) {
      boolean success = job.printPage(pageLayout, node);
      if (success) {
        job.endJob();

      }
    }
    node.getTransforms().remove(scale);
  }
Run Code Online (Sandbox Code Playgroud)

灵感来自这里找到的解决方案:https://carlfx.wordpress.com/2013/07/15/introduction-by-example-javafx-8-printing/