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>12.3.9</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 demonstrates how to detect whether an Excel document is password protected or not using Spire.XLS for Java.

import com.spire.xls.*;

public class DetectProtectedOrNot  {
    public static void main(String[] args) {
        //Get the file path
        String filePath= "C:\\Users\\Administrator\\Desktop\\sample.xlsx";

        //Detect whether the workbook is password protected or not
        Boolean isProtected = Workbook.isPasswordProtected(filePath);

        //Print results
        if (isProtected) {
            System.out.print("The document is password protected.");
        }
        else {
            System.out.print("The document is not protected.");
        }
    }
}

Detect if an Excel Document is Password Protected in Java

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

This article demonstrates how to highlight the highest and lowest value in a cell rang through conditional formatting. You can also highlight the top 5 or bottom 5 values by passing 5 to setRank() method in the code snippet below.

import com.spire.xls.*;
import com.spire.xls.core.IConditionalFormat;
import com.spire.xls.core.spreadsheet.collections.XlsConditionalFormats;

import java.awt.*;

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

        //Create a Workbook object
        Workbook workbook = new Workbook();

        //Load the sample Excel file
        workbook.loadFromFile("G:\\360MoveData\\Users\\Administrator\\Desktop\\sales report.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Add a conditional formatting and specify ranges
        XlsConditionalFormats conditional = sheet.getConditionalFormats().add();
        conditional.addRange(sheet.getCellRange("B2:E5"));

        //Apply conditional formatting to highlight the highest value
        IConditionalFormat format1 = conditional.addTopBottomCondition(TopBottomType.Top,1);
        format1.setBackColor(Color.red);

        //Apply conditional formatting to highlight the lowest value
        IConditionalFormat format2 = conditional.addTopBottomCondition(TopBottomType.Bottom,1)
        format2.setBackColor(Color.yellow);

        //Save the document
        workbook.saveToFile("output/HighestLowestValue.xlsx", ExcelVersion.Version2016);


    }
}

Highlight Highest and Lowest Value in Excel in Java

This article demonstrates how to highlight the duplicate and unique values in a selected range through conditional formatting using Spire.XLS for Java.

import com.spire.xls.*;
import com.spire.xls.core.IConditionalFormat;
import com.spire.xls.core.spreadsheet.collections.XlsConditionalFormats;

import java.awt.*;

public class HighlightDuplicates  {
    public static void main(String[] args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();

        //Load a sample Excel file
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.xlsx");

        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Add a conditional formatting and specify ranges
        XlsConditionalFormats conditional = sheet.getConditionalFormats().add();
        conditional.addRange(sheet.getCellRange("A2:A11"));

        //Use conditional formatting to highlight duplicate values with red
        IConditionalFormat format1 = conditional.addCondition();
        format1.setFormatType(ConditionalFormatType.DuplicateValues);
        format1.setBackColor(Color.red);

        //Use conditional formatting to highlight unique values with yellow
        IConditionalFormat format2 = conditional.addCondition();
        format2.setFormatType(ConditionalFormatType.UniqueValues);
        format2.setBackColor(Color.yellow);

        //Save the document
        workbook.saveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2016);
    }
}

Highlight Dulicate and Unique Values in Excel in Java

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

Wednesday, 18 September 2019 06:33

Add Tooltip to the Searched Text on PDF in C#

This article demonstrates how to add tooltip to the text on an existing PDF document in C#. Spire.PDF for .NET supports to create tooltips by adding invisible button over the searched text from the PDF file.

Step 1: Load the sample document file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Sample.pdf");

Step 2: Searched the text “Add tooltip to PDF” from the first page of the sample document and get the position of it.

PdfPageBase page = doc.Pages[0];
PdfTextFinder finder = new PdfTextFinder(page);
finder.Options.Parameter =TextFindParameter.WholeWord;
List<PdfTextFragment> result = finder.Find("Add tooltip to PDF");
RectangleF rec = result[0].Bounds[0];

Step 3: Create invisible button on text position

PdfButtonField field1 = new PdfButtonField(page, "field1");
field1.Bounds = rec;

field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
field1.BorderWidth = 0;
field1.BackColor = Color.Transparent;
field1.ForeColor = Color.Transparent;
field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
field1.IconLayout.IsFitBounds = true;

Step 4: Set the content and format for the tooltip field.

field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
field1.BorderWidth = 0;
field1.BackColor = Color.Transparent;
field1.ForeColor = Color.Transparent;
field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
field1.IconLayout.IsFitBounds = true;

Step 5: Save the document to file.

doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF);

Effective screenshot after adding the tooltip to PDF:

C# add tooltip to the searched text on PDF

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Texts;
using System.Collections.Generic;
using System.Drawing;

namespace TooltipPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Sample.pdf");

            PdfPageBase page = doc.Pages[0];

            PdfTextFinder finder = new PdfTextFinder(page);
            finder.Options.Parameter =TextFindParameter.WholeWord;

            // Find the occurrences of the specified text
            List<PdfTextFragment> result = finder.Find("Add tooltip to PDF");
            RectangleF rec = result[0].Bounds[0];

            //Create invisible button on text position
            PdfButtonField field1 = new PdfButtonField(page, "field1");
            field1.Bounds = rec;

            field1.ToolTip = "E-iceblue Co. Ltd., a vendor of .NET, Java and WPF development components";
            field1.BorderWidth = 0;
            field1.BackColor = Color.Transparent;
            field1.ForeColor = Color.Transparent;
            field1.LayoutMode = PdfButtonLayoutMode.IconOnly;
            field1.IconLayout.IsFitBounds = true;

            doc.SaveToFile("Addtooltip.pdf", FileFormat.PDF);

        }
    }
}