java - 从java程序打印文本到打印机

标签 java printing

我想在 java 中打印一个字符串到打印机。在网上搜索后,我找到了很多教程。对于这个问题,I have the following code found from the answer of this question :

public class PrintText {

  public static void main(String[] args) throws PrintException, IOException {

    String defaultPrinter = 
      PrintServiceLookup.lookupDefaultPrintService().getName();
    System.out.println("Default printer: " + defaultPrinter);
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();

    // prints the famous hello world! plus a form feed
    InputStream is = new ByteArrayInputStream("hello world!\f".getBytes("UTF8"));

    PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
    pras.add(new Copies(1));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    Doc doc = new SimpleDoc(is, flavor, null);
    DocPrintJob job = service.createPrintJob();

    PrintJobWatcher pjw = new PrintJobWatcher(job);
    job.print(doc, pras);
    pjw.waitForDone();
    is.close();
  }
}

class PrintJobWatcher {
  boolean done = false;

  PrintJobWatcher(DocPrintJob job) {
    job.addPrintJobListener(new PrintJobAdapter() {
      public void printJobCanceled(PrintJobEvent pje) {
        allDone();
      }
      public void printJobCompleted(PrintJobEvent pje) {
        allDone();
      }
      public void printJobFailed(PrintJobEvent pje) {
        allDone();
      }
      public void printJobNoMoreEvents(PrintJobEvent pje) {
        allDone();
      }
      void allDone() {
        synchronized (PrintJobWatcher.this) {
          done = true;
          System.out.println("Printing done ...");
          PrintJobWatcher.this.notify();
        }
      }
    });
  }
  public synchronized void waitForDone() {
    try {
      while (!done) {
        wait();
      }
    } catch (InterruptedException e) {
    }
  }
}

运行此 cdoe 后,我得到以下输出。

Default printer: EPSON TM-T81 Receipt
Printing done ...

但是打印机没有打印任何东西。打印力还可以。我无法检测到问题。我只想将一个字符串打印到 printer 。解决办法是什么 ?

最佳答案

     import java.awt.*;
      import java.awt.font.*;
      import java.awt.geom.*;
      import java.awt.print.*;
      import java.io.BufferedReader;
     import java.io.FileReader;
      import java.text.*;

     public class PrintFileToPrinter implements Printable {

      static AttributedString myStyledText = null;

     public static void main(String args[]) {
     /**Location of a file to print**/
     String fileName = "C:/Temp/abc.txt";

     /**Read the text content from this location **/
     String mText = readContentFromFileToPrint(fileName);

     /**Create an AttributedString object from the text read*/
      myStyledText = new AttributedString(mText);

     printToPrinter();

     }

     /**
      * <span id="IL_AD8" class="IL_AD">This method</span> reads the content of a text file.
      * The location of the file is provided in the parameter
     */
      private static String readContentFromFileToPrint(String fileName) {
       String dataToPrint = "";

       try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        String line = "";
        /**Read the file and populate the data**/
        while ((line = input.readLine()) != null) {
            dataToPrint += line + "\n";
        }
      } catch (Exception e) {
        return dataToPrint;
      }
       return dataToPrint;
      }

     /**
      * Printing the data to a printer.
      * Initialization done in this method.
      */
      public static void printToPrinter() {
      /**
       * Get a Printer Job
       */
      PrinterJob printerJob = PrinterJob.getPrinterJob();

      /**
      * Create a book. A book contains a pair of page painters
      * called printables. Also you have different pageformats.
      */
      Book book = new Book();
      /**
       * Append the Printable Object (this one itself, as it
        * implements a printable interface) and the page format.
       */
       book.append(new PrintFileToPrinter(), new PageFormat());
       /**
       * Set the object to be printed (the Book) into the PrinterJob. Doing this
       * before bringing up the print dialog allows the print dialog to correctly
       * display the page range to be printed and to dissallow any print <span id="IL_AD6"
       class="IL_AD">settings</span> not
        * appropriate for the pages to be printed.
     */
       printerJob.setPageable(book);

       /**
        * Calling the printDialog will pop up the Printing Dialog.
       * If you want to print without user <span id="IL_AD10" class="IL_AD">confirmation</span>,
        you can directly call printerJob.print()
       *
       * doPrint will be false, if <span id="IL_AD11" class="IL_AD">the user</span> cancels the

       print <span id="IL_AD12" class="IL_AD">operation</span>.
       */
       boolean doPrint = printerJob.printDialog();

        if (doPrint) {
        try {
            printerJob.print();
           } catch (PrinterException ex) {
            System.err.println("Error occurred while trying to Print: "
                    + ex);
           }
        }
       }

        /**
      * This method comes from the Printable interface.
      * The method implementation in this class
      * prints a page of text.
      */
       public int print(Graphics g, PageFormat format, int pageIndex) {

        Graphics2D graphics2d = (Graphics2D) g;
        /**
         * Move the origin from the corner of the Paper to the corner of the imageable
         * area.
        */
         graphics2d.translate(format.getImageableX(), format.getImageableY());


         Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = myStyledText.getIterator();
         LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
            graphics2d.getFontRenderContext());
         float wrappingWidth = (float) format.getImageableWidth();
         while (measurer.getPosition() &lt; charIterator.getEndIndex()) {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        pen.y += layout.getAscent();
        float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout
                .getAdvance());
        layout.draw(graphics2d, pen.x + dx, pen.y);
        pen.y += layout.getDescent() + layout.getLeading();
         }
        return Printable.PAGE_EXISTS;
        }

       }

关于java - 从java程序打印文本到打印机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26479380/

相关文章:

java - 在类之前和之后调用特定方法的通用测试类的设计 - 用于集成测试

bash - Flutter 桌面 - 将 PDF 发送到打印机

java - 发送十六进制命令到 ESC/POS 打印机 Android

c++ - Qt:打印原始文本

java - 代码不产生 java 输出

java - 使用 GSON,当某些键具有特殊字符时如何将 JSON 转换为 Java

java - 如何在双向关系中删除一侧的对象?

java - primitive == Wrapper 转换为 primitive == primitive 或 Wrapper == Wrapper?

java - 如何在Mobicent jain-slee平台上实现新直径应用?

c - 单词搜索字符串操作