Of course! Here is a comprehensive guide on using PageOffice in a Java project.
What is PageOffice?
PageOffice is a commercial, server-side component designed to integrate Microsoft Office (Word, Excel, PowerPoint) directly into a web browser. It allows users to view, edit, and save Office documents without needing to have Microsoft Office installed on their client machines.
Key features include:
- In-Browser Editing: Open and edit Office docs directly in the browser.
- No Client Installation: Requires only a small, one-time browser plugin (ActiveX for IE, a standard browser component for modern browsers).
- Server-Side Control: All document operations (data filling, merging, printing, saving) are controlled by your Java server code.
- Security: Documents are processed on the server, keeping sensitive data off the client machine.
- Data Binding: Seamlessly bind data from your Java application (e.g., from a database) into Word templates.
Core Concepts
Before diving into code, it's important to understand the main components PageOffice uses:
PageOfficeCtrl(The Control Object): This is the Java object you instantiate on your server. It represents the document editor that will be embedded in the web page. You configure it (e.g., set the document path, add toolbars) and then pass it to the JSP page.DocumentOpenEvent(Event Handling): This is a crucial interface. You implement it to handle events that occur when the user interacts with the document, most importantly theOnSaveevent. This is where you get the document data after the user clicks "Save" and process it on the server.POBrowser(JavaScript Utility): A small JavaScript library that helps open documents in a new browser window or tab, which is often necessary for compatibility and to avoid page layout issues.
Step-by-Step Integration Guide (using JSP)
Let's walk through a complete example of how to create a simple Word document editor.
Step 1: Get PageOffice and Add Dependencies
- Download: Obtain the PageOffice for Java package from the official website (e.g., www.zhuozhengsoft.com).
- Add JARs: You will need to add the following JAR files to your project's
WEB-INF/libdirectory:pageoffice.jar: The core PageOffice library.pojava.jar: Supporting Java utilities.- (Optional, for database support)
poi-ooxml.jar,poi.jar: For handling Office file formats.
Step 2: Configure web.xml
You must register a servlet in your web.xml file. This servlet handles the communication between the browser plugin and your Java server.
<!-- web.xml -->
<web-app>
...
<!-- PageOffice Servlet -->
<servlet>
<servlet-name>poserver</servlet-name>
<servlet-class>com.zhuozhengsoft.pageoffice.poserver.Server</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>poserver</servlet-name>
<url-pattern>/poserver.zz</url-pattern>
</servlet-mapping>
<!-- License File Servlet (Required for commercial use) -->
<servlet>
<servlet-name>license</servlet-name>
<servlet-class>com.zhuozhengsoft.pageoffice.poserver.LicenseServer</servlet-class>
<init-param>
<param-name>license</param-name>
<param-value>YOUR_LICENSE_KEY_STRING</param-value> <!-- Replace with your license -->
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>license</servlet-name>
<url-pattern>/license.zz</url-pattern>
</servlet-mapping>
...
</web-app>
Note: Replace YOUR_LICENSE_KEY_STRING with the actual license key provided by PageOffice. A developer license is often available for trial.
Step 3: Create the JSP Page for Editing
This JSP page will contain the PageOfficeCtrl object. Place your documents in a folder accessible by your web application (e.g., doc).
<%@ page language="java" import="com.zhuozhengsoft.pageoffice.*" %>
<%
// 1. Create a PageOfficeCtrl object
PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
// 2. Set the document path
// The path is relative to the web application's root.
poCtrl.setServerPage("poserver.zz"); // Must match the servlet mapping
poCtrl.setJsFile("pageoffice.js"); // Include the JS utility file
poCtrl.webOpen("doc/Contract.docx", OpenModeType.docNormalEdit, "John Doe");
%>
<!DOCTYPE html>
<html>
<head>PageOffice Document Editor</title>
<script type="text/javascript" src="pageoffice.js"></script>
</head>
<body>
<h1>Edit Document</h1>
<p>Use the toolbar in the document to edit, save, or print.</p>
<!-- 3. Embed the PageOffice control -->
<%=poCtrl.getHtmlCode("PageOfficeCtrl1") %>
</body>
</html>
Step 4: Handle the Save Event (The Most Important Part)
When the user clicks "Save" in the document, the browser sends the data back to your server. You need a servlet to handle this. This is where you implement the DocumentOpenEvent interface.
Create a Java Servlet (e.g., SaveDocumentServlet.java):
import com.zhuozhengsoft.pageoffice.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SaveDocumentServlet extends HttpServlet implements DocumentOpenEvent {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. Create a PageOfficeCtrl object from the request
PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
// 2. Register the event handler
poCtrl.setDocumentOpenEvent(this);
// 3. Open the document in edit mode
poCtrl.webOpen("doc/Contract.docx", OpenModeType.docNormalEdit, "John Doe");
}
// This method is called when the document is saved
@Override
public void OnSave(Document document) {
try {
// 4. Get the saved document data
// The data is in a byte array
byte[] docData = document.getDocumentContent();
// 5. Process the saved data
// For example, save it to a new file on the server
String outputFileName = "C:\\saved_documents\\Contract_" + System.currentTimeMillis() + ".docx";
FileOutputStream fos = new FileOutputStream(outputFileName);
fos.write(docData);
fos.close();
System.out.println("Document saved successfully to: " + outputFileName);
// 6. (Optional) Show a message to the user
// You can use a custom alert by setting a property
document.setCustomAlert("Document has been saved to the server!");
} catch (Exception e) {
e.printStackTrace();
document.setCustomAlert("Error saving document: " + e.getMessage());
}
}
}
Register the new servlet in web.xml:
<!-- web.xml -->
...
<servlet>
<servlet-name>SaveDocument</servlet-name>
<servlet-class>SaveDocumentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SaveDocument</servlet-name>
<url-pattern>/SaveDocument</url-pattern>
</servlet-mapping>
...
Update your JSP to use the servlet:
Modify the JSP from Step 3 to open the document via your new servlet instead of directly.
<!-- In your JSP file -->
<%
// ...
// poCtrl.webOpen("doc/Contract.docx", ...); // REMOVE THIS LINE
// Instead, set the servlet path
poCtrl.setServerPage("poserver.zz");
poCtrl.setJsFile("pageoffice.js");
// The URL pattern of your servlet
poCtrl.webOpen("/SaveDocument", OpenModeType.docNormalEdit, "John Doe");
%>
Common Use Cases
Filling Data into a Word Template (Mail Merge)
This is a very powerful feature. You create a Word template with bookmarks, and your Java code fills them with data.
Word Template (Template.docx):
- Create bookmarks in Word (Insert -> Bookmark) named
customerName,orderDate,totalAmount.
Java Code (in your servlet or event handler):
// In the OnSave method or wherever you prepare the document
public void OnSave(Document document) {
try {
// Get the WordDocument object
WordDocument doc = new WordDocument();
doc.setDocument(document); // Attach to the current document
// Fill the bookmarks with data
doc.openDataRegion("customerName").setValue("Acme Corporation");
doc.openDataRegion("orderDate").setValue(new java.util.Date().toString());
doc.openDataRegion("totalAmount").setValue("$1,250.50");
// The document is now in memory with the data filled.
// You can save it, or the user can continue editing and save it later.
} catch (Exception e) {
e.printStackTrace();
}
}
Protecting Document Content
You can restrict what the user can edit in the document.
// In your servlet before webOpen()
PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
poCtrl.setServerPage("poserver.zz");
// Allow editing only within a specific bookmark
poCtrl.setAllowCopy(false); // Disallow copying
poCtrl.setAllowPrint(false); // Disallow printing
// Protect the document, allowing edits only in the "editableContent" bookmark
poCtrl.wordProtect("editableContent");
Advantages and Disadvantages
| Advantages | Disadvantages |
|---|---|
| True Office Experience: Users get the full, familiar Office UI. | Cost: It's a commercial product with licensing fees. |
| Powerful Server-Side Logic: Full control over document processing. | Plugin Dependency: Requires a small client-side component (though very lightweight). |
| Excellent for Complex Forms: Ideal for templates with data binding. | Learning Curve: Requires understanding its specific event model and API. |
| Security: Sensitive data never leaves the server. | Vendor Lock-in: Ties your application to the PageOffice ecosystem. |
Alternatives
- OnlyOffice / Document Server: An open-source alternative with similar functionality. It has its own document server that you need to deploy and manage.
- LibreOffice Online: Another open-source option, often part of larger collaboration suites (Nextcloud, ownCloud).
- Client-Side Libraries (e.g., docx.js, SheetJS): These are purely JavaScript libraries for manipulating document data in the browser. They don't provide a full editor UI and are more for data extraction or simple generation. They are free but lack the power and ease of use of a server-side solution like PageOffice.
For a professional Java application that requires robust, in-browser Office editing with tight server integration, PageOffice is a very strong and mature solution, despite its cost.
