JavaFX printing non node objects

假如想象 提交于 2019-12-04 15:38:22

You can get a java.awt.Image from each page, draw the page to a java.awt.image.BufferedImage convert the BufferedImage to a javafx.scene.image.Image, and finally print an ImageView containing the image:

Something like:

PrinterJob job = PrinterJob.createPrinterJob();
PDFFile pdfFile = ... ;
if (job != null) {
    boolean success = true ;
    for (int pageNumber = 1; pageNumber <= pdfFile.getNumPages() ; pageNumber++) {
        PDFPage page = pdfFile.getPage(pageNumber, true);
        Rectangle2D bounds = page.getBBox();
        int width = (int) bounds.getWidth();
        int height = (int) bounds.getHeight();
        java.awt.Image img = page.getImage(width, height, bounds, null, true, true);
        BufferedImage bImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        bImg.createGraphics().drawImage(img, 0, 0, null);
        javafx.scene.image.Image fxImg = SwingFXUtils.toFXImage(bImg, null);
        ImageView imageView = new ImageView(fxImg);
        success = success & job.printPage(imageView);
    }

    if (success) {
        job.endJob();
    }
}

Note that this code can be executed off the FX Application Thread, to keep the UI responsive.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!