如何仅打印文本? [英] How do I print only text?
问题描述
我正在尝试将一些文本发送到打印机。我只需要打印的文本,包裹在页边距并在必要时流向另一页。
I am trying to send some text to a printer. I need just the text printed, wrapped at the page margin and flowing to another page if necessary.
以下是我现在正在做的最小例子:
Here is a minimal example of what I am doing now:
@FXML
private void print() {
TextArea printArea = new TextArea(textArea.getText());
printArea.setWrapText(true);
printArea.getChildrenUnmodifiable().forEach(node -> node.setStyle("-fx-background-color: transparent"));
printArea.setStyle("-fx-background-color: transparent");
PrinterJob printerJob = PrinterJob.createPrinterJob();
if (printerJob != null && printerJob.showPrintDialog(textArea.getScene().getWindow())) {
if (printerJob.printPage(printArea)) {
printerJob.endJob();
// done printing
} else {
// failed to print
}
} else {
// failed to get printer job or failed to show print dialog
}
}
最终打印的是灰色背景这似乎是控件本身,以及滚动条。我接近这个错误的方式了吗?我觉得我通过调整和打印控件而不是仅仅发送要打印的文本来对抗API。
What ends up printing is a gray background that seems to be the control itself, along with the scrollbar. Am I approaching this the wrong way? I feel like I'm fighting against the API by tweaking and printing a control instead of just sending the text to be printed.
下面的示例图片来自我的单元格手机相机,所以白纸看起来有点浅灰色,但你仍然可以看到控件和滚动条的灰色背景。
The example image below was taken from my cell phone camera, so the white paper ends up looking a bit light-gray, but you can still see the gray background from the control and the scrollbar.
推荐答案
而不是TextArea,打印 TextFlow :
Instead of a TextArea, print a TextFlow:
private void print() {
TextFlow printArea = new TextFlow(new Text(textArea.getText()));
PrinterJob printerJob = PrinterJob.createPrinterJob();
if (printerJob != null && printerJob.showPrintDialog(textArea.getScene().getWindow())) {
PageLayout pageLayout = printerJob.getJobSettings().getPageLayout();
printArea.setMaxWidth(pageLayout.getPrintableWidth());
if (printerJob.printPage(printArea)) {
printerJob.endJob();
// done printing
} else {
System.out.println("Failed to print");
}
} else {
System.out.println("Canceled");
}
}
请注意,TextFlow的maxWidth需要使用打印对话框显示后,PrinterJob的页面布局。
Notice that the TextFlow's maxWidth needs to be set using the PrinterJob's page layout, after the print dialog has been shown.
这篇关于如何仅打印文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!