因此,我找到了一种最适合我的情况的方法,并且我认为我只发布它的内容,以防对任何人有用。
该解决方案的基础是Java确实拥有自己的完整版(至少与我的版本相比)printDialog
popUp,它具有超出我所需的功能(页面布局编辑,预览等),使用它所需要做的就是一个实现Printable的对象,并且在该对象内您可以创建图形并绘制文档。
我只需要绘制我的输出String即可,而且很容易做到,我什至找到了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; }@Overridepublic 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;}}无论如何,这就是我解决这个问题的方法!希望对某人有用!



