使用标签打印机进行Java特定页面大小的打印

3
我想使用一个标签打印机(具体来说是EPSON TM-T88V)来打印PNG图片。我可以成功地进行打印,但当我打印一张尺寸为220x175,分辨率为72dpi的图片时,会在图像上方印出一大块空白区域,这会浪费很多纸张。您有什么办法可以减少纸张浪费吗?我希望它只打印图像,最小化空白区域,然后切掉纸张。下面是我的代码:
    AttributeSet aset = new HashAttributeSet();
    aset.add(new PrinterName(printerName, null));
    /* locate a print service that can handle the request */
    PrintService[] services = PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PNG, aset);

    if (services.length >= 1) {
        /* create a print job for the chosen service */
        DocPrintJob pj = services[0].createPrintJob();

        DocAttributeSet das = new HashDocAttributeSet();
        das.add(PrintQuality.HIGH);
        das.add(MediaSizeName.ISO_A7); // I know the problem is here somewhere. This Media size seems to work best currently

        try {
            /* 
            * Create a Doc object to hold the print data.
            */
            Doc doc = new SimpleDoc(imageByteIs, DocFlavor.INPUT_STREAM.PNG, das);

            /* print the doc as specified */
            pj.print(doc, null);

        } catch (PrintException e) { 
            System.err.println(e);
        }
    }
3个回答

4

您可以通过以下方式查找可用的纸张尺寸:

PrintService printService = PrintServiceLookup.lookupDefaultPrintService();
Media[] res = (Media[]) printService.getSupportedAttributeValues(Media.class, null, null);
for (Media media : res) {
    if (media instanceof MediaSizeName) {
        MediaSizeName msn = (MediaSizeName) media;
        MediaSize ms = MediaSize.getMediaSizeForName(msn);
        float width = ms.getX(MediaSize.INCH);
        float height = ms.getY(MediaSize.INCH);
        System.out.println(media + ": width = " + width + "; height = " + height);
    }
}

一旦您找到最接近您纸张尺寸的可用MediaSizeName,只需将其添加到MediaSizeName.ISO_A7的位置即可。


0
添加一个MediaPrintableArea
das.add(new MediaPrintableArea(0.05, 0.05, 0.05, 0.05, MediaPrintableArea.INCH));

感谢您的贡献,Joop。但是我现在遇到了一个java.lang.IllegalArgumentException: 0 or negative value argument at javax.print.attribute.standard.MediaPrintableArea.<init>(MediaPrintableArea.java:143)的问题。看起来我无法使用0来初始化MediaPrintableArea。 - alwinc
不,那只是页面左上角的小字。我认为这不是MediaPrintableArea的作用。我相信该类仅用于指定可供打印的媒体区域。例如,如果仅使用顶部一半进行打印等。因此,全局0.05会在左上角产生一个小点。Joop...我认为你离答案还很远。 - alwinc

0

这是我用于在A4纸上打印的设置,边距为10毫米。

int width = Math.round(MediaSize.ISO.A4.getX(MediaSize.MM));
int height = Math.round(MediaSize.ISO.A4.getY(MediaSize.MM));
das.add(new MediaPrintableArea(10, 10, width-20, height-20, MediaPrintableArea.MM));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接