import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringReader; public class PrinterMe implements Printable { private String printData; public PrinterMe(String printDataIn) { this.printData = printDataIn; } public int print(Graphics g, PageFormat pf, int page) throws PrinterException { // Should only have one page, and page # is zero-based. if (page > 0) { return NO_SUCH_PAGE; } // Adding the "Imageable" to the x and y puts the margins on the page. // To make it safe for printing. Graphics2D g2d = (Graphics2D) g; int x = (int) pf.getImageableX(); int y = (int) pf.getImageableY(); g2d.translate(x, y); // Calculate the line height Font font = new Font("Serif", Font.PLAIN, 10); FontMetrics metrics = g.getFontMetrics(font); int lineHeight = metrics.getHeight(); BufferedReader br = new BufferedReader(new StringReader(printData)); // Draw the page: try { String line; // Just a safety net in case no margin was added. x += 50; y += 50; while ((line = br.readLine()) != null) { y += lineHeight; g2d.drawString(line, x, y); } } catch (IOException e) { // } return PAGE_EXISTS; } private void printToPrinter() { // String printData = CalculationTextArea.getText() + "\n" + // SpecificTextArea.getText(); //String printData = "0313 DEJI PLAZA CO.,LTD.,NANJING"; PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(new PrinterMe(printData)); boolean doPrint = job.printDialog(); if (doPrint) { try { job.print(); } catch (PrinterException e) { // Print job did not complete. } } } public static void main(String[] args) { PrinterMe p = new PrinterMe("工行广州市南方支行sdklfjalskjfo23u90348u9"); p.printToPrinter(); System.out.println("Done"); } }