Automatically printing a document

Open the document you wish to change

In this tutorial, we will show how to change a PDF document so that a print dialog appears once the user opens the document.

While this feature can be useful if you wish to help users print their document, it also allows the addition of an actionto a document and ensures that this action is activated as soon as the document is opened.

Create the PDF action

We will now create a Named action that will call the "print" functionality of the application used to show the PDF document.

// Open the document:
PdfDocument doc = new PdfDocument("MyDocument.pdf"); 

// Create the action:
NamedAction action = NamedAction.createInstance(doc); 

// Register the string "Print" which is used traditionaly by a PDF viewer
// application to call its printing facility:
action.setName("Print");

Apply and save the document

Finally, we will add the action to the document and save the result in a new file.

// Register the action
doc.addOpenAction(action); 

// Save the modified document to a new location:
doc.saveAs("generatedDocument.pdf");
doc.close();