我的桌面视图无法放在一个页面上,但是当我打印它时,只打印一页。我应该怎么做以使表格的其余部分打印在其他页面上?
下面的示例代码填充了50行的表视图并打印出来(我使用foxit作为pdf打印机,根据需要进行修改)。输出pdf只包含一个以第30行结束的页面,尽管TableView显示的行数超过45行。
public class FXPrint extends Application {
public static void main(String[] args) { launch(FXPrint.class); }
@Override
public void start(Stage stage) throws Exception {
TableView<String> table = new TableView<>();
for (int i = 0; i < 25; i++) {
TableColumn<String, String> tc = new TableColumn<>("" + i);
int index = i;
tc.setCellValueFactory(param -> {
String s = param.getValue();
if (s.length() <= index) return new SimpleStringProperty();
else return new SimpleStringProperty(s.substring(index, index + 1));
});
table.getColumns().add(tc);
}
for (int i = 0; i < 50; i++) table.getItems().add(i + "sdfghjklrthyjkcasdghasfdsfgdfgsdfggfdg");
Button print = new Button("print");
print.setOnAction(e -> print(table));
VBox box = new VBox(10, table, print);
VBox.setVgrow(table, Priority.ALWAYS);
stage.setScene(new Scene(box));
stage.setWidth(600);
stage.setHeight(1200);
stage.show();
}
public void print(final TableView<?> table) {
Printer printer = Printer.getAllPrinters().stream().filter(p -> p.getName().contains("Foxit")).findAny().get();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
PrinterJob job = PrinterJob.createPrinterJob(printer);
if (job != null) {
job.getJobSettings().setPageLayout(pageLayout);
if (job.printPage(table)) {
job.endJob();
}
}
}
}
答案 0 :(得分:3)
您应该根据可打印区域的高度和行的高度在多个节点上拆分TableView。然后为所有节点调用job.PrintPage,并调用job.endJob。 这是我的多页打印方法:
public static List<Node> getLineRecordPages(Collection<LineRecord> lineRecords, PageLayout layout) {
LinkedList<Node> result = new LinkedList<>();
VBox node = null;
double totalHeight = Double.POSITIVE_INFINITY;
for (LineRecord record : lineRecords) {
PrintLineRecordView view = new PrintLineRecordView();
final PrintLineRecordPresenter presenter = (PrintLineRecordPresenter) view.getPresenter();
presenter.bind(record);
final double elementHeight = view.getView().prefHeight(layout.getPrintableWidth());
if (elementHeight + totalHeight > layout.getPrintableHeight()) {
node = new VBox();
node.setMaxWidth(layout.getPrintableWidth());
result.add(node);
totalHeight = 0;
}
totalHeight+=elementHeight;
if (node != null) {
node.getChildren().add(view.getView());
}
}
return result;
}
并实际将页面发送到打印作业:
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout = printer.getDefaultPageLayout();
PrinterJob printerJob = PrinterJob.createPrinterJob(printer);
final List<Node> pages = Formatter.getLineRecordPages(lineRecords, pageLayout);
final boolean print = printerJob.showPrintDialog(null);
if (print) {
pages.forEach(printerJob::printPage);
printerJob.endJob();
}