DEV Community


Posted on • Updated on

Convert Word to Password-Protected PDF in Java

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.

Enter fullscreen mode Exit fullscreen mode

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;

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

        //Create a Document instance
        Document document = new Document();
        //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);
Enter fullscreen mode Exit fullscreen mode


Discussion (0)