cover page of converting word to pdf with java code

Converting Word documents (doc or .docx) to PDF is a common requirement in many Java-based applications, especially those involving documentation, report generation, or digital archiving. In this tutorial, we'll show you how to convert Word to PDF in Java using reliable and easy-to-implement libraries like Spire.Doc for Java. This guide will walk you through all the code examples from code library integration to converting Word files to PDF format seamlessly.

After reading this guide, you will learn:

Let's dive into the Java code for Word to PDF conversion and help your application automate document processing with just a few lines of code.

Specific Steps of How to Convert Doc/Docx Files to PDF Format with Spire.Doc for Java

Before going through the sample code, you should know one of the best Word Java library known as Spire.Doc for Java. It supports not only Word file format conversion, but more advanced settings including page size adjustment, font embed, specific area conversion, etc. It is a one time download for long-term benefits.

Follow the steps below to learn how you can convert Word files to PDF format with Spire.Doc for Java.

Step 1. Install Spire.Doc for Java

Before converting, you should add the Spire.Doc.jar file as a dependency in your Java program. You can download the JAR file from the official download page.

If you are using Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file directly:


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

Step 2. Convert Word to PDF with Java Code

After library integration, now, it's time to convert your Word files. Copy the code below to your Java program:

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();
    }
}

RESULT:

result of converting word to pdf with spire doc for java

Advanced Settings When Converting Word Files to PDF

Except for simply converting Word to PDF files, Spire.Doc for Java provides more options beyond simply conversion. For example, you can set a password to protect your PDF data with simple code during the conversion. You have no need to look for other tutorials. The following list is a preview of these settings, and you can directly jump to the corresponding part.

Convert Word files to PDF/A Format with Java Code

Spire.Doc for Java allows you to 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.

Copy the code below to convert your doc/docx to PDF/A files with Java:

import com.spire.doc.Document;
import com.spire.doc.ToPdfParameterList;
import com.spire.doc.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("C:\\Users\\Administrator\\Desktop\\ToPdfA.pdf", parameters);

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

Convert Word Files to Password-Protected PDF in Java

To protect your data, you may need to set a password for the converted PDF file. In this part, you can encrypt the converted PDF documents with password during the conversion process without any hassle. By passing the ToPdfParameterList object as a parameter to the Document.saveToFile() method, these encryption settings will be applied during the saving process.

Copy the code below to encrypt converted PDF files during conversion with Java:

import com.spire.doc.Document;
import com.spire.doc.PdfPermissionsFlags;
import com.spire.doc.ToPdfParameterList;

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", PdfPermissionsFlags.valueOf("permissionPsd"));

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

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

Convert a Specific Area in Word to PDF in Java

The third section is that you can create a copy of a certain section with Spire.Doc's Section.deepClone() method and use the SectionCollection.add() method to add the copied section to the section collection of another document.

You can easily create a document containing the desired section from the source document with the following Java code:

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();
    }
}

How to Adjust Word Files When Converting Word to PDF with Java Code

To get the best conversion result, you can make more adjustment to your Word documents during the conversion process. For example, you can embed fonts, adjust page size, set image quality, create bookmarks, or modify hyperlink with Java code.

Here, I will take one adjustment as an example to show you how to manage it. If you need to apply other adjustments, you can directly click the link above and jump to the corresponding page.

Example: Set Image Quality During Word to PDF Conversion

Image quality is a vital element when converting DOC/DOCX files to PDF format. It may influence the conversion speed and play an important role in the conversion result. With Spire.Doc for Java, you can set the image quality according to your specific needs to ensure the highest efficiency.

Copy the following code in your Java program to adjust picture quality:

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();
    }
}

Final Words

Converting Word to PDF in Java is simple and efficient with Spire.Doc for Java. From basic conversion to advanced options like password protection, section export, and image quality settings, you can handle it all with just a few lines of code.

If you'd like to access all features without limitations and remove the evaluation watermark, please request a 30-day trial license for yourself.

Published in Conversion

There are many reasons why you might need to convert Word documents to images. For example, a lot of devices can open and display images directly without any special software, and when images are transmitted their content is difficult to be tampered with. In this article, you will learn how to convert Word to popular image formats such as JPG, PNG and SVG using Spire.Doc for Java.

Install Spire.Doc for Java

First, 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>13.11.2</version>
    </dependency>
</dependencies>

Convert Word to JPG in Java

Spire.Doc for Java offers the Document.saveToImages() method to convert a whole Word document into individual BufferedImage images. Then, each BufferedImage can be saved as a BMP, EMF, JPEG, PNG, GIF, or WMF file. The following are the steps to convert Word to JPG using this library.

  • Create a Document object.
  • Load a Word document using Document.loadFromFile() method.
  • Convert the document to BufferedImage images using Document.saveToImages() method.
  • Loop through the image collection to get the specific one.
  • Re-write the image with different color space.
  • Write the BufferedImage to a JPG file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.documents.ImageType;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ConvertWordToJPG {

    public static void main(String[] args) throws IOException {

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

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

        //Convert the whole document into individual buffered images
        BufferedImage[] images = doc.saveToImages(ImageType.Bitmap);

        //Loop through the images
        for (int i = 0; i < images.length; i++) {

            //Get the specific image
            BufferedImage image = images[i];

            //Re-write the image with a different color space
            BufferedImage newImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
            newImg.getGraphics().drawImage(image, 0, 0, null);

            //Write to a JPG file
            File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.jpg"), i));
            ImageIO.write(newImg, "JPEG", file);
        }
    }
}

Convert Word to SVG in Java

Using Spire.Doc for Java, you can save a Word document as a list of byte arrays. Each byte array can then be written as a SVG file. The detailed steps to convert Word to SVG are as follows.

  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Save the document as a list of byte arrays using Document.saveToSVG() method.
  • Loop through the items in the list to get a specific byte array.
  • Write the byte array to a SVG file.
  • Java
import com.spire.doc.Document;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class ConvertWordToSVG {

    public static void main(String[] args) throws IOException {

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

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

        //Save the document as a list of byte arrays
        List<byte[]> svgBytes = doc.saveToSVG();

        //Loop through the items in the list
        for (int i = 0; i < svgBytes.size(); i++)
        {
            //Get a specific byte array
            byte[] byteArray = svgBytes.get(i);

            //Specify the output file name
            String outputFile = String.format("Image-%d.svg", i);

            //Write the byte array to a SVG file
            try (FileOutputStream stream = new FileOutputStream("C:\\Users\\Administrator\\Desktop\\Images\\" + outputFile)) {
                stream.write(byteArray);
            }
        }
    }
}

Convert Word to PNG with Customized Resolution

An image with higher resolution is generally more clear. You can customize the image resolution while converting Word to PNG by following the following steps.

  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Convert the document to BufferedImage images with the specified resolution using Document.saveToImages() method.
  • Loop through the image collection to get the specific one and save it as a PNG file.
  • Java
import com.spire.doc.Document;
import com.spire.doc.documents.ImageType;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class ConvertWordToPNG {

    public static void main(String[] args) throws IOException {

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

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

        //Convert the whole document into individual buffered images with customized resolution
        BufferedImage[] images = doc.saveToImages(0, doc.getPageCount(), ImageType.Bitmap, 150, 150);

        //Loop through the images
        for (int i = 0; i < images.length; i++) {

            //Get the specific image
            BufferedImage image = images[i];

            //Write to a PNG file
            File file = new File("C:\\Users\\Administrator\\Desktop\\Images\\" + String.format(("Image-%d.png"), i));
            ImageIO.write(image, "PNG", file);
        }
    }
}

Java: Convert Word to Images (JPG, PNG and SVG)

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.

Published in Conversion
Page 3 of 3