During the conversion of a Word document to PDF, we may want to encrypt the PDF document to prevent unauthorized viewing. In this article, I will introduce how to achieve this task programmatically using Java.
Add Dependencies
To implement the conversion, I will be using Spire.Doc for Java, which is a powerful and easy-to-use API for creating, reading, editing, and converting Word documents.
You can either download the API’s jar from this link or install it from Maven by adding the following code to your maven-based project’s pom.xml file.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc</artifactId>
<version>4.10.9</version>
</dependency>
</dependencies>
Convert Word to Password-Protected PDF
Spire.Doc for Java allows developers to convert Word documents to password-protected PDF documents by using the Document.saveToFile(String, ToPdfParameterList) method. The ToPdfParameterList parameter controls how a Word document will be converted to PDF, for example, whether to encrypt the result PDF during the conversion.
1. Create a Document instance.
2. Load a Word document using Document.loadFromFile() method.
3. Create a ToPdfParameterList instance.
4. Set open password and permission password for PDF using ToPdfParameterList.getPdfSecurity().encrypt() method.
5. Save the Word document to PDF with password using Document.saveToFile(String, ToPdfParameterList) method.
import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;
import com.spire.pdf.security.PdfEncryptionKeySize;
import com.spire.pdf.security.PdfPermissionsFlags;
public class ConvertWordToPasswordProtectedPDF {
public static void main(String[] args){
//Create a Document instance
Document document = new Document();
//Load a Word document
document.loadFromFile("Sample.docx");
//Create a ToPdfParameterList instance
ToPdfParameterList toPdf = new ToPdfParameterList();
//Set open password and permission password for PDF
String password = "password";
toPdf.getPdfSecurity().encrypt(password, password, PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_128_Bit);
//Save the Word document to PDF with password
document.saveToFile("ToPdfWithPassword.pdf", toPdf);
}
}
Output:
![](https://officedevblogs805426550.wordpress.com/wp-content/uploads/2021/10/wordtopasswordprotectedpdf.png?w=544)