Monday, 1 March 2021

【Java】Set the layout of the slide in PowerPoint documents

Microsoft PowerPoint includes 11 built-in slide layouts as below. In our daily work, we can use the slide layouts to reasonably and concisely lay out the text, images or other content in PowerPoint documents.

Requirement and Solution

Now, I want to insert the slide layouts into the slides using Java codes without installing Microsoft PowerPoint. Through survey and test, I find a free Java API called FreeSpire.Presentation for Java can do it. This component can not only set a single layout but also several different layouts.

Dependency

Before running codes, we need add Spire.presentation.jar in the library to IDEA. Download the package from the link and manually add the Jar file, or reference it by using the following Maven configuration in the pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Set a single layout

The following codes are used to set a layout called Title Slide for the first slide.

import com.spire.presentation.*;

public class SingleLayout {
public static void main(String[] args) throws Exception {
//Create an instance of Presentation
Presentation ppt = new Presentation();

//Remove the default slide
ppt.getSlides().removeAt(0);

//Append a slide and set the layout for slide
ISlide slide = ppt.getSlides().append(SlideLayoutType.TITLE);

//Add content for Title and Text
IAutoShape shape = (IAutoShape)slide.getShapes().get(0);
shape.getTextFrame().setText("Spire.Presentation for Java");

shape = (IAutoShape)slide.getShapes().get(1);
shape.getTextFrame().setText("Set the Layout of Slide as Title");

//Save the document
ppt.saveToFile("output/SingleSlideLayout.pptx", FileFormat.PPTX_2013);
ppt.dispose();
}
}
Output

Set multiple different layouts

The following codes are designed to set 11 different layouts for slides. The layouts include Title Slide, Title Only, Blank, Title and Content, Section Header, Two Content, Comparison, Content with Caption, Picture with Caption, Title and Vertical Text, Vertical Title and Text.

import com.spire.presentation.*;
public class MultipleLayout {
public static void main(String[] args) throws Exception {
//Create an instance of Presentation
Presentation presentation = new Presentation();

//Remove the default slide
presentation.getSlides().removeAt(0);

//Loop through slide layouts
for (SlideLayoutType type : SlideLayoutType.values())
{
//Append slide by specified slide layout
presentation.getSlides().append(type);
}

//Save the document
presentation.saveToFile("output/MultipleSlideLayout.pptx", FileFormat.PPTX_2013);
presentation.dispose();
}
}

Output




Thursday, 25 February 2021

Set an expiration date for a PDF document in Java

In daily work, in order to protect our document from being disclosed, we can set an expiration data for it. The document can’t be opened once the expiration date has gone. Today, I’ll introduce how to set an expiration date or a PDF document in Java using a free API called Free Spire.PDF for Java.

About Free Spire.PDF for Java

Free Spire.PDF for Java is a PDF API that enables Java applications to read, write and save PDF documents without using Adobe Acrobat. Using this Java PDF library, developers and programmers can implement rich capabilities to create PDF files from scratch or process existing PDF documents entirely on Java applications (J2SE and J2EE).

Dependency

First of all, please download the latest version of Free Spire.PDF for Java from the link, and add Spire.Pdf.jar to your project as a dependency.

Of course, if you are using maven, you can directly add the following code to your project's pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfJavaScriptAction;

public class ExpiryDate {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Load a PDF file
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

//Set expiration date and warning information,and then close the document through JavaScript
String javaScript = "var rightNow = new Date();"
+ "var endDate = new Date('February 26, 2021 14:40:59');"
+ "if(rightNow.getTime() > endDate)"
+ "app.alert('This document is no longer valid, please contact us for a updated one.',1);"
+ "this.closeDoc();";

//Create a PdfJavaScriptAction object based on the javascript
PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);

//Set PdfJavaScriptAction as the AfterOpenAction
doc.setAfterOpenAction(js);

//Save to file
doc.saveToFile("output/ExpirationDate.pdf", FileFormat.PDF);
}
}

Output



Wednesday, 24 February 2021

Add multiple image watermarks to Word documents in Java

I introduced how to add multiple text watermarks to a Word document in Java before. Today, this tutorial will demonstrate how to add multiple image watermarks to a Word document in Java.

Dependency

It’s worth mentioning that I used a free third-party library called Free Spire.doc for Java to achieve the effect I want. Before typing codes, you need to add the jar file in the library to IDEA. Please click the link to download the product package and manually add Spire.doc.jar to IDEA, or directly reference it using the following Maven configurations.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Using the code

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.HeaderFooter;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextWrappingStyle;
import com.spire.doc.fields.DocPicture;

public class Watermark {
public static void main(String[] args) {
//Load the sample file
Document doc=new Document();
doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.docx");
//Load the image
DocPicture picture = new DocPicture(doc);
picture.loadImage(
"C:\\Users\\Test1\\Desktop\\Image.png");

//Set the text wrapping style
picture.setTextWrappingStyle(TextWrappingStyle.Behind);

for (int n = 0; n < doc.getSections().getCount(); n++) {
Section section = doc.getSections().get(n);
//Get the head of section
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph paragrapg1;
if(header.getParagraphs().getCount()>0){
paragrapg1=header.getParagraphs().get(
0);

}
else {
//Add the header to the paragraph
paragrapg1 = header.addParagraph();
}

for (int p = 0; p < 3; p++) {

for (int q = 0; q < 2; q++) {
//copy the image and add it to many places
picture = (DocPicture)picture.deepClone();
picture.setVerticalPosition(
100 + 200 * p);
picture.setHorizontalPosition(
50 + 210 * q);
paragrapg1.getChildObjects().add(picture);
}
}
}
//Save the document to file
doc.saveToFile("output/AddMultipleImageWatermark.docx", FileFormat.Docx_2013);
}
}

Output




Sunday, 21 February 2021

How to merge Excel files using a free Java API

In the process of manipulating Excel files, it is a lot easier to process data in a single file instead of switching between numerous sources. In this article, I’m going to introduce how to copy data from one worksheet into another worksheet in the same Excel file, and how to copy sheets from multiple Excel workbooks into one workbook.

Dependency

I used a free Java API called Free Spire.XLS for Java in this tutorial. Before running codes, we need to insert the Jar file in the library into IDEA. You can download it from the website or directly reference it using the following Maven configurations.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

How to copy data from one worksheet to another worksheet

I have an Excel file which includes two worksheets as below. Now I want to copy the data and its format

in the second worksheet into the first worksheet.


Use the following codes to achieve the effect I mentioned above.

import com.spire.xls.*;

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

//Load a Excel file including two worksheets
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

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

//Get the second worksheet
Worksheet sheet2 = workbook.getWorksheets().get(1);

//Copy the data and format in the second worksheet into the first worksheet
sheet2.getAllocatedRange().copy(sheet1.getRange().get(sheet1.getLastRow() +1, 1));

//Save the resulting document
workbook.saveToFile("output/MergeWorksheets.xlsx", ExcelVersion.Version2013);
}
}

Output


How to copy sheets from multiple Excel workbooks into one workbook

In addition to merging worksheets, Free Spire.XLS for Java supports merging multiple Excel files into

a single file. The screenshot of the original files is shown as below.


Use the following codes to merge several Excel files into a single file.

import com.spire.xls.*;
public class MergeFiles {
public static void main(String[] args) {
//Input the two Excel files which are used to merge into a file
String[] inputFiles = new String[]{"C:\\Users\\Test1\\Desktop\\file1.xlsx","C:\\Users\\Test1\\Desktop\\file2.xlsx"};

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

//Clear all worksheets
newBook.getWorksheets().clear();

//Create another workbook
Workbook tempBook = new Workbook();

//Loop through the two Excel files, and copy worksheets in each Excel file into the new workbook
for (String file : inputFiles)
{
tempBook.loadFromFile(file);
for (Worksheet sheet : (Iterable<Worksheet>)tempBook.getWorksheets())
{
newBook.getWorksheets().addCopy(sheet, WorksheetCopyType.CopyAll);
}
}

//Save the resulting document
newBook.saveToFile("output/MergeFiles.xlsx", ExcelVersion.Version2013);

}
}

Output



Thursday, 18 February 2021

[Java] Add, Read and Delete Speaker Notes in a PowerPoint document

Speaker Notes in PowerPoint slides are a short paragraph that reminds the speaker of the contents of the current slide in the slide-show, and they are an important tool in ensuring a smooth presentation for your work. The most interesting thing about them is the fact that they are not viewable by the audience during a presentation. This article will show you how to add, read and delete speaker notes using Java codes.

Using the tool

In this tutorial, I used a free third-party library called FreeSpire.Presentation for Java. It is a professional PowerPoint API that enables developers to create, edit, read, convert and save PowerPoint documents in Java Applications without installing Microsoft PowerPoint.

Before typing codes, you need to add the Jar file in the library to your project. You can download it from the link, and manually add it to IDEA, or directly reference it using the following Maven configuration.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Add Speaker Notes

import com.spire.presentation.*;
public class AddSpeakerNotes {
public static void main(String[] args) throws Exception {
//Load the PowerPoint document
Presentation ppt = new Presentation();
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);
//Add note slide
NotesSlide notesSlide = slide.addNotesSlide();

//Add a paragraph to the note slide
ParagraphEx paragraph = new ParagraphEx();
paragraph.setText("Tips for making effective presentations:");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(0).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(0).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Use the slide master feature to create a consistent and simple design template.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(2).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Simplify and limit the number of words on each screen.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet type and style for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(3).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

//Add a paragraph to the note slide
paragraph = new ParagraphEx();
paragraph.setText("Use contrasting colors for text and background.");
notesSlide.getNotesTextFrame().getParagraphs().append(paragraph);
//Set the bullet and style type for the paragraph
notesSlide.getNotesTextFrame().getParagraphs().get(4).setBulletType(TextBulletType.NUMBERED);
notesSlide.getNotesTextFrame().getParagraphs().get(4).setBulletStyle(NumberedBulletStyle.BULLET_ARABIC_PERIOD);

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

Output


Read Speaker Notes

import com.spire.presentation.*;
import java.io.FileWriter;

public class ReadSpeakerNotes {
public static void main(String[] args) throws Exception {
//Load the PowerPoint document
Presentation ppt = new Presentation();
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\AddSpeakerNotes.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);

//Get the content of notes from note slide
StringBuilder buffer = new StringBuilder();
String notes = slide.getNotesSlide().getNotesTextFrame().getText();
buffer.append(notes);

//Save to .txt file
FileWriter writer = new FileWriter("output/ReadSpeakerNotes.txt");
writer.write(buffer.toString());
writer.flush();
writer.close();
}
}

Output



Delete Speaker Notes

import com.spire.presentation.*;

public class DeleteSpeakerNotes {
public static void main(String[] args) throws Exception {
//Load the PowerPoint document
Presentation ppt = new Presentation();
ppt.loadFromFile("C:\\Users\\Test1\\Desktop\\AddSpeakerNotes.pptx");

//Get the first slide
ISlide slide = ppt.getSlides().get(0);

//Delete all speaker notes from the note slide
slide.getNotesSlide().getNotesTextFrame().getParagraphs().clear();

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

Monday, 25 January 2021

Add an image stamp or a text stamp to a PDF document in Java

Adding an image stamp (such as Paid, Reviewed, and Approved) to a PDF document can give readers a simple meaning to indicate the status of the file. Besides, you can add a dynamic stamp which usually consists of some dynamic information, such as company name, “Approved By” and system date. This tutorial will introduce how to add an image stamp or a dynamic stamp to a PDF document using Java codes.

Dependency

Before running codes, we need to insert a Jar file into IDEA. You can download it from the website or directly reference it using the following Maven configurations.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Using the code

Add an image stamp

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTemplate;
import java.awt.geom.Rectangle2D;

public class ImageStamp {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();

//load a PDF document
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

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

//load an image file
PdfImage image = PdfImage.fromFile("C:\\Users\\Test1\\Desktop\\Image.png");

//get the width and height of the image
int width = image.getWidth();
int height = image.getHeight();

//create a PdfTemplate object based on the size of the image
PdfTemplate template = new PdfTemplate(width, height);

//draw image on the template
template.getGraphics().drawImage(image, 0, 0, width, height);

//create a rubber stamp annotation, specifying its location and position
Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 50), (float) (page.getActualSize().getHeight() - height - 30), width, height);
PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);

//create a PdfAppearance object
PdfAppearance pdfAppearance = new PdfAppearance(stamp);

//set the template as the normal state of the appearance
pdfAppearance.setNormal(template);

//apply the appearance to the stamp
stamp.setAppearance(pdfAppearance);

//add the stamp annotation to PDF
page.getAnnotationsWidget().add(stamp);

//save the file
doc.saveToFile("output/ImageStamp.pdf");
doc.close();
}
}

Output


Add a dynamic stamp

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;

public class DynamicStamp {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument document = new PdfDocument();

//load a PDF file
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

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

//create a pdf template
PdfTemplate template = new PdfTemplate(185, 50);

//create two fonts
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Elephant", Font.ITALIC,16), true);
PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", Font.ITALIC ,10), true);

//create a solid brush and a gradient brush
PdfSolidBrush solidBrush = new PdfSolidBrush(new PdfRGBColor(Color.blue));
Rectangle2D rect1 = new Rectangle2D.Float();
rect1.setFrame(new Point2D.Float(0,0),template.getSize());
PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1,new PdfRGBColor(Color.white),new PdfRGBColor(Color.orange),PdfLinearGradientMode.Horizontal);

//create rounded rectangle path
int CornerRadius = 20;
PdfPath path = new PdfPath();
path.addArc(template.getBounds().getX(), template.getBounds().getY(), CornerRadius, CornerRadius, 180, 90);
path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius,template.getBounds().getY(), CornerRadius, CornerRadius, 270, 90);
path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY()+ template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 0, 90);
path.addArc(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 90, 90);
path.addLine( template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, template.getBounds().getX(), template.getBounds().getY() + CornerRadius / 2);

//draw path on the template
template.getGraphics().drawPath(linearGradientBrush, path);
template.getGraphics().drawPath(PdfPens.getRed(), path);

//draw dynamic text on the template
String s1 = "APPROVED\n";
String s2 = "By Tony at " + dateToString(new java.util.Date(),"yyyy-MM-dd HH:mm:ss");
template.getGraphics().drawString(s1, font1, solidBrush, new Point2D.Float(5, 5));
template.getGraphics().drawString(s2, font2, solidBrush, new Point2D.Float(2, 28));

//create a rubber stamp, specifying its size and location
Rectangle2D rect2= new Rectangle2D.Float();
rect2.setFrame(new Point2D.Float((float)(page.getActualSize().getWidth()-250),(float)(page.getActualSize().getHeight()-120)), template.getSize());
PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect2);

//create a PdfAppearance object and apply the template as its normal state
PdfAppearance appearance = new PdfAppearance(stamp);
appearance.setNormal(template);

//apply the appearance to stamp
stamp.setAppearance(appearance);

//add the stamp annotation to annotation collection
page.getAnnotationsWidget().add(stamp);

//save the file
document.saveToFile("output/DynamicStamp.pdf");
document.close();
}

//convert date to string
public static String dateToString(java.util.Date date,String dateFormat) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
return format.format(date);
}
}

Output



Monday, 18 January 2021

Add and Remove Bookmarks in Word Documents using Java

The bookmark feature in a Word document is similar to a bookmark we used while reading a book. When you have a long document and need to return to specific locations in the document later for reviewing or editing, you can use the Bookmark feature in Microsoft Word. In this article, I’ll use Java codes to manipulate bookmarks including add and remove them in a Word document without installing Microsoft Office.

Kindly note that you need a third-party library while using Java codes to finish the actions above. Here I recommend a free library called Free Spire.Doc for Java. The first thing you need to do is adding the jar file to IDEA. You can download the package from the link or directly reference it using the following Maven configurations.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Add a Bookmark for the specified paragraph in a Word document

Free Spire.Doc for Java supports adding a bookmark to the specified paragraph through two provides which are

appendBookmarkStart (string name) and appendBookmarkEnd (string name). BookmarkStart represents the start

point of the bookmark, while BookmarkEnd represents the end point of the bookmark.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
public class AddBookmark {
public static void main(String[] args) {
//create a Document object
Document doc = new Document();

//load a Word file to test
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//get the paragraph where you want to insert bookmark
Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(4);

//Create a start bookmark and move it to the beginning of the paragraph
BookmarkStart start = paragraph.appendBookmarkStart("Bookmark1");
paragraph.getItems().insert(0,start);

//append a end bookmark at the end of the paragraph
paragraph.appendBookmarkEnd("Bookmark1");

//save the resulting file
doc.saveToFile("output/AddBookmark.docx", FileFormat.Docx_2013);
}
}

Output

Add a bookmark for the specified String in a Word document

At the same time, Free Spire.Doc for Java provides the findString () method to find the specified words where

we want to add a bookmark. And then use BookmarkStart and BookmarkEnd methods to locate the start point

and end point of the bookmark.

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.TextRange;

public class AddBookmarkToCharacter {
public static void main(String[] args) {
//Load a Word document to test
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmark.docx");

//Find the specified string
TextSelection textSelection = doc.findString("Before you fret too much over this",false,false);
TextRange range = textSelection.getAsOneRange();
Paragraph para = range.getOwnerParagraph();
int index = para.getChildObjects().indexOf(range);

//Add a bookmark to the specified string
BookmarkStart start = new BookmarkStart(doc,"Bookmark2");
BookmarkEnd end = new BookmarkEnd(doc, "Bookmark2");
para.getChildObjects().insert(index, start);
para.getChildObjects().insert(index + 2, end);

//Save the resulting document
doc.saveToFile("output/AppendBookmarkToCharacter.docx",FileFormat.Docx_2013);
doc.dispose();
}
}

Output


Remove a specified bookmark in a Word document

Every Word document contains a collection of bookmarks, which are accessible through the Bookmarks property

of Document class. We can find a specified bookmark by its index and remove it using the Bookmarks property.

import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveBookmark {
public static void main(String[] args) {
//create a Document object
Document doc = new Document();

//load a Word file to test
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\AppendBookmarkToCharacter.docx");

//get the first bookmark by its index
Bookmark bookmark = doc.getBookmarks().get(1);

//remove the bookmark
doc.getBookmarks().remove(bookmark);

//save the resulting file
doc.saveToFile("output/RemoveBookmark.docx", FileFormat.Docx);
}
}

Output





Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...