Java: 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 document while converting.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.10.3</version>
    </dependency>
</dependencies>
    

Convert Word to Password-Protected PDF

The following are the steps to convert a Word document to password-protected PDF:

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Create a ToPdfParameterList instance.
  • Set open password and permission password for PDF using ToPdfParameterList.getPdfSecurity().encrypt() method.
  • Save the Word document to PDF with password using Document.saveToFile(String, ToPdfParameterList) method.
  • Java
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(false);
        //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);
    }
}

Java: Convert Word to Password-Protected PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.