When working with PDF documents in Java applications, you often need to customize how the document will appear when opened in a viewer. These preferences can include window positioning, UI element visibility, page layout, and display modes. This article demonstrates how to implement these viewer preferences using the Free Spire.PDF for Java library.
Library Integration
Option 1: Download the Free Spire.PDF for Java package and extract it. Then add the Spire.Pdf.jar file from the lib folder as a dependency to your Java project.
Option 2: Install the JAR package directly through Maven repository by configuring your pom.xml file as follows:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>2.6.3</version>
</dependency>
</dependencies>
Ipmlementation Example:
import com.spire.pdf.*;
public class CustomizePdfViewer {
public static void main(String[] args) {
// Initialize PDF document object
PdfDocument document = new PdfDocument();
// Load source PDF file
document.loadFromFile("sample.pdf");
// Access viewer preferences settings
PdfViewerPreferences preferences = document.getViewerPreferences();
// Configure window position and display options
preferences.setCenterWindow(true); // Center the viewer window
preferences.setDisplayTitle(false); // Hide document title
preferences.setFitWindow(true); // Resize to fit window
preferences.setHideMenubar(true); // Hide menu bar
preferences.setHideToolbar(true); // Hide toolbar
// Set page layout to two columns
preferences.setPageLayout(PdfPageLayout.Two_Column_Left);
// Optional: Uncomment below lines for additional settings
// preferences.setPageMode(PdfPageMode.Full_Screen); // Full screen mode
// preferences.setPrintScaling(PrintScalingMode.App_Default); // Print scaling
// Save the modified document
document.saveToFile("CustomizedViewer.pdf");
// Clean up resources
document.close();
}
}
The code above demonstrates how to programmatically control various PDF viewer settinsg to create a customized viewing experience for end users.