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.


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;

public class ConvertWordToPasswordProtectedPDF {
    public static void main(String[] args){

        //Create a Document instance
        Document document = new Document(false);
        //Load a Word document

        //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.