Remove PDF Headers and Footers in Java

Remove header and footer artifacts from the first page of a PDF in Java.

Use this approach when existing header and footer artifacts should be removed from the page.

  1. Open the source PDF Document.
  2. Iterate through the page artifact collection in reverse order.
  3. Delete pagination artifacts whose subtype is header or footer, then save the document.
public static void deleteHeaderFooterArtifact(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (int i = document.getPages().get_Item(1).getArtifacts().size(); i >= 1; i--) {
            Artifact artifact = document.getPages().get_Item(1).getArtifacts().get_Item(i);
            if (artifact.getType() == Artifact.ArtifactType.Pagination
                    && (artifact.getSubtype() == Artifact.ArtifactSubtype.Header
                    || artifact.getSubtype() == Artifact.ArtifactSubtype.Footer)) {
                document.getPages().get_Item(1).getArtifacts().delete(artifact);
            }
        }

        document.save(outputFile.toString());
    }
}