Java: Add Page Number to Word Documents
Page numbers in Word documents are marked on each page to indicate the order and the number of pages. They can facilitate document creators to manage the document content and help users quickly find specific content in the document, thus improving reading speed and reading experience. This article is going to show how to use Spire.Doc for Java to add page numbers to Word documents programmatically.
- Add Page Numbers to a Word Document in Java
- Restart Page Numbering for Each Section in a Word Document in Java
- Add Page Numbers to a Specific Section in a Word Document in Java
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.4.1</version> </dependency> </dependencies>
Add Page Numbers to a Word Document in Java
Page numbers in Word are displayed using specific types of fields. For example, the Page field displays the page number of the current page, the NumPages field displays the total number of pages in a document, and the SectionPages field displays the total number of pages in a section.
Spire.Doc for Java provides the Paragraph.appendField(String fieldName, FieldType fieldType) method to add various types of fields to a Word document, including the Page field (FieldType.Field_Page), the NumPages field (FieldType.Field_Num_Pages), and the SectionPages field (FieldType.Field_Section_Pages).
The following steps explain how to add a Page field and a NumPages field to the footer of a Word document to display the current page number and the total number of pages in the document using Spire.Doc for Java:
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Get the first section using Document.getSections().get() method.
- Get the footer of the first section using Section.getHeadersFooters().getFooter() method.
- Add a paragraph to the footer, and then add a Page field and a NumPages field to the paragraph using Paragraph.appendField(String fieldName, FieldType fieldType) method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FieldType; import com.spire.doc.HeaderFooter; import com.spire.doc.Section; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; public class addPageNumbersWholeDocument { public static void main(String[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document document.loadFromFile("Sample.docx"); //Get the first section Section section = document.getSections().get(0); //Get the footer of the section HeaderFooter footer = section.getHeadersFooters().getFooter(); //Add Page and NumPages fields to the footer and set the format Paragraph footerParagraph = footer.addParagraph(); footerParagraph.appendField("page number", FieldType.Field_Page); footerParagraph.appendText(" / "); footerParagraph.appendField("page count", FieldType.Field_Num_Pages); footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); footerParagraph.getStyle().getCharacterFormat().setFontSize(16); //Save the document document.saveToFile("PageNumberWholeDocument.docx"); document.dispose(); } }
Restart Page Numbering for Each Section in a Word Document in Java
Restarting page numbering allows you to start the page numbers at a particular number in each section, rather than continuing from the page numbers of the previous section.
To restart page numbering for each section of a Word document, you need to loop through all sections in the document and add a Page field and a SectionPages field to each section. Then use the Section.getPageSetup().setRestartPageNumbering(true) method to enable restarting page numbering and the Section.getPageSetup().setPageStartingNumber(int value) method to set the starting page number for each section. The detailed steps are as follows:
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Loop through the sections in the document.
- Call the Paragraph.appendField(String fieldName, FieldType fieldType) method to add a Page field and a SectionPages field to each section.
- Call the Section.getPageSetup().setRestartPageNumbering(true) method to enable restarting page numbering and the Section.getPageSetup().setPageStartingNumber(int value) method to set the starting page number for each section.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FieldType; import com.spire.doc.HeaderFooter; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; public class addPageNumbersEachSection { public static void main(String[] args) { //Create an object of Document class Document document = new Document(); //Load a Word document document.loadFromFile("Sample.docx"); //Get the count of sections in the document int s = document.getSections().getCount(); //Loop through the sections in the document for (int i = 0; i < s; i++) { //Add Page and SectionPages fields to each section HeaderFooter footer = document.getSections().get(i).getHeadersFooters().getFooter(); Paragraph footerParagraph = footer.addParagraph(); footerParagraph.appendField("page number", FieldType.Field_Page); footerParagraph.appendText(" / "); footerParagraph.appendField("section page count", FieldType.Field_Section_Pages); footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); footerParagraph.getStyle().getCharacterFormat().setFontSize(16); //Restart page numbering for each section if (i == s-1) break; else { document.getSections().get(i + 1).getPageSetup().setRestartPageNumbering(true); document.getSections().get(i + 1).getPageSetup().setPageStartingNumber(1); } } //Save the document document.saveToFile("PageNumbersSections.docx"); document.dispose(); } }
Add Page Numbers to a Specific Section in a Word Document in Java
By default, when you insert page numbers into the footer of a section, the subsequent sections will automatically link to the previous section to continue displaying the page numbers. If you want to add page numbers to only a specific section, you will need to unlink the subsequent sections from the previous section, and then delete the content of the footers in the subsequent sections. The detailed steps are as follows:
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Get the second section of the document using Document.getSections().get() method.
- Call the Section.getPageSetup().setRestartPageNumbering(true) method to enable restarting page numbering and the Section.getPageSetup().setPageStartingNumber(int value) method to set the starting page number for the section.
- Call the Paragraph.appendField(String fieldName, FieldType fieldType) method to add a Page field and a SectionPages field to the section.
- Unlink the subsequent section from the second section using the Section.getHeadersFooters().getFooter().setLinkToPrevious(false) method.
- Delete the content of the footers in the subsequent sections.
- Save the document using Doucment.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FieldType; import com.spire.doc.HeaderFooter; import com.spire.doc.Section; import com.spire.doc.documents.HorizontalAlignment; import com.spire.doc.documents.Paragraph; public class addPageNumbersToSpecificSection { public static void main(String[] args) { //Create an object of Document Document document = new Document(); //Load a Word document document.loadFromFile("Sample.docx"); //Get the second section Section section = document.getSections().get(1); //Get the footer of the second section HeaderFooter footer = section.getHeadersFooters().getFooter(); //Set the start page as the first page of the second section and the starting number as 1 section.getPageSetup().setRestartPageNumbering(true); section.getPageSetup().setPageStartingNumber(1); //Add page numbers to the footer and set the format Paragraph footerParagraph = footer.addParagraph(); footerParagraph.appendField("Page number", FieldType.Field_Page); footerParagraph.appendText(" / "); footerParagraph.appendField("Number of pages", FieldType.Field_Section_Pages); footerParagraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Center); footerParagraph.getStyle().getCharacterFormat().setFontSize(12); //Unlink the subsequent section from the second section document.getSections().get(2).getHeadersFooters().getFooter().setLinkToPrevious(false); //Delete the content of the footers in the subsequent sections for (int i = 2; i < document.getSections().getCount(); i++) { document.getSections().get(i).getHeadersFooters().getFooter().getChildObjects().clear(); document.getSections().get(i).getHeadersFooters().getFooter().addParagraph(); } //Save the document document.saveToFile("PageNumberOneSection.docx"); document.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.
Add a round corner rectangle to presentation slide in C#
With the help of Spire.Presentation, we can add shapes to the presentation slides easily. This example shows you how to add a round corner rectangle to presentation slide and set the radius of the round corner rectangle in C#.
using Spire.Presentation; using Spire.Presentation.Drawing; using System.Drawing; namespace RoundRectangle { class Program { static void Main(string[] args) { Presentation presentation = new Presentation(); //Insert a round corner rectangle and set its radious presentation.Slides[0].Shapes.InsertRoundRectangle(0, 60, 90, 100, 200, 36); //Append a round corner rectangle and set its radious IAutoShape shape = presentation.Slides[0].Shapes.AppendRoundRectangle(260, 90, 100, 200, 80); //Set the color and fill style of shape shape.Fill.FillType = FillFormatType.Solid; shape.Fill.SolidColor.Color = Color.SeaGreen; shape.ShapeStyle.LineColor.Color = Color.White; //Rotate the shape to 90 degree shape.Rotation = 90; //Save the document to file presentation.SaveToFile("Result.pptx", FileFormat.Pptx2013); } } }
Effective screenshot of the round corner rectangle on presentation slide:
Get Bookmark Text in Java
This article demonstrates how to get the text inside a bookmark in a Word document using Spire.Doc for Java.
import com.spire.doc.Document; import com.spire.doc.documents.BookmarksNavigator; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextBodyPart; import com.spire.doc.fields.TextRange; import java.io.FileNotFoundException; import java.io.PrintWriter; public class GetBookmarkText { public static void main(String[] args) throws FileNotFoundException { //create a Document object Document doc = new Document(); //load a sample Word file doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx"); //get the specific bookmark BookmarksNavigator navigator = new BookmarksNavigator(doc); navigator.moveToBookmark("MyBookmark"); //get the bookmark content TextBodyPart textBodyPart = navigator.getBookmarkContent(); //declare a String variable String text = ""; //loop through body items for (Object item : textBodyPart.getBodyItems()) { //determine if an item is a paragraph if (item instanceof Paragraph) { Paragraph paragraph = (Paragraph) item; //loop through the child objects of the paragraph for (Object childObj : paragraph.getChildObjects()) { //determine if a child object is a text range if (childObj instanceof TextRange) { //get text from the text range TextRange textRange = (TextRange) childObj; text = text + textRange.getText(); } } } } //write the bookmark text to a .txt file PrintWriter printWriter = new PrintWriter("output/BookmarkText.txt"); printWriter.println(text); printWriter.close(); } }
Create a Multi-Column Word Document in Java
We can format Word document in a multi-column newsletter layout by adding columns. This article demonstrates how to add multiple columns to a Word document and specify the column width and the spacing between columns using Spire.Doc for Java.
import com.spire.doc.*; import com.spire.doc.documents.*; public class CreateMutiColumnWordDocument { public static void main(String[] args){ //create a Document object Document document = new Document(); //add a section Section section = document.addSection(); //add 3 columns to the section section.addColumn(100, 20); section.addColumn(100, 20); section.addColumn(100, 20); //add a paragraph to the section Paragraph paragraph = section.addParagraph(); //add a paragraph to the section paragraph = section.addParagraph(); String text = "Spire.Doc for Java is a professional Java Word API that enables Java applications " +"to create, convert, manipulate and print Word documents without using Microsoft Office."; //add text to the paragraph paragraph.appendText(text); //add column break to the paragraph paragraph.appendBreak(BreakType.Column_Break); //add a paragraph to the section paragraph = section.addParagraph(); //add text to the paragraph paragraph.appendText(text); //add column break to the paragraph paragraph.appendBreak(BreakType.Column_Break); //add a paragraph to the section paragraph = section.addParagraph(); //add text to the paragraph paragraph.appendText(text); //add line between columns section.getPageSetup().setColumnsLineBetween(true); //save the resultant document document.saveToFile("Muti-Column Document.docx", FileFormat.Docx_2013); } }
Output:
Java make a booklet from a PDF document
When we print a huge PDF document, print as a booklet is a great way to save the paper and make the pages tidy. This article we will introduce how to create a booklet from a PDF document in Java applications.
import com.spire.pdf.*; public class PDFBooklet{ public static void main(String[] args) throws Exception { String inputPath = "Sample.pdf"; PdfDocument doc = new PdfDocument(); doc.loadFromFile(inputPath); PdfPageBase page = doc.getPages().get(0); float width = (float) page.getSize().getWidth()*2; float height = (float) page.getSize().getHeight(); doc.createBooklet(inputPath, width, height,true); doc.saveToFile("Output/Booklet.pdf"); } }
Effective screenshot after creating PDF booklet:
Detect Required Fields in a PDF Document in Java
This article demonstrates how to detect the required form fields in an existing PDF document using Spire.PDF for Java.
import com.spire.pdf.fields.PdfField; import com.spire.pdf.widget.PdfFormWidget; public class DetectRequiredFields { public static void main(String[] args) { //load a PDF file PdfDocument doc = new PdfDocument(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Fields.pdf"); //get form widget from the PDF document. PdfFormWidget formWidget = (PdfFormWidget)doc.getForm(); //loop through the fields widget for (int i = 0; i < formWidget.getFieldsWidget().getList().getCapacity(); i++) { //get the specific field PdfField field = (PdfField) formWidget.getFieldsWidget().getList().get_Item(i); //get the field name String fieldName = field.getName(); //determine if the field is required boolean isRequired = field.getRequired(); if (isRequired){ //print the required field System.out.println(fieldName + " is required"); } } } }
Add Content Controls to Word Document in Java
This article demonstrates how to add combo box, check box, text, picture, date picker and drop-down list content controls to a Word document using Spire.Doc for Java.
import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.*; import java.util.Date; public class ContentControls { public static void main(String[] args){ //create a new Word document Document document = new Document(); Section section = document.addSection(); Paragraph paragraph = section.addParagraph(); TextRange txtRange = paragraph.appendText("The following example shows how to add content controls in a Word document."); section.addParagraph(); //add combo box content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Combo Box Content Control: "); txtRange.getCharacterFormat().setItalic(true); StructureDocumentTagInline sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setSDTType(SdtType.Combo_Box); sd.getSDTProperties().setAlias("ComboBox"); sd.getSDTProperties().setTag("ComboBox"); SdtComboBox cb = new SdtComboBox(); cb.getListItems().add(new SdtListItem("Spire.Doc")); cb.getListItems().add(new SdtListItem("Spire.XLS")); cb.getListItems().add(new SdtListItem("Spire.PDF")); sd.getSDTProperties().setControlProperties(cb); TextRange rt = new TextRange(document); rt.setText(cb.getListItems().get(0).getDisplayText()); sd.getSDTContent().getChildObjects().add(rt); section.addParagraph(); //Add checkbox content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Check Box Content Control: "); txtRange.getCharacterFormat().setItalic(true); sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setSDTType(SdtType.Check_Box); sd.getSDTProperties().setAlias("CheckBox"); sd.getSDTProperties().setTag("CheckBox"); SdtCheckBox scb = new SdtCheckBox(); sd.getSDTProperties().setControlProperties(scb); rt = new TextRange(document); sd.getChildObjects().add(rt); scb.setChecked(true); section.addParagraph(); //add text content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Text Content Control: "); txtRange.getCharacterFormat().setItalic(true); sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setSDTType(SdtType.Text); sd.getSDTProperties().setAlias("Text"); sd.getSDTProperties().setTag("Text"); SdtText text = new SdtText(true); text.isMultiline(true); sd.getSDTProperties().setControlProperties(text); rt = new TextRange(document); rt.setText("Text"); sd.getSDTContent().getChildObjects().add(rt); section.addParagraph(); //add picture content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Picture Content Control: "); txtRange.getCharacterFormat().setItalic(true); sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setControlProperties(new SdtPicture()); sd.getSDTProperties().setAlias("Picture"); sd.getSDTProperties().setTag("Picture"); DocPicture pic = new DocPicture(document); pic.setWidth(10f); pic.setHeight(10f); pic.loadImage("logo.png"); sd.getSDTContent().getChildObjects().add(pic); section.addParagraph(); //add date picker content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Date Picker Content Control: "); txtRange.getCharacterFormat().setItalic(true); sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setSDTType(SdtType.Date_Picker); sd.getSDTProperties().setAlias("Date"); sd.getSDTProperties().setTag("Date"); SdtDate date = new SdtDate(); date.setCalendarType(CalendarType.Default); date.setDateFormat("yyyy.MM.dd"); date.setFullDate(new Date()); sd.getSDTProperties().setControlProperties(date); rt = new TextRange(document); rt.setText("2018.12.25"); sd.getSDTContent().getChildObjects().add(rt); section.addParagraph(); //add drop-down list content control paragraph = section.addParagraph(); txtRange = paragraph.appendText("Add Drop-Down List Content Control: "); txtRange.getCharacterFormat().setItalic(true); sd = new StructureDocumentTagInline(document); paragraph.getChildObjects().add(sd); sd.getSDTProperties().setSDTType(SdtType.Drop_Down_List); sd.getSDTProperties().setAlias("DropDownList"); sd.getSDTProperties().setTag("DropDownList"); SdtDropDownList sddl = new SdtDropDownList(); sddl.getListItems().add(new SdtListItem("Harry")); sddl.getListItems().add(new SdtListItem("Jerry")); sd.getSDTProperties().setControlProperties(sddl); rt = new TextRange(document); rt.setText(sddl.getListItems().get(0).getDisplayText()); sd.getSDTContent().getChildObjects().add(rt); //save the resultant document document.saveToFile("addContentControls.docx", FileFormat.Docx_2013); } }
Output:
How to wrap text around image on Word document in Java
This article will show you how to set the wrapping style to adjust the position of the image in Java applications with the help of Spire.Doc for Java.
import com.spire.doc.*; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.TextWrappingStyle; import com.spire.doc.documents.TextWrappingType; import com.spire.doc.fields.DocPicture; public class ImageWrappingStyle { public static void main(String[] args) throws Exception { Document doc = new Document(); doc.loadFromFile("Sample.docx"); Section sec = doc.getSections().get(0); Paragraph para = sec.getParagraphs().get(0); DocPicture picture = para.appendPicture("logo.png"); //Set image width and height picture.setWidth(150f); picture.setHeight(125f); //Set text wrapping style to Behind picture.setTextWrappingStyle(TextWrappingStyle.Behind); picture.setTextWrappingType(TextWrappingType.Both); //Save the document to file doc.saveToFile("Output/WrapStyle.docx"); doc.close(); } }
Effective screenshot after setting the wrapping style for image:
Java: Insert Page Breaks and Section Breaks to Word
In document creation, divisions of content are frequently required to fulfill specific layout requirements and establish logical structures. The insertion of section breaks and page breaks is the most commonly employed method for dividing content, as it enables flexible control over page and section organization. Moreover, page breaks and section breaks are quite helpful in formatting purposes and the establishment of distinct document styles. This article aims to demonstrate how to use Spire.Doc for Java to insert page breaks and section breaks into Word documents through Java programs.
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>12.4.1</version> </dependency> </dependencies>
Insert Page Breaks into Word Documents
Spire.Doc for Java provides the Paragraph.appendBreak(BreakType.PageBreak) method to insert a page break at the end of a paragraph. The detailed steps are as follows:
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Get the first section using Document.getSections().get() method.
- Get the eighth paragraph of the section using Section.getParagraphs().get() method.
- Add a page break to the end of the paragraph using Paragraph.appendBreak(BreakType.PageBreak) method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.Section; import com.spire.doc.documents.BreakType; import com.spire.doc.documents.Paragraph; public class InsertPageBreak { public static void main(String[] args) { //Create an object of Document class Document doc = new Document(); //Load a Word document doc.loadFromFile("Sample.docx"); //Get the first section Section section = doc.getSections().get(0); //Get the eighth paragraph Paragraph paragraph = section.getParagraphs().get(7); //Add a page break to the end of the paragraph paragraph.appendBreak(BreakType.Page_Break); //Save the document doc.saveToFile("PageBreak.docx", FileFormat.Auto); } }
Insert Section Breaks into Word Documents
Inserting section breaks involves using the Paragraph.insertSectionBreak(SectionBreakType) method. This method allows users to specify the type of section break you want to insert. he following table provides an overview of the section break types, along with their corresponding Enums and descriptions:
Section Break | Enum | Description |
New page | SectionBreakType.New_Page | Start the new section on a new page. |
Continuous | SectionBreakType.No_Break | Start the new section without starting a new page, allowing for continuous content flow. |
Odd page | SectionBreakType.Odd_Page | Start the new section on the next odd-numbered page. |
Even page | SectionBreakType.Even_Page | Start the new section on the next even-numbered page. |
New column | SectionBreakType.New_Column | Start the new section in the next column if columns are enabled. |
The detailed steps for inserting a continuous section break are as follows:
- Create an object of Document class.
- Load a Word document using Document.loadFromFile() method.
- Get the first section using Document.getSections().get() method.
- Get the second paragraph of the section using Section.getParagraphs().get() method.
- Add a continuous section break to the end of the paragraph using Paragraph.insertSectionBreak(SectionBreakType.No_Break) method.
- Save the document using Document.saveToFile() method.
- Java
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.Section; import com.spire.doc.documents.Paragraph; import com.spire.doc.documents.SectionBreakType; public class InsertSectionBreak { public static void main(String[] args) { //Create an object of Document class Document doc = new Document(); //Load a Word document doc.loadFromFile("Sample.docx"); //Get the first section Section section = doc.getSections().get(0); //Get the second paragraph Paragraph paragraph = section.getParagraphs().get(1); //Insert a section break paragraph.insertSectionBreak(SectionBreakType.No_Break); //Save the document doc.saveToFile("SectionBreak.docx", FileFormat.Auto); } }
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.
Delete Attachments in PDF in Java
This article demonstrates how to delete attachments and annotation attachments in a PDF document using Spire.PDF for Java.
Delete Attachments
import com.spire.pdf.attachments.PdfAttachmentCollection; public class DeleteAttachments { public static void main(String[] args) { //load a PDF document PdfDocument doc = new PdfDocument(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf"); //get the attachments collection, not containing annotation attachments PdfAttachmentCollection attachments = doc.getAttachments(); //remove all attachments attachments.clear(); //remove a specific attachment //attachments.removeAt(0); //save to file doc.saveToFile("output/DeleteAttachments.pdf"); doc.close(); } }
Delete Annotation Attachments
import com.spire.pdf.annotations.PdfAnnotation; import com.spire.pdf.annotations.PdfAnnotationCollection; import com.spire.pdf.annotations.PdfAttachmentAnnotationWidget; public class DeleteAnnotationAttachments { public static void main(String[] args) { //load a PDF document PdfDocument doc = new PdfDocument(); doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Attachments.pdf"); //loop through the pages for (int i = 0; i < doc.getPages().getCount(); i++) { //get the annotations collection PdfAnnotationCollection annotationCollection = doc.getPages().get(i).getAnnotationsWidget(); //loop through the annotations for (Object annotation: annotationCollection) { //determine if an annotation is an instance of PdfAttachmentAnnotationWidget if (annotation instanceof PdfAttachmentAnnotationWidget){ //remove the attachment annotation annotationCollection.remove((PdfAnnotation) annotation); } } } //save to file doc.saveToFile("output/DeleteAnnotationAttachments.pdf"); doc.close(); } }