问题
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
}
}
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.
回答1:
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");
}
}
Notice that the TextFlow's maxWidth needs to be set using the PrinterJob's page layout, after the print dialog has been shown.
来源:https://stackoverflow.com/questions/36555291/how-do-i-print-only-text