The JavaFX Print API
This is a JavaFX Print Example. JavaFX added support for printing nodes through the Print API in thejavafx.print package. The API consists of the following classes:
- Printer
- PrinterAttributes
- PrintResolution
- PrinterJob
- JobSettings
- Paper
- PaperSource
- PageLayout
- PageRange
Instances of the above-listed classes represent different parts of the printing process. For example, aPrinter represents a printer that can be used for printing jobs. APrinterJob represents a print job that can be sent to aPrinter for printing. And aPaper represents the paper sizes available on printers.
The Print API provides support for printing nodes that may or may not be attached to a Scene Graph.
If a node is modified during the printing process, the printed node may not appear correct. Note that the printing of aNode may span multiple pulse events resulting in concurrent change in the content being printed. To ensure correct printing, please make sure that theNode being printed is not modified during the print process.
Nodes can be printed on any thread including the JavaFX Application Thread. It is recommended that large, time-consuming print jobs be submitted on a background thread to keep the UI responsive.
Classes in the Print API are final as they represent existing printing device properties. Most of them do not provide any public constructor as you cannot make up a printing device. Rather, you obtain their references using factory methods in various classes.
The following table shows an overview of the whole article:
Table Of Contents
The following examples uses Java SE 8 and JavaFX 2.2.
1. Listing Available Printers
1.1 The Code
FxPrintExample1.java
import javafx.application.Application;import javafx.collections.ObservableSet;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.Printer;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample1 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TextAreafinal TextArea textArea = new TextArea();// Create the ButtonButton button = new Button("Get all Printers");// Create the Event-Handlers for the Buttonsbutton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { //Get all Printers ObservableSet<Printer> printers = Printer.getAllPrinters(); for(Printer printer : printers) { textArea.appendText(printer.getName()+"\n"); } } });// Create the VBox with a 10px spacingVBox root = new VBox(10);// Add the Children to the VBoxroot.getChildren().addAll(button,textArea);// Set the Size of the VBoxroot.setPrefSize(400, 250);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Showing all Printers");// Display the Stagestage.show();}}ThePrinter.getAllPrinters() static method returns anObservableList of installed printers on the machine. Note that the list of printers returned by the method may change over time as new printers are installed or old printers are removed. Use thegetName() method of thePrinter to get the name of the printer.
The following snippet of code lists all installed printers on the machine running the code. You may get a different output.
//Get all PrintersObservableSet<Printer> printers = Printer.getAllPrinters();for(Printer printer : printers) {textArea.appendText(printer.getName()+"\n");}1.2 The GUI
The following GUI shows a list of all printers:

2. Getting the Default Printer
2.1 The Code
FxPrintExample2.java
import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.Printer;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample2 extends Application{public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage){// Create the TextAreafinal TextArea textArea = new TextArea();// Create the ButtonButton button = new Button("Get the Default Printer");// Create the Event-Handlers for the Buttonsbutton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { //Get the Default Printer Printer defaultprinter = Printer.getDefaultPrinter(); if (defaultprinter != null) { String name = defaultprinter.getName(); textArea.appendText("Default printer name: " + name); } else { textArea.appendText("No printers installed."); } } });// Create the VBox with a 10px spacingVBox root = new VBox(10);// Add the Children to the VBoxroot.getChildren().addAll(button,textArea);// Set the Size of the VBoxroot.setPrefSize(400, 250);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Show the default Printer");// Display the Stagestage.show();}}ThePrinter.getDefaultPrinter() method returns the defaultPrinter. The method may return null if no printer is installed. The default printer may be changed on a machine. Therefore, the method may return different printers from call to call, and the printer returned may not be valid after some time.
The following snippet of code shows how to get the defaultPrinter.
//Get the Default PrinterPrinter defaultprinter = Printer.getDefaultPrinter();if (defaultprinter != null) {String name = defaultprinter.getName();textArea.appendText("Default printer name: " + name);} else {textArea.appendText("No printers installed.");}2.2 The GUI
The following image shows the default printer. In this case, it is a CutePDF Writer.

3. Printing Nodes
3.1 The Code
FxPrintExample3.java
import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.PrinterJob;import javafx.scene.Node;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample3 extends Application{// Create the JobStatus Labelprivate Label jobStatus = new Label();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage){// Create the VBoxfinal VBox root = new VBox(5);// Create the Text LabelLabel textLabel = new Label("Please insert your Text:");// Create the TextAreafinal TextArea textArea = new TextArea();// Create the ButtonsButton printTextButton = new Button("Print Text");Button printSceneButton = new Button("Print Scene");// Create the Event-Handlers for the ButtonsprintTextButton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { print(textArea); } });printSceneButton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { print(root); } });// Create the Status BoxHBox jobStatusBox = new HBox(5, new Label("Job Status: "), jobStatus);// Create the Button BoxHBox buttonBox = new HBox(5, printTextButton, printSceneButton);// Add the Children to the VBoxroot.getChildren().addAll(textLabel, textArea, buttonBox, jobStatusBox);// Set the Size of the VBoxroot.setPrefSize(400, 300);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Printing Nodes Example");// Display the Stagestage.show();}private void print(Node node) {// Define the Job Status MessagejobStatus.textProperty().unbind();jobStatus.setText("Creating a printer job...");// Create a printer job for the default printerPrinterJob job = PrinterJob.createPrinterJob();if (job != null) {// Show the printer job statusjobStatus.textProperty().bind(job.jobStatusProperty().asString());// Print the nodeboolean printed = job.printPage(node);if (printed) {// End the printer jobjob.endJob();} else {// Write Error MessagejobStatus.textProperty().unbind();jobStatus.setText("Printing failed.");}} else {// Write Error MessagejobStatus.setText("Could not create a printer job.");}}}Printing aNode is easy. Create aPrinterJob and call itsprintPage() method passing theNode to be printed.
The details of the following code snippet will discuss in the next sentences.
// Create a printer job for the default printerPrinterJob job = PrinterJob.createPrinterJob();if (job != null) {// Show the printer job statusjobStatus.textProperty().bind(job.jobStatusProperty().asString());// Print the nodeboolean printed = job.printPage(node);if (printed) {// End the printer jobjob.endJob();} else {// Write Error MessagejobStatus.textProperty().unbind();jobStatus.setText("Printing failed.");}} else {// Write Error MessagejobStatus.setText("Could not create a printer job.");}You can use thecreatePrinterJob() static method of thePrinterJob class to create a printer job:
- public static PrinterJob createPrinterJob()
- public static PrinterJob createPrinterJob(Printer printer)
The method with no-args creates a printer job for the default printer. You can use the other version of the method to create a printer job for the specified printer.
You can change the printer for aPrinterJob by calling itssetPrinter() method. If the current printer job settings are not supported by the new printer, the settings are reset automatically for the new printer.
Setting thePrinter to null for the job will use the default printer. Use one of the followingprintPage() methods to print aNode:
- boolean printPage(Node node)
- boolean printPage(PageLayout pageLayout, Node node)
The first version of the method takes only the node to be printed as the parameter. It uses the default page layout for the job for printing.
The second version lets you specify a page layout for printing theNode. The specifiedPageLayout will override thePageLayout for the job and it will be used only for printing the specified node. For subsequent printing, the defaultPageLayout for the job will be used. You can create aPageLayout using thePrinter class.
TheprintPage() method returns true if the printing was successful. Otherwise, it returns false. When you are done printing, call theendJob() method. The method returns true if the job can be successfully spooled to the printer queue. Otherwise, it returns false, which may indicate that the job could not be spooled or it was already completed. After successful completion of the job, the job can no longer be reused.
You can cancel a print job using thecancelJob() method of thePrinterJob. The printing may not be cancelled immediately, for example, when a page is in the middle of printing. The cancellation occurs as soon as possible. The method does not have any effect if,
- The job has already been requested to be cancelled.
- The job is already completed.
- The job has an error.
APrinterJob has a read-only status, which is defined by one of the constants of thePrinterJob.JobStatus enum:
- NOT_STARTED
- PRINTING
- CANCELED
- DONE
- ERROR
TheNOT_STARTED status indicates a new job. In this status, the job can be configured and printing can be initiated. ThePRINTING status indicates that the job has requested to print at least one page and it has not terminated printing. In this status, the job cannot be configured.
The other three statuses,CANCELED,DONE, andERROR, indicate the termination state of the job. Once the job is in one of these statuses, it should not be reused. There is no need to call theendJob() method when the status goes toCANCELED orERROR. TheDONE status is entered when the printing was successful and theendJob() method was called. The PrinterJob class contains a read-onlyjobStatus property that indicates the current status of the print job.
3.2 The GUI
The GUI of the above program shows how to print nodes. It displays aTextArea where you can enter text.
Two Buttons are provided: one prints theTextArea node and the other the entireScene. When printing is initiated, the print job status is displayed in aLabel.

After pressing the PrintButton, the following dialog appears:

Now you can define the location and name of the document.
4. Showing the Page Setup
4.1 The Code
FxPrintExample4.java
import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.PrinterJob;import javafx.scene.Node;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample4 extends Application{// Create the JobStatus Labelprivate final Label jobStatus = new Label();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage){// Create the Text LabelLabel textLabel = new Label("Please insert your Text:");// Create the TextAreafinal TextArea textArea = new TextArea();// Create the ButtonsButton pageSetupButton = new Button("Page Setup and Print");// Create the Event-Handlers for the ButtonpageSetupButton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { pageSetup(textArea, stage); } });// Create the Status BoxHBox jobStatusBox = new HBox(5, new Label("Job Status: "), jobStatus);// Create the Button BoxHBox buttonBox = new HBox(pageSetupButton);// Create the VBoxVBox root = new VBox(5);// Add the Children to the VBoxroot.getChildren().addAll(textLabel, textArea, buttonBox, jobStatusBox);// Set the Size of the VBoxroot.setPrefSize(400, 300);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Printing Dialog Example");// Display the Stagestage.show();}private void pageSetup(Node node, Stage owner) {// Create the PrinterJobPrinterJob job = PrinterJob.createPrinterJob();if (job == null) {return;}// Show the page setup dialogboolean proceed = job.showPageSetupDialog(owner);if (proceed) {print(job, node);}}private void print(PrinterJob job, Node node) {// Set the Job Status MessagejobStatus.textProperty().bind(job.jobStatusProperty().asString());// Print the nodeboolean printed = job.printPage(node);if (printed) {job.endJob();}}}The Print API allows users to interact with the printing process. Users can change the printer settings interactively before the printing is initiated. The API lets you show Page Setup and Print Setup dialogs for setting the page properties and printer settings for the job.
You can let the user configure the page layout by showing a Page Setup dialog. Use theshowPageSetupDialog(Window owner) method of thePrinterJob to show a Page Setup dialog. The user can set the page size, source, orientation, and margin. The dialog may allow the user to access other printing properties such as the list of printers.
Once the user confirms the settings on the dialog, thePrinterJob has the new settings. The method returns true if the user confirms the settings on the dialog. It returns false if the user cancels the dialog. It also returns false if the dialog cannot be displayed, such as when the job is not in theNOT_STARTED state.
The owner parameter to the method is the window that will be the owner of the dialog box. It can be null. If specified, the inputs to the window will be blocked while the dialog is displayed.
The following code snippet shows how to create aPageSetupDialog:
// Create the PrinterJobPrinterJob job = PrinterJob.createPrinterJob();if (job == null) {return;}// Show the page setup dialogboolean proceed = job.showPageSetupDialog(owner);if (proceed) {print(job, node);}4.2 The GUI
The following image shows an example of the Page Setup Dialog:

After pressing on the Page Setup and PrintButton, the following dialog will appear:

Now you can define the format and other attributes.
5. Showing the Print Dialogs
5.1 The Code
FxPrintExample5.java
import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.PrinterJob;import javafx.scene.Node;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.Label;import javafx.scene.control.TextArea;import javafx.scene.layout.HBox;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample5 extends Application{// Create the JobStatus Labelprivate final Label jobStatus = new Label();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(final Stage stage){// Create the Text LabelLabel textLabel = new Label("Please insert your Text:");// Create the TextAreafinal TextArea textArea = new TextArea();// Create the ButtonsButton printSetupButton = new Button("Print Setup and Print");// Create the Event-Handlers for the ButtonprintSetupButton.setOnAction(new EventHandler () { public void handle(ActionEvent event) { printSetup(textArea, stage); } });// Create the Status BoxHBox jobStatusBox = new HBox(5, new Label("Job Status: "), jobStatus);// Create the Button BoxHBox buttonBox = new HBox(printSetupButton);// Create the VBoxVBox root = new VBox(5);// Add the Children to the VBoxroot.getChildren().addAll(textLabel, textArea, buttonBox, jobStatusBox);// Set the Size of the VBoxroot.setPrefSize(400, 300);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("A Printing Dialog Example");// Display the Stagestage.show();}private void printSetup(Node node, Stage owner) {// Create the PrinterJobPrinterJob job = PrinterJob.createPrinterJob();if (job == null) {return;}// Show the print setup dialogboolean proceed = job.showPrintDialog(owner);if (proceed) {print(job, node);}}private void print(PrinterJob job, Node node) {// Set the Job Status MessagejobStatus.textProperty().bind(job.jobStatusProperty().asString());// Print the nodeboolean printed = job.printPage(node);if (printed) {job.endJob();}}}You can use theshowPrintDialog(Window owner) method to show a Print dialog where the user can modify the printer and settings for thePrinterJob. The return value and parameter of this method have meanings similar to that of theshowPageSetupDialog() method.

Thank you!
We will contact you soon.
The following code snippet shows how to create a Print Dialog:
// Create the PrinterJobPrinterJob job = PrinterJob.createPrinterJob();if (job == null) {return;}// Show the print setup dialogboolean proceed = job.showPrintDialog(owner);if (proceed) {print(job, node);}5.2 The GUI
The following image shows an example of the Print Setup Dialog:

After pressing on the Print Setup and PrintButton, the following dialog will appear:

Now you can define the printer, pages and other attributes.
6. Customizing PrinterJob Settings
6.1 The Code
FxPrintExample6.java
import java.util.Set;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.print.Collation;import javafx.print.JobSettings;import javafx.print.PageOrientation;import javafx.print.PrintSides;import javafx.print.Printer;import javafx.print.PrinterAttributes;import javafx.print.PrinterJob;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.VBox;import javafx.stage.Stage;public class FxPrintExample6 extends Application{// Create the TextAreafinal TextArea textArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage){// Create the ButtonButton button = new Button("Get all Printer Attributes");// Create the Event-Handlers for the Buttonsbutton.setOnAction(new EventHandler <ActionEvent>() { public void handle(ActionEvent event) { printAttributes(); } });// Create the VBox with a 10px spacingVBox root = new VBox(10);// Add the Children to the VBoxroot.getChildren().addAll(button, textArea);// Set the Size of the VBoxroot.setPrefSize(400, 250);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Showing all Printer Attributes");// Display the Stagestage.show();}private void printAttributes(){// Get the Default PrinterPrinter printer = Printer.getDefaultPrinter();// Get the Printer AttributesPrinterAttributes attribs = printer.getPrinterAttributes();// Read some printer attributesint maxCopies = attribs.getMaxCopies();PrintSides printSides = attribs.getDefaultPrintSides();Set<PageOrientation> orientations = attribs.getSupportedPageOrientations();Set<Collation> collations = attribs.getSupportedCollations();// Print the printer attributestextArea.appendText("Max. Copies: " + maxCopies + "\n");textArea.appendText("Print Sides: " + printSides + "\n");textArea.appendText("Supported Orientation: " + orientations + "\n");textArea.appendText("Supported Collations: " + collations + "\n");// Create a printer job for the default printerPrinterJob job = PrinterJob.createPrinterJob();// Get the JobSettings for the print jobJobSettings jobSettings = job.getJobSettings();// Print the printer attributestextArea.appendText("Print Sides: " + jobSettings.getPrintSides() + "\n");// Set the printSides to DUPLEXjobSettings.setPrintSides(PrintSides.DUPLEX);// Print the printer attributestextArea.appendText("Print Sides: " + jobSettings.getPrintSides() + "\n");}}The Print API contains two classes that are related to printer and printer job settings:
- PrinterAttributes
- JobSettings
APrinter has attributes, which indicate the printing capabilities of the printer. Examples of printer attributes are default paper size, supported paper sizes, maximum number of copies, and default collation.
APrinterAttributes object encapsulates the attributes of aPrinter. The Print API does not let you change the printer attributes as you cannot change the capabilities of a printer. You can only use its capabilities.
You cannot create aPrinterAttributes object directly. You need to get it from aPrinter object using thegetPrinterAttributes() method.
The following snippet of code prints some attributes of the default printer in the machine: You may get a different output.
// Get the Default PrinterPrinter printer = Printer.getDefaultPrinter();// Get the Printer AttributesPrinterAttributes attribs = printer.getPrinterAttributes();// Read some printer attributesint maxCopies = attribs.getMaxCopies();PrintSides printSides = attribs.getDefaultPrintSides();Set<PageOrientation> orientations = attribs.getSupportedPageOrientations();Set<Collation> collations = attribs.getSupportedCollations();// Print the printer attributestextArea.appendText("Max. Copies: " + maxCopies + "\n");textArea.appendText("Print Sides: " + printSides + "\n");textArea.appendText("Supported Orientation: " + orientations + "\n");textArea.appendText("Supported Collations: " + collations + "\n");AJobSettings contains the printer attributes to be used for a print job for a specific printer. You can obtain theJobSettings of a print job using thegetJobSettings() method of thePrinterJob object. AJobSettings is a mutable object. It contains a property for each printer attribute that can be set for a print job. By default, its properties are initialized to the default properties of the printer. You can change the property that will be used for the current print job. If you change the property of aJobSettings that is not supported by the printer, the property reverts to the default value for the printer.
The following snippet of code sets theprintSides property toDUPLEX. In this case, the printer supports onlyONE_SIDED printing.
Therefore, theprintSides property is set toONE_SIDED, which is the default, and only supportedprintSides value by the printer. You may get a different output.
// Create a printer job for the default printerPrinterJob job = PrinterJob.createPrinterJob();// Get the JobSettings for the print jobJobSettings jobSettings = job.getJobSettings();// Print the printer attributestextArea.appendText("Print Sides: " + jobSettings.getPrintSides() + "\n");// Set the printSides to DUPLEXjobSettings.setPrintSides(PrintSides.DUPLEX);// Print the printer attributestextArea.appendText("Print Sides: " + jobSettings.getPrintSides() + "\n");For a print job, you can specify the page ranges using thepageRanges property of theJobSettings.
The pageRanges property is an array ofPageRange. APageRange hasstartPage andendPage properties that define the range.
6.2 The GUI
The following image shows an example how to get thePrinter attributes:

7. Setting Page Layout
7.1 The Code
FxPrintExample7.java
import javafx.print.JobSettings;import javafx.print.PageLayout;import javafx.print.PageOrientation;import javafx.print.Paper;import javafx.print.Printer;import javafx.print.PrinterJob;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextArea;import javafx.scene.layout.VBox;import javafx.application.Application;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.stage.Stage;public class FxPrintExample7 extends Application{// Create the TextAreafinal TextArea textArea = new TextArea();public static void main(String[] args) {Application.launch(args);}@Overridepublic void start(Stage stage){// Create the ButtonButton button = new Button("Get all Page Attributes");// Create the Event-Handlers for the Buttonsbutton.setOnAction(new EventHandler () { public void handle(ActionEvent event) { printAttributes(); } });// Create the VBox with a 10px spacingVBox root = new VBox(10);// Add the Children to the VBoxroot.getChildren().addAll(button, textArea);// Set the Size of the VBoxroot.setPrefSize(400, 250);// Set the Style-properties of the VBoxroot.setStyle("-fx-padding: 10;" +"-fx-border-style: solid inside;" +"-fx-border-width: 2;" +"-fx-border-insets: 5;" +"-fx-border-radius: 5;" +"-fx-border-color: blue;");// Create the SceneScene scene = new Scene(root);// Add the scene to the Stagestage.setScene(scene);// Set the title of the Stagestage.setTitle("Showing all Page Layout Attributes");// Display the Stagestage.show();}private void printAttributes(){// Create the Printer JobPrinterJob printerJob = PrinterJob.createPrinterJob();// Get The Printer Job SettingsJobSettings jobSettings = printerJob.getJobSettings();// Get the Page LayoutPageLayout pageLayout = jobSettings.getPageLayout();// Get the Page Attributesdouble pgW = pageLayout.getPrintableWidth();double pgH = pageLayout.getPrintableHeight();double pgLM = pageLayout.getLeftMargin();double pgRM = pageLayout.getRightMargin();double pgTM = pageLayout.getTopMargin();double pgBM = pageLayout.getBottomMargin();// Show the Page AttributestextArea.appendText("Printable Width: " + pgW + "\n");textArea.appendText("Printable Height: " + pgH + "\n");textArea.appendText("Page Left Margin: " + pgLM + "\n");textArea.appendText("Page Right Margin: " + pgRM + "\n");textArea.appendText("Page Top Margin: " + pgTM + "\n");textArea.appendText("Page Bottom Margin: " + pgBM + "\n");// Get The PrinterPrinter printer = printerJob.getPrinter();// Create the Page Layout of the PrinterpageLayout = printer.createPageLayout(Paper.A4,PageOrientation.LANDSCAPE,Printer.MarginType.EQUAL);jobSettings.setPageLayout(pageLayout);// Get the Page AttributespgW = pageLayout.getPrintableWidth();pgH = pageLayout.getPrintableHeight();pgLM = pageLayout.getLeftMargin();pgRM = pageLayout.getRightMargin();pgTM = pageLayout.getTopMargin();pgBM = pageLayout.getBottomMargin();// Show the Page AttributestextArea.appendText("Printable Width: " + pgW + "\n");textArea.appendText("Printable Height: " + pgH + "\n");textArea.appendText("Page Left Margin: " + pgLM + "\n");textArea.appendText("Page Right Margin: " + pgRM + "\n");textArea.appendText("Page Top Margin: " + pgTM + "\n");textArea.appendText("Page Bottom Margin: " + pgBM + "\n");}}An instance of thePageLayout class represents the page setup for a print job. By default, it is set to the printer default value. You have already seen setting up the page layout using the Page Setup dialog. APageLayout encapsulates three things:
- The paper size
- The page orientation
- The page margins
APageLayout is used to configure the printable area of the page, which must lie within the printable area of the hardware. If a page is rendered outside the printable area of the hardware, the content is clipped. You cannot create aPageLayout object directly. You need to use one of thecreatePageLayout() methods of thePrinter to get aPageLayout.
- PageLayout createPageLayout(Paper paper, PageOrientation orient, double lMargin, double rMargin, double tMargin, double bMargin)
- PageLayout createPageLayout(Paper paper, PageOrientation orient, Printer.MarginType mType)
The margins can be specified as numbers or as one of the following constants of thePrinter.MarginType enum.
- DEFAULT
- EQUAL
- EQUAL_OPPOSITES
- HARDWARE_MINIMUM
TheDEFAULT margin type requests default 0.75 inch on all sides.
TheEQUAL margin type uses the largest of the four hardware margins on all four sides, so the margins are equal on all four sides.
TheEQUAL_OPPOSITES margin type uses the larger of left and right hardware margins for the left and right sides, and the larger of the top and bottom hardware margins for the top and bottom sides.
TheHARDWARE_MINIMUM requests that the minimum hardware allowed margins should be set on all sides.
The following snippet of code creates aPageLayout for A4 size paper,LANDSCAPE page orientation, and equal margins on all sides. ThePageLayout is set to a print job.
// Get The PrinterPrinter printer = printerJob.getPrinter();// Create the Page Layout of the PrinterpageLayout = printer.createPageLayout(Paper.A4,PageOrientation.LANDSCAPE,Printer.MarginType.EQUAL);jobSettings.setPageLayout(pageLayout);// Get the Page AttributespgW = pageLayout.getPrintableWidth();pgH = pageLayout.getPrintableHeight();pgLM = pageLayout.getLeftMargin();pgRM = pageLayout.getRightMargin();pgTM = pageLayout.getTopMargin();pgBM = pageLayout.getBottomMargin();
Sometimes, you want to know the size of the printable area on the page. You can get it using thegetPrintableWidth() andgetPrintableHeight() methods of thePageLayout. This is useful if you want to resize a node before printing, so it fits the printable area.
// Create the Printer JobPrinterJob printerJob = PrinterJob.createPrinterJob();// Get The Printer Job SettingsJobSettings jobSettings = printerJob.getJobSettings();// Get the Page LayoutPageLayout pageLayout = jobSettings.getPageLayout();// Get the Page Attributesdouble pgW = pageLayout.getPrintableWidth();double pgH = pageLayout.getPrintableHeight();double pgLM = pageLayout.getLeftMargin();double pgRM = pageLayout.getRightMargin();double pgTM = pageLayout.getTopMargin();double pgBM = pageLayout.getBottomMargin();// Show the Page AttributestextArea.appendText("Printable Width: " + pgW + "\n");textArea.appendText("Printable Height: " + pgH + "\n");textArea.appendText("Page Left Margin: " + pgLM + "\n");textArea.appendText("Page Right Margin: " + pgRM + "\n");textArea.appendText("Page Top Margin: " + pgTM + "\n");textArea.appendText("Page Bottom Margin: " + pgBM + "\n");7.2 The GUI
The following image shows an example how to get the page attributes:

8. Download Java Source Code
This was an example ofjavafx.print
You can download the full source code of this example here:JavaFxPrintExample.zip

Thank you!
We will contact you soon.




