Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

java - JavaFX : Image getting scaled to 25% and then getting printed.

I am trying to print an image using JavaFX api's. Unfortunately, it is cutting a part of the image, approximately 25% and then stretching that to the entire A4 page, and printing it. What am I doing wrong with the print code. How can I instruct to fit the image to page for printing, no matter what the printer is. Kindly let me know.

Code :

 public void printThis() {

        System.out.println("I was called");
        // note you can use overloaded forms of the Image constructor
        // if you want to scale, etc
        String path = "resources/img/printouts/image.png";
        Image image = new Image(getClass().getResource(path).toExternalForm());
        ImageView imageView = new ImageView(image);
        new Thread(() -> printImage(imageView)).start();
    }

    public void printImage(ImageView image) {
        Printer printer = Printer.getDefaultPrinter();
        PrinterJob printJob = PrinterJob.createPrinterJob(printer);
        PageLayout pageLayout = printJob.getJobSettings().getPageLayout();
        //PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
        printJob.getJobSettings().setPageLayout(pageLayout);
        if (printJob != null) {
            boolean success = printJob.printPage(image);
            if (success) {
                printJob.endJob();
            }
        }
    }

Kindly let me know what am I doing wrong. Thank you. :-)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could add the following code to the printImage method:

image.setPreserveRatio(true);
image.setFitHeight(pageLayout.getPrintableHeight());
image.setFitWidth(pageLayout.getPrintableWidth());

This will print the image scaled to the largest size that can be fit into a rectangle of pageLayout.getPrintableWidth() x pageLayout.getPrintableHeight() preserving the ratio, see ImageView.preserveRation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...