Search code examples
javajavafxprintingresolutiondpi

Javafx - Print a node with a DPI larger than 72


I am trying to print a node with something very basic

private void print(Node node) {
    System.out.println("Creating a printer job...");

    PrinterJob job = PrinterJob.createPrinterJob();
    if (job != null && job.showPrintDialog(node.getScene().getWindow()) ) {
        System.out.println(job.jobStatusProperty().asString());

        PageLayout pageLayout = Printer.getDefaultPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);

        boolean printed = job.printPage(pageLayout, node);
        if (printed) {
            System.out.println("Printed.");
            job.endJob();
        } else {
            System.out.println("Printing failed.");
        }
    } else {
        System.out.println("Could not create a printer job.");
    }
}

The problem is that I am stuck with a DPI resolution set to 72. Is it a way (without multiplying dimensions with 72.0/wanted_dpi_resolution) of changing it in other DPI resolution? (My screen is as well 96 DPI) I am very interested to be able to print with a DPI value that is at least 96 DPI.

Thank you and waiting for your response.


Solution

  • Meh the short answer is that it is impossible.

    Hopefully this will help someone else with the same issue as I. Please find enclose next code.

    public static void printReport(ArrayList<MyPane> nodeList) {
        System.out.println("Creating a printer job...");
    
        String printerName = CachedComponents.getPrinterName();
    
        Printer printer = null;
        for (Printer p : Printer.getAllPrinters()) {
            if (p.getName().equals(printerName)) {
                printer = p;
                break;
            }
        }
    
        PrinterJob job = PrinterJob.createPrinterJob(printer);
        if (job != null) {
            job.getJobSettings().setPrintQuality(PrintQuality.HIGH);
    
            PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT,
                    Printer.MarginType.HARDWARE_MINIMUM);
    
            boolean fail = false;
            for (int i=0; i<nodeList.size(); i++) {
                MyPane node = nodeList.get(i);
    
                double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
                node.getTransforms().add(new Scale(scaleX, scaleX));
    
                boolean printed = job.printPage(pageLayout, node);
    
                if (printed) {
                    System.out.println("Printed.");
                } else {
                    System.out.println("Printing failed.");
                    fail = true;
                }
            }
            if (!fail) {
                job.endJob();
            }
        } else {
            System.out.println("Could not create a printer job.");
        }
    }
    

    Check out for the null checking.

    Cheers!