Java:将程序输出打印到物理打印机

我是一个相对较新的程序员,所以这可能是一个非常简单的问题,但它让我有点难过..

我正在尝试将Java GUI的最终输出打印到打印机。 现在,在我的GUI中,我有它,所以当你点击打印时,弹出窗口会显示可用打印机列表,并根据你选择的打印机打印到该打印机。

但事实并非如此。 我通过在互联网上搜索此问题的解决方案获得了大部分代码,并找到了一些有希望的代码。 但是,它打印出一个文件。 所以我只是在我的方法中做的就是首先将输出写入文件,以便我可以使用相同的方法。

方法之前的一些事情:

  1. 没有抛出任何错误或exception。

  2. 我每次尝试创建的文件始终存在,并且具有正确的文本。

  3. 打印到IS的打印机正在接收打印作业,它甚至认为它已经完成了。

如果我不得不猜测,我会认为我可能正在将输出写入File,因为打印机不会除外但不会告诉我。 无论如何,这段代码中有相当一部分我没有真正理解,所以请让我知道你能找到什么。

这是我的代码:

private void printToPrinter() { File output = new File("PrintFile.txt"); output.setWritable(true); //Will become the user-selected printer. Object selection = null; try { BufferedWriter out = new BufferedWriter(new FileWriter(output)); out.write(calculationTextArea.getText() + "\n" + specificTextArea.getText()); out.close(); } catch (java.io.IOException e) { System.out.println("Unable to write Output to disk, error occured in saveToFile() Method."); } FileInputStream textStream = null; try { textStream = new FileInputStream("PrintFile.txt"); } catch (java.io.FileNotFoundException e) { System.out.println("Error trying to find the print file created in the printToPrinter() method"); } DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc mydoc = new SimpleDoc(textStream, flavor, null); //Look up available printers. PrintService[] printers = PrintServiceLookup.lookupPrintServices(flavor, null); if (printers.length == 0) { // No printers found. Inform user. jOptionPane2.showMessageDialog(this, "No printers could be found on your system!", "Error!", JOptionPane.ERROR_MESSAGE); } else { selection = jOptionPane2.showInputDialog(this, "Please select the desired printer:", "Print", JOptionPane.INFORMATION_MESSAGE, null, printers, PrintServiceLookup.lookupDefaultPrintService()); if (selection instanceof PrintService) { PrintService chosenPrinter = (PrintService) selection; DocPrintJob printJob = chosenPrinter.createPrintJob(); try { printJob.print(mydoc, null); } catch (javax.print.PrintException e) { jOptionPane2.showMessageDialog(this, "Unknown error occured while attempting to print.", "Error!", JOptionPane.ERROR_MESSAGE); } } } } 

所以我找到了一种适合我情况的方法,我想我会发布它的内容,以防它对任何人都有用。

解决方案的基础是Java确实拥有自己的完全成熟(至少与我的相比)printDialog popUp,它比我需要的更多(页面布局编辑,预览等),所有你需要做的就是手工操作实现Printable的对象,在该对象中创建图形并绘制文档。

我只需要绘制我的输出字符串,这很容易完成,我甚至找到了一个StringReader,所以我可以天真地停止编写一个文件,只是为了让我的输出在BufferedReader中。

这是代码。 有两个部分,我绘制图像的方法和类:

方法:

 private void printToPrinter() { String printData = CalculationTextArea.getText() + "\n" + SpecificTextArea.getText(); PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(new OutputPrinter(printData)); boolean doPrint = job.printDialog(); if (doPrint) { try { job.print(); } catch (PrinterException e) { // Print job did not complete. } } } 

这里是打印文档的类:

 public class OutputPrinter implements Printable { private String printData; public OutputPrinter(String printDataIn) { this.printData = printDataIn; } @Override 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; } } 

无论如何,这就是我如何解决这个问题! 希望它对某人有用!

创建一个JTextComponent (我建议使用JTextArea这样你就可以使用append() ),并将你需要的东西追加到字段中。 不要在视图上显示它,它只是一个用于打印目的的隐藏字段。

所有JTextComponent都有一个print()方法。 只需调用hiddenTextArea.print() ,其余部分就会为您处理。

  JTextArea hiddenTextArea = new JTextArea(); for (String s : dataToPrintCollection) { hiddenTextArea.append(s + "\n"); } try { hiddenTextArea.print(); } catch (PrinterException e) {} 

您可以直接打印JFrame / JPanel的图形,而不是生成Doc。 这段代码应该有效:

 PrinterJob pj = PrinterJob.getPrinterJob(); pj.setJobName("name"); PageFormat format = pj.getPageFormat(null); pj.setPrintable (new Printable() { @Override public int print(Graphics pg, PageFormat pf, int pageNum) throws PrinterException { if (pageNum > 0){ return Printable.NO_SUCH_PAGE; } Graphics2D g2 = (Graphics2D) pg; this.paint(g2); return Printable.PAGE_EXISTS; } }, format); if (pj.printDialog() == false) return; pj.print(); } catch (PrinterException ex) { // handle exception } }