JavaFX标签打印

时间:2018-11-23 13:43:38

标签: java javafx printing

我尝试在30x20mm纸张尺寸和203dpi分辨率的标签打印机上打印图像。图像尺寸直接取决于纸张尺寸,因为图像尺寸必须适合纸张尺寸。

private static BufferedImage createImage(double widthMm, double heightMm, float resolution) {
    int width = (int) MetricUtils.millimetersToPixels(widthMm, resolution);
    int height = (int) MetricUtils.millimetersToPixels(heightMm, resolution);
    return new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}

public final class MetricUtils {

public static final double INCH_PER_MM = 25.4d;

public static double millimetersToInches(double mm) {
    return mm / INCH_PER_MM;
}

public static double millimetersToPixels(double mm, float dpi) {
    return millimetersToInches(mm) * dpi;
}

}

之后,我尝试像这样设置纸张尺寸(打印区域)和图像打包尺寸(图像区域)

private void printLabel(Printer printer, BufferedImage image) throws PrinterException {
    try {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        PrintService printService = findPrintService(printer.getName(), printServices);

        double width = MetricUtils.millimetersToPixels(printer.getPaperSize().first, 72.0F);
        double height = MetricUtils.millimetersToPixels(printer.getPaperSize().second, 72.0F);

        Paper paper = new Paper();
        paper.setSize(width, height);
        paper.setImageableArea(0, 0, image.getWidth(), image.getHeight());

        PageFormat pageFormat = new PageFormat();
        pageFormat.setPaper(paper);
        pageFormat.setOrientation(PageFormat.PORTRAIT);

        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(new ImagePrintable(image), pageFormat);
        printJob.setPrintService(printService);
        printJob.pageDialog(pageFormat);
        printJob.print();

    } catch (Exception e) {
        throw new PrintingException("Could not print image on the local printer", e);
    }
}

因此,图像尺寸必须等于纸张尺寸,但结果是,打印机将向左偏移小图像。

public class ImagePrintable implements Printable {

    private BufferedImage image;

    public ImagePrintable(BufferedImage image) {
        this.image = image;
    }

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex != 0) {
            return NO_SUCH_PAGE;
        }

        Graphics2D printerGraphics = (Graphics2D) graphics;
        printerGraphics.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
        printerGraphics.drawImage(image, 0, 0, (int) pageFormat.getImageableWidth(), (int) pageFormat.getImageableHeight(), null);
        return PAGE_EXISTS;
    }
}

0 个答案:

没有答案