How do I print only text?

て烟熏妆下的殇ゞ 提交于 2019-12-30 10:04:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!