gpt4 book ai didi

java - 打印 JTextArea 换页字符作为分页符

转载 作者:行者123 更新时间:2023-11-29 08:09:53 25 4
gpt4 key购买 nike

我正在尝试使用 Java 打印服务 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);

JTextArea 是从包含换页字符 (\f) 的文件加载的。如何让这些字符在我的本地打印机上充当分页符?

最佳答案

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。

关于java - 打印 JTextArea 换页字符作为分页符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com