1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| 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(); }
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; 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; } } }
|