PDF annotations are notes or markers added to documents, which are great for making comments, giving explanations, giving feedback, etc. Co-creators of documents often communicate with annotations. However, when the issues associated with the annotations have been dealt with or the document has been finalized, it is necessary to remove the annotations to make the document more concise and professional. This article shows how to delete PDF annotations programmatically using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.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.pdf</artifactId>
        <version>11.12.16</version>
    </dependency>
</dependencies>

Remove the Specified Annotation

Annotations are page-level document elements. Therefore, deleting an annotation requires getting the page where the annotation is located first, and then you can use the PdfPageBase.getAnnotationsWidget().removeAt() method to delete the annotation. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Remove the first annotation from this page using PdfPageBase.getAnnotationsWidget().removeAt() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAnnotation {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Annotations.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Remove the first annotation
        page.getAnnotationsWidget().removeAt(0);

        //Save the document
        pdf.saveToFile("RemoveOneAnnotation.pdf");
    }
}

Java: Remove Annotations from PDF Documents

Remove All Annotations from a Page

Spire.PDF for Java also provides PdfPageBase.getAnnotationsWidget().clear() method to remove all annotations in the specified page. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Remove all annotations from the page using PdfPageBase.getAnnotationsWidget().clear() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAllAnnotationPage {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Annotations.pdf");

        //Get the first page
        PdfPageBase page = pdf.getPages().get(0);

        //Remove all annotations in the page
        page.getAnnotationsWidget().clear();

        //Save the document
        pdf.saveToFile("RemoveAnnotationsPage.pdf");
    }
}

Java: Remove Annotations from PDF Documents

Remove All Annotations from a PDF Document

To remove all annotations from a PDF document, we need to loop through all pages in the document and delete all annotations from each page. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through all pages to delete annotations.
  • Delete annotations in each page using PdfPageBase.getAnnotationsWidget().clear() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAllAnnotations {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Users/Sirion/Desktop/Annotations.pdf");

        //Loop through the pages in the document
        for (Object page : (Iterable) pdf.getPages()) {
            PdfPageBase pageBase = (PdfPageBase) page;
            //Remove annotations in each page
            pageBase.getAnnotationsWidget().clear();
        }


        //Save the document
        pdf.saveToFile("RemoveAllAnnotations.pdf");
    }
}

Java: Remove Annotations from PDF Documents

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.

Monday, 11 January 2021 07:13

Add Line Numbers to a PDF in C#/VB.NET

This article demonstrates how to add line numbers before chunks of text in a PDF page by using Spire.PDF for .NET.

Below is a screenshot of the input document.

Add Line Numbers to a PDF in C#, VB.NET

C#
using Spire.Pdf;
using Spire.Pdf.General.Find;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddLineNumber
{
    class Program
    {
        static void Main(string[] args)
        {
     //Create a PdfDocument object
     PdfDocument doc = new PdfDocument();

     //Load PDF document
     doc.LoadFromFile(@"C:\Users\Administrator\Desktop\input.pdf");

     //Get the first page
     PdfPageBase page = doc.Pages[0];

     //Find specified text in the first line
     PdfTextFinder finder = new PdfTextFinder(page);
     finder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord;
     PdfTextFragment topLine = finder.Find("C# (pronounced See Sharp)")[0];

     //Get line height
     float lineHeight = topLine.Bounds[0].Height;

     //Get a Y coordinate for the starting position of line numbers
     float y = topLine.Bounds[0].Location.Y - 2;

     //Find specified text in the second line
     PdfTextFinder secondfinder = new PdfTextFinder(page);
     secondfinder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord;
     PdfTextFragment secondLine = secondfinder.Find("language. C#")[0];

     //Calculate line spacing
     float lineSpacing = secondLine.Bounds[0].Top - topLine.Bounds[0].Bottom;

     //Find specified text in the last line
     PdfTextFinder bottomfinder = new PdfTextFinder(page);
     bottomfinder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord;
     PdfTextFragment bottomLine = bottomfinder.Find("allocation of objects")[0];

     //Get the bottom Y coordinate of the last line, which is the height of the line number area
     float height = bottomLine.Bounds[0].Bottom;

     //Create a font with the same size as the text in the PDF
     PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 11f);

     int i = 1;
     while (y < height)
     {
         //Draw line numbers at the beginning of each line
         page.Canvas.DrawString(i.ToString(), font, PdfBrushes.Black, new PointF(15, y));
         y += lineHeight + lineSpacing;
         i++;
     }

     //Save the document
     doc.SaveToFile("result.pdf");
        }
    }
}
VB.NET
Imports Spire.Pdf
Imports Spire.Pdf.General.Find
Imports Spire.Pdf.Graphics
Imports System.Drawing
 
Namespace AddLineNumber
    Class Program
        Shared  Sub Main(ByVal args() As String)
        'Create a PdfDocument object
        Dim doc As New PdfDocument()

        'Load PDF document
        doc.LoadFromFile("C:\Users\Administrator\Desktop\input.pdf")

        'Get the first page
        Dim page As PdfPageBase = doc.Pages(0)

        'Find specified text in the first line
        Dim finder As New PdfTextFinder(page)
        finder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord
        Dim topLine As PdfTextFragment = finder.Find("C# (pronounced See Sharp)")(0)

        'Get line height
        Dim lineHeight As Single = topLine.Bounds(0).Height

        'Get a Y coordinate for the starting position of line numbers
        Dim y As Single = topLine.Bounds(0).Location.Y - 2

        'Find specified text in the second line
        Dim secondfinder As New PdfTextFinder(page)
        secondfinder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord
        Dim secondLine As PdfTextFragment = secondfinder.Find("language. C#")(0)

        'Calculate line spacing
        Dim lineSpacing As Single = secondLine.Bounds(0).Top - topLine.Bounds(0).Bottom

        'Find specified text in the last line
        Dim bottomfinder As New PdfTextFinder(page)
        bottomfinder.Options.Parameter = Spire.Pdf.Texts.TextFindParameter.WholeWord
        Dim bottomLine As PdfTextFragment = bottomfinder.Find("allocation of objects")(0)

        'Get the bottom Y coordinate of the last line, which is the height of the line number area
        Dim height As Single = bottomLine.Bounds(0).Bottom

        'Create a font with the same size as the text in the PDF
        Dim font As PdfFont = New PdfFont(PdfFontFamily.TimesRoman, 11.0F)

        Dim i As Integer = 1
        While y < height
            'Draw line numbers at the beginning of each line
            page.Canvas.DrawString(i.ToString(), font, PdfBrushes.Black, New PointF(15, y))
            y += lineHeight + lineSpacing
            i += 1
        End While

        'Save the document
        doc.SaveToFile("result.pdf")

        End Sub
    End Class
End Namespace

Output

Add Line Numbers to a PDF in C#, VB.NET

We have introduced how to compare two Word documents in C# and VB.NET. From Spire.Doc V8.12.14, it supports to get the differences between two Word documents in a structure list. This article will show you how to use Spire.Doc to get the differences by comparing two Word documents.

C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting.Revisions;
using System;

namespace GetWordDifferences
    {
    class Program
    {
        static void Main(string[] args)

        {
            //Load the first Word document
            Document doc1 = new Document();
            doc1.LoadFromFile("Sample1.docx");

            //Load the second Word document
            Document doc2 = new Document();
            doc2.LoadFromFile("Sample2.docx");

            //Compare the two Word documents
            doc1.Compare(doc2, "Author");

            foreach (Section sec in doc1.Sections)
            {
                foreach (DocumentObject docItem in sec.Body.ChildObjects)
                {
                    if (docItem is Paragraph)
{
                        Paragraph para = docItem as Paragraph;
                        if (para.IsInsertRevision)
                        { 
                            EditRevision insRevison = para.InsertRevision;
                            EditRevisionType insType = insRevison.Type; 
                            string insAuthor = insRevison.Author; 
                            DateTime insDateTime = insRevison.DateTime; 
                        }

                        else if (para.IsDeleteRevision)
                        { 
                            EditRevision delRevison = para.DeleteRevision; 
                            EditRevisionType delType = delRevison.Type; 
                            string delAuthor = delRevison.Author; 
                            DateTime delDateTime = delRevison.DateTime; 
                        }

                        foreach (ParagraphBase paraItem in para.ChildObjects)
                        {
                            if (paraItem.IsInsertRevision)
                            { 
                                EditRevision insRevison = paraItem.InsertRevision; 
                                EditRevisionType insType = insRevison.Type; 
                                string insAuthor = insRevison.Author; 
                                DateTime insDateTime = insRevison.DateTime; 
                            }

                            else if (paraItem.IsDeleteRevision)
                            { 
                                EditRevision delRevison = paraItem.DeleteRevision; 
                                EditRevisionType delType = delRevison.Type; 
                                string delAuthor = delRevison.Author; 
                                DateTime delDateTime = delRevison.DateTime; 
                            }

                        }
                    }
                }
            }

            //Get the difference about revisions
            DifferRevisions differRevisions = new DifferRevisions(doc1);
            var insetRevisionsList = differRevisions.InsertRevisions;
            var deletRevisionsList = differRevisions.DeleteRevisions;      
        }
    }
 }
VB.NET
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Formatting.Revisions
Imports System

Namespace GetWordDifferences
    
    Class Program
        
        Private Shared Sub Main(ByVal args() As String)
            'Load the first Word document
            Dim doc1 As Document = New Document
            doc1.LoadFromFile("Sample1.docx")
            'Load the second Word document
            Dim doc2 As Document = New Document
            doc2.LoadFromFile("Sample2.docx")
            'Compare the two Word documents
            doc1.Compare(doc2, "Author")
            For Each sec As Section In doc1.Sections
                For Each docItem As DocumentObject In sec.Body.ChildObjects
                    If (TypeOf docItem Is Paragraph) Then
                        Dim para As Paragraph = CType(docItem,Paragraph)
                        If para.IsInsertRevision Then
                            Dim insRevison As EditRevision = para.InsertRevision
                            Dim insType As EditRevisionType = insRevison.Type
                            Dim insAuthor As String = insRevison.Author
                            Dim insDateTime As DateTime = insRevison.DateTime
                        ElseIf para.IsDeleteRevision Then
                            Dim delRevison As EditRevision = para.DeleteRevision
                            Dim delType As EditRevisionType = delRevison.Type
                            Dim delAuthor As String = delRevison.Author
                            Dim delDateTime As DateTime = delRevison.DateTime
                        End If
                        
                        For Each paraItem As ParagraphBase In para.ChildObjects
                            If paraItem.IsInsertRevision Then
                                Dim insRevison As EditRevision = paraItem.InsertRevision
                                Dim insType As EditRevisionType = insRevison.Type
                                Dim insAuthor As String = insRevison.Author
                                Dim insDateTime As DateTime = insRevison.DateTime
                            ElseIf paraItem.IsDeleteRevision Then
                                Dim delRevison As EditRevision = paraItem.DeleteRevision
                                Dim delType As EditRevisionType = delRevison.Type
                                Dim delAuthor As String = delRevison.Author
                                Dim delDateTime As DateTime = delRevison.DateTime
                            End If
                            
                        Next
                    End If
                    
                Next
            Next
            'Get the difference about revisions
            Dim differRevisions As DifferRevisions = New DifferRevisions(doc1)
            Dim insetRevisionsList = differRevisions.InsertRevisions
            Dim deletRevisionsList = differRevisions.DeleteRevisions
        End Sub
    End Class
End Namespace

This article demonstrates how to find the text that matches a specific regular expression in a PDF document using Spire.PDF for Java.

" //Load a PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.pdf");

        //Create a object of PdfTextFind collection
        PdfTextFindOptions findOptions = new PdfTextFindOptions();

        //Loop through the pages
        for (Object page : (Iterable) pdf.getPages()) {
            PdfPageBase pageBase = (PdfPageBase) page;

            //Define a regular expression
            String pattern = "\\#\\w+\\b";
            // Set search parameter to use regular expression
            findOptions.setTextFindParameter(EnumSet.of(TextFindParameter.Regex));

            // Create a text finder object for the page
            PdfTextFinder textFinder = new PdfTextFinder(pageBase);

            // Find text fragments that match the pattern
            List finds = textFinder.find(pattern, findOptions);

            //Highlight the search results with yellow
            for (PdfTextFragment find : finds) {
                find.highLight(Color.yellow);
            }
        }

        //Save to file
        pdf.saveToFile("FindByPattern.pdf");"

Find Text in PDF by Regular Expression in Java

Monday, 20 July 2020 07:58

Edit Bookmarks in PDF in Java

This article demonstrates how to edit the existing bookmarks in a PDF file, for example, change the bookmark title, font color and text style using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;

public class EditBookmarks {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Load the PDF file
        doc.loadFromFile("Bookmarks.pdf");

        //Get the first bookmark
        PdfBookmark bookmark = doc.getBookmarks().get(0);
        //Change the title of the bookmark
        bookmark.setTitle("New Title");
        //Change the font color of the bookmark
        bookmark.setColor(new PdfRGBColor(new Color(255,0,0)));
        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Edit child bookmarks of the first bookmark
        for (Object Bookmark : (Iterable) bookmark) {
            PdfBookmark childBookmark=(PdfBookmark)Bookmark;
            childBookmark.setColor(new PdfRGBColor(new Color(0,0,255)));
            childBookmark.setDisplayStyle(PdfTextStyle.Bold);

            for (PdfBookmark Bookmark2 : (Iterable⁢PdfBookmark>) bookmark){
                PdfBookmark childBookmark2=(PdfBookmark)Bookmark2;
                childBookmark2.setColor(new PdfRGBColor(new Color(160,160,122)) );
                childBookmark2.setDisplayStyle(PdfTextStyle.Bold);
            }
        }

        //Save the result file
        doc.saveToFile("EditBookmarks.pdf");
        doc.close();
    }
}

Output:

Edit Bookmarks in PDF in Java

Monday, 30 January 2023 08:50

Java: Add, Edit, or Delete Bookmarks in PDF

A bookmark in a PDF document consists of formatted text linking to a specific section of the document. Readers can navigate through pages by simply clicking on the bookmarks displayed on the side of the page instead of scrolling up and down, which is very helpful for those huge documents. Moreover, well-organized bookmarks can also serve as contents. When you create a PDF document with a lot of pages, it’s better to add bookmarks to link to significant content. This article is going to show how to add, modify, and remove bookmarks in PDF documents using Spire.PDF for Java through programming.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.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.pdf</artifactId>
        <version>11.12.16</version>
    </dependency>
</dependencies>

Add Bookmarks to a PDF Document

Spire.PDF for Java provides PdfDocument.getBookmarks().add() method to add bookmarks to a PDF document. In addition to adding primary bookmarks, we can use PdfBookmark.add() method to add a sub-bookmark to a primary bookmark. There are also many other methods under PdfBookmark class which are used to set the destination, text color, and text style of bookmarks. The detailed steps of adding bookmarks to a PDF document are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the PDF document to add bookmarks and set their styles.
  • Add a primary bookmark to the document using PdfDocument.getBookmarks().add() method.
  • Create a PdfDestination class object and set the destination of the primary bookmark using PdfBookmark.setAction() method.
  • Set the text color of the primary bookmark using PdfBookmark.setColor() method.
  • Set the text style of the Primary bookmark using PdfBookmark.setDisplayStyle() method.
  • Add a sub-bookmark to the primary bookmark using PdfBookmark.add() method.
  • Use the above methods to set the destination, text color, and text style of the sub-bookmark.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;
import java.awt.geom.Point2D;

public class addBookmark {
    public static void main(String[] args) {

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF file
        pdf.loadFromFile("There's No Planet B.pdf");

        //Loop through the pages in the PDF file
        for(int i = 0; i< pdf.getPages().getCount();i++) {
            PdfPageBase page = pdf.getPages().get(i);
            //Add a bookmark
            PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", i + 1));
            //Set the destination page and location
            PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 0));
            bookmark.setAction(new PdfGoToAction(destination));
            //Set the text color
            bookmark.setColor(new PdfRGBColor(new Color(139, 69, 19)));
            //Set the text style
            bookmark.setDisplayStyle(PdfTextStyle.Bold);
            //Add a child bookmark
            PdfBookmark childBookmark = bookmark.add(String.format("Sub-Bookmark-%s", i + 1));
            //Set the destination page and location
            PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 100));
            childBookmark.setAction(new PdfGoToAction(childDestination));
            //Set the text color
            childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
            //Set the text style
            childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }

        //Save the result file
        pdf.saveToFile("AddBookmarks.pdf");
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

Edit Bookmarks in a PDF Document

We can also use methods of PdfBookmark class in Spire.PDF for Java to edit existing PDF bookmarks. The detailed steps are as follows.

  • Create a PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first bookmark using PdfDocument.getBookmarks().get() method.
  • Change the title of the bookmark using PdfBookmark.setTitle() method.
  • Change the font color of the bookmark using PdfBookmark.setColor() method.
  • Change the outline text style of the bookmark using PdfBookmark.setDisplayStyle() method.
  • Change the text color and style of the sub-bookmark using the above methods.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;

public class editBookmarks {
    public static void main(String[] args) {

        //Create a PdfDocument class instance
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("AddBookmarks.pdf");

        //Get the first bookmark
        PdfBookmark bookmark = doc.getBookmarks().get(0);
        //Change the title of the bookmark
        bookmark.setTitle("New Title");
        //Change the font color of the bookmark
        bookmark.setColor(new PdfRGBColor(new Color(255,0,0)));
        //Change the outline text style of the bookmark
        bookmark.setDisplayStyle(PdfTextStyle.Italic);

        //Edit sub-bookmarks of the first bookmark
        for (Object Bookmark : (Iterable) bookmark) {
            PdfBookmark childBookmark=(PdfBookmark)Bookmark;
            childBookmark.setColor(new PdfRGBColor(new Color(0,0,255)));
            childBookmark.setDisplayStyle(PdfTextStyle.Bold);
        }


        //Save the result file
        doc.saveToFile("EditBookmarks.pdf");
        doc.close();
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

Delete Bookmarks from a PDF Document

We can use Spire.PDF for Java to delete any bookmark in a PDF document. PdfDocument.getBookmarks().removeAt() is used to remove a specific primary bookmark, PdfDocument.getBookmarks().clear() method is used to remove all bookmarks, and PdfBookmark.removeAt() method is used to remove a specific sub-bookmark of a primary bookmark. The detailed steps of removing bookmarks form a PDF document are as follows.

  • Create PdfDocument class instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first bookmark using PdfDocument.getBookmarks().get() method.
  • Remove the sub-bookmark of the first bookmark using PdfBookmark.removeAt() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.PdfBookmark;

public class deleteBookmarks {
    public static void main(String[] args) {

        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();

        //Load the PDF file
        pdf.loadFromFile("AddBookmarks.pdf");

        //Get the first bookmark
        PdfBookmark pdfBookmark = pdf.getBookmarks().get(0);

        //Delete the sub-bookmark of the first bookmark
        pdfBookmark.removeAt(0);

        //Delete the first bookmark along with its child bookmark
        //pdf.getBookmarks().removeAt(0);

        //Delete all the bookmarks
        //pdf.getBookmarks().clear();

        //Save the result file
        pdf.saveToFile("DeleteBookmarks.pdf");
    }
}

Java: Add, Edit, or Delete Bookmarks in PDF

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.

This article will demonstrate how to use Spire.Presentaion for Java to remove text watermark and image watermark from the presentation slides.

Firstly, view the sample PowerPoint document with text and image watermark:

Java remove text or image watermark from presentation slides

import com.spire.presentation.*;
import com.spire.presentation.drawing.*;

public class removeTextOrImageWatermark {

    public static void main(String[] args) throws Exception {
        //Load the sample document
        Presentation presentation = new Presentation();
        presentation.loadFromFile("Sample.pptx");

        //Remove text watermark by removing the shape which contains the string "E-iceblue".
        for (int i = 0; i < presentation.getSlides().getCount(); i++)
        {
            for (int j = 0; j < presentation.getSlides().get(i).getShapes().getCount(); j++)
            {
                if (presentation.getSlides().get(i).getShapes().get(j) instanceof IAutoShape)
                {
                    IAutoShape shape = (IAutoShape)presentation.getSlides().get(i).getShapes().get(j);
                    if (shape.getTextFrame().getText().contains("E-iceblue"))
                    {
                        presentation.getSlides().get(i).getShapes().remove(shape);
                    }
                }
            }
        }

        //Remove image watermark
        for (int i = 0; i < presentation.getSlides().getCount(); i++)
        {
            presentation.getSlides().get(i).getSlideBackground().getFill().setFillType(FillFormatType.NONE);
        }

        //Save to file.
        presentation.saveToFile("removeTextOrImageWatermark.pptx", FileFormat.PPTX_2013);
    }
}

Effective screenshot after removing text or image watermark:

Java remove text or image watermark from presentation slides

Tuesday, 12 November 2019 05:56

Modify Hyperlinks in Word in Java

This article demonstrates how to modify hyperlinks in Word including modifying hyperlink address and display text using Spire.Doc for Java.

Below is the sample Word document we used for demonstration:

Modify Hyperlinks in Word in Java

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.util.ArrayList;
import java.util.List;

public class ModifyHyperlink {
    public static void main(String[] args) {
        //Load Word document
        Document doc = new Document();
        doc.loadFromFile("Hyperlink.docx");

       ⁢List⁢<Field> hyperlinks = new ArrayList<>();

        //Loop through the section in the document
        for (Section section : (Iterable<Section>) doc.getSections()
                ) {
            //Loop through the section in the document
            for (Paragraph para : (Iterable<Paragraph>) section.getParagraphs()
                    ) {
                for (DocumentObject obj:(Iterable<DocumentObject>) para.getChildObjects()
                     ) {
                    if (obj.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                        Field field = (Field) obj;
                        if (field.getType().equals(FieldType.Field_Hyperlink)) {
                            hyperlinks.add(field);
                        }
                    }
                }
            }
        }

        hyperlinks.get(0).setCode("HYPERLINK \"http://www.google.com\"");
        hyperlinks.get(0).setFieldText("www.google.com");

        doc.saveToFile("EditHyperlink.docx", FileFormat.Docx_2013);
    }
}

Output:

Modify Hyperlinks in Word in Java

Tuesday, 29 October 2019 08:33

Rotate shapes on Word document in Java

This article demonstrates how to rotate shapes on a Word document using Spire.Doc for Java.

import com.spire.doc.Document;
import com.spire.doc.DocumentObject;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;

public class RotateShape {
    public static void main(String[] args) throws Exception {

               //Load the Sample Word document.
                Document doc = new Document();
                doc.loadFromFile("InsertShapes.docx");

               //Get the first section
                Section sec = doc.getSections().get(0);

                //Traverse every paragraphs to get the shapes and rotate them
                for ( Paragraph para: (Iterable<⁢Paragraph>) sec.getParagraphs()) {
                    for (DocumentObject obj : (Iterable⁢<DocumentObject>) para.getChildObjects()) {

                        if (obj instanceof ShapeObject) {
                            ((ShapeObject) obj).setRotation(20);

                        }
                    }
                }
                //Save to file
                doc.saveToFile("output/RotateShape.docx", FileFormat.Docx);

    }
}

Effective screenshot after rotating the shapes on word:

Rotate shapes on Word document in Java

Thursday, 17 October 2019 09:30

Add Data Labels to Chart in PowerPoint in Java

This article demonstrates how to add data labels to a chart and set the appearance (border style and fill style) for the data labels in PowerPoint using Spire.Presentation for Java. Note some chart types like Surface3D, Surface3DNoColor, Contour and ContourNoColor do not support data labels.

Below screenshot shows the original chart before adding data labels:

Add Data Labels to Chart in PowerPoint in Java

import com.spire.presentation.FileFormat;
import com.spire.presentation.ISlide;
import com.spire.presentation.Presentation;
import com.spire.presentation.charts.IChart;
import com.spire.presentation.charts.entity.ChartDataLabel;
import com.spire.presentation.charts.entity.ChartSeriesDataFormat;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;

public class AddDataLabelsToChart {
    public static void main(String[] args) throws Exception {
        //Load the PowerPoint document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Chart.pptx");

        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);
        //Get the chart in the slide
        IChart chart = (IChart)slide.getShapes().get(0);

        //Loop through the series in the chart
        for (ChartSeriesDataFormat series:(Iterable<ChartSeriesDataFormat>)chart.getSeries()) {
             ) {
            //Add data labels for the data points in each series
            for(int i = 0; i < 4; i++){
                ChartDataLabel dataLabel = series.getDataLabels().add();
                //Show label value
                dataLabel.setLabelValueVisible(true);
                //Show series name
                dataLabel.setSeriesNameVisible(true);
                //Set border line style
                dataLabel.getLine().setFillType(FillFormatType.SOLID);
                dataLabel.getLine().getSolidFillColor().setColor(Color.RED);
                //Set fill style
                dataLabel.getFill().setFillType(FillFormatType.SOLID);
                dataLabel.getFill().getSolidColor().setColor(Color.YELLOW);
            }
        }

        //Save the resultant document
        ppt.saveToFile("DataLabels.pptx", FileFormat.PPTX_2013);
    }
}

Output:

Add Data Labels to Chart in PowerPoint in Java