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

时间:2012-01-12 19:25:55

标签: java netbeans printing

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

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

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

方法之前的几件事:

  1. 没有抛出错误或异常。

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

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

  4. 如果我不得不猜测,我会认为我可能正在将输出写入文件中,打印机不会除外但不会告诉我。无论如何,这段代码中有相当一部分我对此并不十分了解,所以请告诉我你能找到的内容。

    这是我的代码:

    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);
                    }
                }
            }
    }
    

3 个答案:

答案 0 :(得分:9)

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

解决方案的基础是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;
}
}

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

答案 1 :(得分:1)

创建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) {}

答案 2 :(得分:0)

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

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
              }
            }
相关问题