Java打印的几种方法

论坛 期权论坛 脚本     
已经匿名di用户   2022-5-29 19:35   3006   0

实现Java打印功能有3种方式

javax.print.PrintService

使用javax.print包下的类来打印,可以打印文档,PDF等等文档

Doc doc = new SimpleDoc(new FileInputStream("tobeprint.pdf"), DocFlavor.BYTE_ARRAY.PDF, null);
PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = ps.createPrintJob();
job.print(doc, null);

java.awt.PrinterJob

awt的实现,可以通过Printable 打印 Graphics,自己程序绘制要打印的内容。

import java.awt.*;
import java.awt.print.*;


public class PrintToPrinter {

    public static void main(String[] args) throws Exception {
        Book book = new Book();
        PageFormat pf = new PageFormat();
        pf.setOrientation(PageFormat.PORTRAIT);

        Paper p = new Paper();
        p.setSize(590, 840);
        p.setImageableArea(10, 10, 590, 840);
        pf.setPaper(p);
        book.append(new OneLabel(), pf);

        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(book);
        job.print();
    }

    /**
     * 实现Printable即可打印
     */
    public static class OneLabel implements Printable {
        @Override
        public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
            if (pageIndex != 0) {
                // 此例子只有一页;
                return NO_SUCH_PAGE;
            }
            Graphics2D g2 = (Graphics2D) graphics;
            double scale = 72.0 / 300; //屏幕DPI是72;打印机DPI:300; 可以实现打印的更精细,特别是图片
            g2.scale(scale, scale);

            g2.setColor(Color.black);

            double x = pageFormat.getImageableX();
            double y = pageFormat.getImageableY();
            System.out.println("左上角:" + x + "," + y + "  宽高: " + pageFormat.getWidth() + "," + pageFormat.getHeight());

            String str = "中文字符串";
            Font font = new Font("微软雅黑", Font.PLAIN, 10);
            g2.setFont(font);
            g2.drawString(str, (float) x, (float) (y + 20));

            Font font2 = new Font("微软雅黑", Font.PLAIN, 20);
            g2.setFont(font2);
            g2.drawString(str, (float) x, (float) (y + 80));

            return PAGE_EXISTS;
        }
    }
}

javafx.print.PrinterJob

这是javafx的实现,可以打印Canvas,类似awt的功能

final Canvas canvas = new Canvas(250,250);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.fillText("hello, world.", 10, 10);
PrinterJob printerJob = PrinterJob.createPrinterJob();
printerJob.printPage(canvas);

原文

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:81
帖子:4969
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP