Remove PDF Comments in Java with PDFBox

One way to remove comments from a PDF in Java is to use the Apache PDFBox library. Below is a simple example code that can open a PDF file, delete all comments, and save the modified file.

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDAnnotation;

import java.io.File;
import java.io.IOException;

public class RemoveAnnotations {

    public static void main(String[] args) {
        try {
            // Load the PDF file
            File file = new File("input.pdf");
            PDDocument document = PDDocument.load(file);

            // Remove all annotations from each page
            for (PDPage page : document.getPages()) {
                page.getAnnotations().clear();
            }

            // Save the modified document
            document.save("output.pdf");
            document.close();

            System.out.println("Annotations removed successfully!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above code, first load a PDF file (assuming the file name is input.pdf), then iterate through each page and remove all comments, and finally save the modified file as output.pdf. Please make sure to add the Apache PDFBox library to the project’s build path before running this code.

bannerAds