Convert Word to Password-Protected PDF in Java

·

2 min read

When editing a contract or legal document in MS Word, you may need to convert it to PDF for better transfer or printing. And for some highly confidential documents, if you want to prevent them from being snoopied from others, you can also encrypt the document to ensure that only the designated people can access these documents. This article will show you how to directly convert a Word document to password-protected PDF using a free Java API.

Import Dependency

Method 1: Download the free API (Free Spire.Doc for Java) and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<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.free</artifactId>
      <version>5.2.0</version>
   </dependency>
</dependencies>

Sample Code

To accomplish this task, you'll need to create a ToPdfParameterList instance, and then use the ToPdfParameterList.getPdfSecurity().encrypt() method to set open password and permission password for the converted PDF document. Finally, you can 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("E:\\Files\\test.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);
    }
}

passwordPDF.png