Java: Convert Word to PDF

Transforming a Microsoft Word file into a portable PDF format is a versatile skill with numerous benefits. PDFs maintain the original document's visual integrity, ensuring your work appears consistent across devices and platforms. Meanwhile, the conversion process offers enhanced security, as PDFs are less vulnerable to unauthorized editing compared to editable Word documents.

This article presents a collection of code examples that showcase how to convert Word documents to PDF format in Java using Spire.Doc for Java. In addition to the core conversion process, the examples also demonstrate how to configure various options to customize the resulting PDF output.

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.11.0</version>
    </dependency>
</dependencies>
    

Convert Word to PDF in Java

Converting a Word document to PDF without specifying any customization options can be achieved by first loading the document using the Document.loadFromFile() method, and then saving it as a PDF file using the Document.saveToFile() method.

The steps to convert Word to PDF using Java are as follows.

  • Create a Document object.
  • Load a Word document using Document.loadFromFile() method.
  • Save the document to PDF using Doucment.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class ConvertWordToPdf {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Save the document to PDF
        doc.saveToFile("ToPDF.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Convert Word to PDF/A in Java

Spire.Doc for Java offers the ToPdfParameterList class to configure options for the Word-to-PDF conversion. For example, you can set the conformance level as Pdf/A-1a. To apply these customized settings, pass the ToPdfParameterList object as a parameter to the Document.saveToFile() method.

The steps to convert Word to PDF/A using Java are as follows.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to specify the conversion options.
  • Set the conformance level as Pdf_A_1_A using ToPdfParameterList.setPdfConformanceLevel() method.
  • Convert the Word document to PDF/A using Doucment.saveToFile(String fileName, ToPdfParameterList paramList) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;
import com.spire.pdf.PdfConformanceLevel;

public class ConvertWordToPdfa {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a ToPdfParameterList object
        ToPdfParameterList parameters  = new ToPdfParameterList();

        // Set the conformance level for PDF
        parameters.setPdfConformanceLevel(PdfConformanceLevel.Pdf_A_1_A);

        // Save the document to a PDF file
        doc.saveToFile("ToPdfA.pdf", parameters);

        // Dispose resources
        doc.dispose();
    }
}

Convert Word to Password-Protected PDF in Java

To encrypt the generated PDF document with a password, you can use the ToPdfParameterList.getPdfSecurity().encrypt() method. By passing the ToPdfParameterList object as a parameter to the Document.saveToFile() method, these encryption settings will be applied during the saving process.

The steps to convert a Word document to an encrypted PDF using Java are as follows:

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to specify the conversion options.
  • Set an open password and a permission password for the generated PDF document using ToPdfParameterList.PdfSecurity.Encrypt() method.
  • Convert the Word document to a password-protected PDF file using Doucment.saveToFile(String fileName, ToPdfParameterList paramList) 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 object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a ToPdfParameterList object
        ToPdfParameterList parameters = new ToPdfParameterList();

        // Set open password and permission password for PDF
        parameters.getPdfSecurity().encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.None, PdfEncryptionKeySize.Key_256_Bit);

        // Save the document to PDF
        doc.saveToFile("PasswordProtected.pdf", parameters);

        // Dispose resources
        doc.dispose();
    }
}

Convert a Specific Section in Word to PDF in Java

Spire.Doc's Section.deepClone() method allows you to create a copy of a certain section, and the SectionCollection.add() method enables you to add the copied section to the section collection of another document. Using these two methods, you can easily create a document containing the desired section from the source document.

To convert a specific section of a Word document to a PDF file, follow these steps.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create another Document object for holding one section from the source document.
  • Create a copy of a certain section of the source document using Section.deepClone() method.
  • Add the copy to the new document using Document.getSections.Add() method.
  • Save the new Word document to PDF using Doucment.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;

public class ConvertSectionToPdf {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Get a specific section of the document
        Section section = doc.getSections().get(1);

        // Create a new document object
        Document newDoc = new Document();

        // Clone the default style to the new document
        doc.cloneDefaultStyleTo(newDoc);

        // Clone the section to the new document
        newDoc.getSections().add(section.deepClone());

        // Save the new document to PDF
        newDoc.saveToFile("SectionToPDF.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
        newDoc.dispose();
    }
}

Change Page Size when Converting Word to PDF in Java

The PageSetup.setPageSize() method provides a means to change the page size of a Word document, allowing you to select from standard paper sizes or define a custom size. This page configuration will be maintained during the conversion from Word to PDF.

The steps to change page size while converting Word to PDF using Java are as follows.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Iterate through the sections in the document, and change the page size of each section to a standard paper size or a custom size using Section.getPageSetup().setPageSize() method.
  • Convert the Word document to PDF using Doucment.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.PageSize;

import java.awt.*;
import java.awt.geom.Dimension2D;

public class ChangePageSizeDuringConversion {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Iterate through the sections in the document
        for (Object section: doc.getSections()
             ) {

            // Change the page size of each section to a standard page size
            ((Section)section).getPageSetup().setPageSize(PageSize.B5);

            // Change the page size of each section to a custom size
            // Dimension2D dimension2D = new Dimension();
            // dimension2D.setSize(500, 700);
            // ((Section)section).getPageSetup().setPageSize(dimension2D);
        }

        // Save the document to PDF
        doc.saveToFile("ChangePageSize.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Set Image Quality when Converting Word to PDF in Java

With Spire.Doc for Java, you can control the image quality within the document by adjusting the value passed to the Document.setJPEGQuality() method. For example, setting the value to 50 will reduce the image quality to 50% of its original state.

The steps to set image quality while converting Word to PDF using Java are as follows.

  • Create a Document object.
  • Load a Word document for a given file path.
  • Set the image quality using Document.setJPEGQuality() method.
  • Convert the document to PDF using Doucment.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class SetImageQualityDuringConversion {

    public static void main(String[] args) {
        
        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Set the image quality to 50% of the original quality
        doc.setJPEGQuality(50);

        // Preserve original image quality
        // doc.setJPEGQuality(100);

        // Save the document to PDF
        doc.saveToFile("SetImageQuality.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Embed Fonts when Converting Word to PDF in Java

To embed all fonts used in the Word document in the generated PDF document, you can use the ToPdfParameterList.isEmbeddedAllFonts() method. Alternatively, if you prefer to specify a specific list of fonts to embed, you can use the ToPdfParameterList.setEmbeddedFontNameList() method.

The following are the steps to embed fonts while converting Word to PDF using Java.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to specify the conversion options.
  • Embed all fonts in the generated PDF by passing true to the ToPdfParameterList.isEmbeddedAllFonts() method.
  • Convert the Word document to PDF with fonts embedded using Doucment.saveToFile(String fileName, ToPdfParameterList paramList) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.ToPdfParameterList;

public class EmbedFontsDuringConversion {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a ToPdfParameterList object
        ToPdfParameterList parameters = new ToPdfParameterList();

        // Embed all the fonts used in Word in the generated PDF
        parameters.isEmbeddedAllFonts(true);

        // Save the document to PDF
        doc.saveToFile("EmbedFonts.pdf", FileFormat.PDF);

        // Dispose resources
        doc.dispose();
    }
}

Create Bookmarks when Converting Word to PDF in Java

While converting a Word document to PDF using Spire.Doc for Java, you can opt to automatically generate bookmarks based on existing bookmarks or headings. This can be achieved by passing true to either ToPdfParameterList.setCreateWordsBookmarks() method or ToPdfParameterList.setCreateWordBookmarksUsingHeadings() method.

The steps to create bookmarks while converting Word to PDF using Java are as follows.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to specify the conversion options.
  • Generate bookmarks in PDF based on the existing bookmarks of the Word document by passing true to ToPdfParameterList.setCreateWordsBookmarks() method.
  • Convert the Word document to PDF using Doucment.SaveToFile(String fileName, ToPdfParameterList paramList) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;

public class GenerateBookmarksDuringConversion {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a ToPdfParameterList object
        ToPdfParameterList parameters = new ToPdfParameterList();

        // Create bookmarks in PDF from existing bookmarks in Word
        parameters.setCreateWordBookmarks(true);

        // Create bookmarks from Word headings
        // parameters.setCreateWordBookmarksUsingHeadings(true);

        // Save the document to PDF
        doc.saveToFile("CreateBookmarks.pdf", parameters);

        // Dispose resources
        doc.dispose();
    }
}

Disable Hyperlinks when Converting Word to PDF in Java

To prevent hyperlinks from being included during the Word-to-PDF conversion, you can do so by passing true to the ToPdfParameterList.setDisableLink() method.

The detailed steps for this process are outlined below.

  • Create a Document object.
  • Load a Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to specify the conversion options.
  • Disable hyperlinks by setting the ToPdfParameterList.setDisableLink() method to true.
  • Convert the Word document to PDF using Doucment.saveToFile(String fileName, ToPdfParameterList paramList) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;

public class DisableHyperlinksDuringConversion {

    public static void main(String[] args) {

        // Create a Document object
        Document doc = new Document();

        // Load a Word document
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");

        // Create a ToPdfParameterList object
        ToPdfParameterList parameters = new ToPdfParameterList();

        // Disable hyperlinks
        parameters.setDisableLink(true);

        // Save the document to PDF
        doc.saveToFile("DisableHyperlinks.pdf", parameters);

        // Dispose resources
        doc.dispose();
    }
}

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.