我正在尝试使用Java Print Service API打印JTextArea:
BufferedReader br = new BufferedReader(new FileReader(new File(path)));
JTextArea text = new JTextArea();
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
text.read(br, null);
text.print(null, null, true, defaultService, pras, true);
从包含换页符(\ f)的文件中加载JTextArea。如何在本地打印机上将这些字符用作分页符?
答案 0 :(得分:4)
public class PagedTextArea extends JTextArea implements Printable, Pageable {
JTextArea singlePageTextArea;
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (singlePageTextArea == null) {
// Copy attributes to the singlePageTextArea:
singlePageTextArea = new JTextArea();
singlePageTextArea.setBounds(getBounds());
}
String[] pages = getText().split("\f");
if (pageIndex >= pages.length) {
return Printable.NO_SUCH_PAGE;
}
singlePageTextArea.setText(pages[pageIndex]);
singlePageTextArea.printAll(graphics);
return Printable.PAGE_EXISTS;
}
@Override
public int getNumberOfPages() {
String[] pages = getText().split("\f");
return pages.length;
}
@Override
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
return new PageFormat();
}
@Override
public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
return this;
}
}
打印:
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(pagedTextArea);
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
boolean ok = job.printDialog(pras);
if (ok) {
System.out.println("Printing...");
try {
job.print();
} catch (PrinterException ex) {
System.out.println("The job did not successfully complete");
}
} else {
System.out.println("Could not print");
}
您可能希望使用PageFormat对页面的x,y执行Graphics2D.translate。
答案 1 :(得分:1)