This article demonstrates how to secure Word documents by applying password portection using the Spire.Cloud.Word API. We will cover the steps from obtaining API credentials to encrypting a document and viewing the result.
Setup
-
Account and Application Registration:
- Register for an account on the Spire.Cloud website (https://cloud.e-iceblue.cn/).
- Log in and navigate to the 'My Applications' section to create a new application. This will provide you with your unique App ID and App Key.
-
Document Upload:
- Access the 'Document Management' section on the Spire.Cloud website.
- For better organization, create two folders:
inputandoutput. Upload the Word document you intend to encrypt into theinputfolder. Theoutputfolder will be used to store the encrypted document.
-
Project Setup (Maven):
- Create a new Maven project.
- Add the Spire.Cloud.SDK JAR package and its dependencies to your project's
pom.xmlfile. The following XML snippet includes the necessary configurations:
Encrypting the Document
Create a new Java class to utilize the Spire.Cloud.Word API for password-protecting the document located in the input folder.
Java Code:
import spire.cloud.word.sdk.client.*;
import spire.cloud.word.sdk.client.api.EncryptApi;
public class DocumentEncryption {
// Replace with your actual App ID and App Key
private static final String API_APP_ID = "YOUR_APP_ID";
private static final String API_APP_KEY = "YOUR_APP_KEY";
private static final String API_BASE_URL = "https://api.e-iceblue.cn";
public static void main(String[] args) {
// Initialize API configuration
Configuration apiConfig = new Configuration(API_APP_ID, API_APP_KEY);
EncryptApi encryptor = new EncryptApi(apiConfig);
// Document details
String sourceFileName = "sample.docx";
String inputFolder = "input";
String outputFileName = "encrypted_document.docx";
String targetStorage = null; // Use default storage
String oldPassword = null; // No existing password
String newPassword = "securePassword123"; // New password for encryption
String destinationPath = "output/" + outputFileName;
try {
// Call the API to encrypt the document
encryptor.encryptDocument(
sourceFileName,
destinationPath,
inputFolder,
targetStorage,
oldPassword,
newPassword
);
System.out.println("Document successfully encrypted and saved to " + destinationPath);
} catch (ApiException e) {
System.err.println("Error encrypting document: " + e.getMessage());
e.printStackTrace();
}
}
}
After execution, the specified Word document will be encrypted with the proivded password. You can then use the Spire.Cloud online editor to open and verify the encrypted document.