Wednesday, 12 August 2020

Add, Edit, Read and Delete Bookmarks in a PDF Document in Java

It is very useful to add bookmarks to PDF files, especially technical documents and instruction manuals. After you add bookmarks to a PDF file, you can access to a specific part of a PDF file easily and efficiently. In this article, I’ll show you how to add, edit, read and delete bookmarks in a PDF document by using Free Spire.PDF for Java.

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> 

            <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>2.6.3</version> 

    </dependency> 

</dependencies>

Add Bookmarks

The first step of adding bookmarks is to loop through all pages in a PDF file, and then add bookmarks and childbookmarks for each page. At the same time, you can set text color and style for bookmarks by using setColor and setDisplayStyle methods.

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 instance
       
PdfDocument pdf = new PdfDocument();
       
//Load a PDF file
       
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.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 bookmark
           
PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", i + 1));
           
//Set destination page and location
           
PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 50));
            bookmark.setAction(
new PdfGoToAction(destination));
           
//Set text color
           
bookmark.setColor(new PdfRGBColor(new Color(139, 7, 126)));
           
//Set text style
           
bookmark.setDisplayStyle(PdfTextStyle.Bold);

           
//Add child bookmark
           
PdfBookmark childBookmark = bookmark.add(String.format("ChildBookmark-%s", i + 1));
           
//Set destination page and location
           
PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 200));
            childBookmark.setAction(
new PdfGoToAction(childDestination));
           
//Set text color
           
childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
           
//Set text style
           
childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }
       
//Save the result file
       
pdf.saveToFile("output/AddBookmarks.pdf");
    }
}

Output

Edit Bookmarks

Using setTitle, setColor and setDisplayStyle methods, you can change the title, color and style of bookmarks 
and childbookmarks in a PDF file.
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 EditBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument doc = new PdfDocument();
       
//Load the PDF file
       
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\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(2, 139, 2)));
       
//Change the outline text style of the bookmark
       
bookmark.setDisplayStyle(PdfTextStyle.Italic);
       
//Edit child bookmarks of the first bookmark
       
for (PdfBookmark childBookmark : (Iterable <PdfBookmark>) bookmark) {
            childBookmark.setColor(
new PdfRGBColor(new Color(255, 19, 24)));
            childBookmark.setDisplayStyle(PdfTextStyle.
Bold);
        }
       
//Save the result file
       
doc.saveToFile("output/EditBookmarks.pdf");
        doc.close();
    }
    }

Output

Read Bookmarks

To read bookmarks in a PDF file, you first get the bookmark collection by using pdf.getBookmarks() method,
and then create a .txt file and insert bookmarks in it.
import com.spire.pdf.*;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfBookmarkCollection;
import java.io.FileWriter;
import java.io.IOException;
public class ReadBookmark {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Load the PDF file
      
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");
       
//Get bookmarkCollection
       
PdfBookmarkCollection bookmarkCollection = pdf.getBookmarks();
       
//Crate a StringBuilder instance
       
StringBuilder stringbuilder = new StringBuilder();
       
//Define a method to get bookmarks
       
GetBookmarkTitle(bookmarkCollection, stringbuilder);
       
//Create a .txt file,and write down bookmarks
       
FileWriter writer;
       
try {
            writer =
new FileWriter("output/ReadBookmark.txt");
            writer.write(stringbuilder.toString());
            writer.flush();
        }
catch (IOException e) {
            e.printStackTrace();
        }
        pdf.dispose();
    }
   
// Define a method to get the titles of bookmarks
   
static void GetBookmarkTitle(PdfBookmarkCollection bookmarkCollection, StringBuilder stringbuilder)
    {
       
if (bookmarkCollection.getCount()> 0)
        {
           
for(int i = 0 ; i< bookmarkCollection.getCount(); i++ )
            {
                PdfBookmark parentBookmark = bookmarkCollection.get(i);
                stringbuilder.append(parentBookmark.getTitle());
                GetBookmarkTitle(parentBookmark, stringbuilder);
            }
        }
    }
}

Output

Delete Bookmarks

You can easily delete a specific child bookmark, a parent bookmark along with its child bookmarks or all the bookmarks from a PDF file.

import com.spire.pdf.PdfDocument;
public class DeleteBookmark {

public static void main(String[] args) {
//Create a PdfDocument instance

PdfDocument pdf = new PdfDocument();

//Load the PDF file
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\AddBookmarks.pdf");

//Delete the first child bookmark

//pdf.getBookmarks().get(0).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("output/DeleteBookmarks.pdf");
    }
}





Wednesday, 5 August 2020

Add and Rotate Shapes in Word Document in Java

When creating a Word document, you can add many types of shapes, such as triangle, rectangle and circle, to highlight important items. Bring attention to those items helps readers to better understand the content of the document. Here I’ll show you how to add or rotate shapes in a Word document by using Free Spire.Doc for Java.

BEFORE START

Please download the latest version of Free Spire.Doc for Java from the link, unzip it and manually add Spire.Doc.jar located in the lib folder to your JAVA project as a dependency.

Besides, if you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

<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>2.7.3</version>

    </dependency>

</dependencies>

Code Snippets

Add Single Shapes
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;

public class AddShapes {
public static void main(String[] args) {
//create a Word document.
Document doc = new Document();

//add a section and a paragraph
Section sec = doc.addSection();
Paragraph para = sec.addParagraph();

//insert a rectangle
ShapeObject rectangle = para.appendShape(130, 80, ShapeType.Rectangle);
rectangle.setFillColor(Color.green);
rectangle.setStrokeColor(Color.white);
rectangle.setVerticalPosition(50);

//insert a triangle
ShapeObject triangle = para.appendShape((float)(160/Math.sqrt(3)),80, ShapeType.Triangle);
triangle.setStrokeColor(Color.blue);
triangle.setFillColor(Color.red);
triangle.setVerticalPosition(50);
triangle.setHorizontalPosition(200);

//insert a circle
ShapeObject circle = para.appendShape(220,80, ShapeType.Ellipse);
circle.setFillColor(Color.yellow);
circle.setStrokeWeight(5);
circle.setStrokeColor(Color.lightGray);
circle.setVerticalPosition(50);
circle.setHorizontalPosition((float)(220 + 160/Math.sqrt(3)));
//save to file
doc.saveToFile("output/InsertShapes.docx", FileFormat.Docx);
}
}

Output

Add Shape Groups

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.ShapeType;
import com.spire.doc.fields.ShapeGroup;
import com.spire.doc.fields.ShapeObject;
import java.awt.*;

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

//add a section and a paragraph
Section sec = doc.addSection();
Paragraph para = sec.addParagraph();

//get page width
float pageWidth = sec.getPageSetup().getClientWidth();

//add a shape group, specifying width, height and horizontal position
ShapeGroup shapegroup = para.appendShapeGroup(200, 150);
shapegroup.setHorizontalPosition((pageWidth - 200) / 2);

//calculate the scale ratio
float X = (shapegroup.getWidth() / 1000.0f);
float Y = (shapegroup.getHeight() / 1000.0f);

//create a circle
ShapeObject circle_1 = new ShapeObject(doc, ShapeType.Ellipse);
circle_1.setWidth(80 / X);
circle_1.setHeight(80 / Y);
circle_1.setFillColor(new Color(176, 196, 222));
circle_1.setStrokeColor(new Color(176, 196, 222));
circle_1.setHorizontalPosition(60 / X);//set its horizontal position relative to shape group

//add the circle to shape group
shapegroup.getChildObjects().add(circle_1);

//add two more circles to shape group
ShapeObject circle_2 = new ShapeObject(doc, ShapeType.Ellipse);
circle_2.setWidth(80 / X);
circle_2.setHeight(80 / Y);
circle_2.setFillColor(new Color(0, 128, 128));
circle_2.setStrokeColor(new Color(0, 128, 128));
circle_2.setHorizontalPosition(30 / X);
circle_2.setVerticalPosition(50 / Y);
shapegroup.getChildObjects().add(circle_2);
ShapeObject circle_3 = new ShapeObject(doc, ShapeType.Ellipse);
circle_3.setWidth(80 / X);
circle_3.setHeight(80 / Y);
circle_3.setFillColor(new Color(72, 61, 139));
circle_3.setStrokeColor(new Color(72, 61, 139));
circle_3.setHorizontalPosition(90 / X);
circle_3.setVerticalPosition(50 / Y);
shapegroup.getChildObjects().add(circle_3);

//save the document
doc.saveToFile("output/InsertShapeGroup.docx", FileFormat.Docx_2010);
}
}

Output

Rotate Shapes
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 RotateShapes {
public static void main(String[] args) {
//Load the Sample Word document
Document doc = new Document();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\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);
}
}

Output


Wednesday, 29 July 2020

Insert, Hide and Delete Excel Rows and Columns in Java

If you need to add new data or delete existing data in an Excel worksheet, you can insert or delete rows or columns in the worksheet. Besides, you will have a cleaner spreadsheet without deleting data you might need later by hiding rows and columns. In this article, I’ll show you how to insert, hide and delete Excel rows and columns by using Free Spire.XLS for Java.

ADD JAR TO PROJECT

Download the latest version of Free Spire.XLS forJava, unzip it and add Spire.Xls.jar located in the “lib” folder to your Java project as a dependency.

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

<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>2.2.0</version>  
    </dependency>  
</dependencies>

Using the code

 1. Insert Rows and Columns in Excel

By using the InsertRow and InsertColumn methods, we can insert one or several rows and columns in Excel workbook. Below are the code snippets.

import com.spire.xls.*;

public class AddRowsAndColumns {
public static void main(String[] args) {
//Load the sample Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

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

//Insert a row into the worksheet.
worksheet.insertRow(2);

//Insert a column into the worksheet.
worksheet.insertColumn(2);

//Insert multiple rows into the worksheet.
worksheet.insertRow(5, 2);

//Insert multiple columns into the worksheet.
worksheet.insertColumn(5, 2);
//Save to file.
workbook.saveToFile("output/InsertRowsAndColumns.xlsx", ExcelVersion.Version2013);
}
}

Effective screenshot after inserting the empty rows and columns:



2.Hide Rows and Columns in Java

import com.spire.xls.*;

public class HideRowsAndColumns {
public static void main(String[] args) {
//Load the sample Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\InsertRowsAndColumns.xlsx");

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

//Hide the column of the worksheet.
worksheet.hideColumn(2);

//Hide the row of the worksheet
worksheet.hideRow(3);

//Save to file.
workbook.saveToFile("output/HideRowAndColumn.xlsx", ExcelVersion.Version2013);
}
}

Effective screenshot after hiding the second column and the third row:


3. Delete Rows and Columns in Excel


import com.spire.xls.*;

public class DeleteRowsAndColumns {
public static void main(String[] args) {
//Load the sample Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertRowsAndColumns.xlsx");

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

//Delete a row from the worksheet.
worksheet.deleteRow(2);

//Delete multiple columns from the worksheet.
worksheet.deleteColumn(5, 2);

//Save to file.
workbook.saveToFile("output/DeleteRowAndColumn.xlsx", ExcelVersion.Version2013);
}
}

Effective screenshot after deleting the second row and the fifth and sixth columns:


Tuesday, 21 July 2020

Add Shapes to PowerPoint in Java

Shapes in PowerPoint can be used to add interest to any presentation, emphasize a point or create custom graphics based on your requirement. Generally, shapes used in PowerPoint are circles, rectangles, squares, pentagons and so on. Furthermore, individual shapes can be merged in to other complex shapes. Let’s take a look at how to add individual shapes or group shapes to PowerPoint by using Free Spire.Presentation for Java.

ADD SPIRE.PRESENTATION.JAR AS 

DEPENDENCY

Download the latest version of Free Spire.Presentation for Java from the link, unzip it and add Spire.Presentation.jar located in the “lib” folder to your Java IDEA.

Of course, if you are creating a Maven project, you can easily add the jar dependency by adding the following configurations to the pom.xml.

<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</artifactId>

        <version>3.5.4/version>

    </dependency>

</dependencies>

 

Using the code

Sample 1 Add Shapes

import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

public class AddShape {
   
public static void main(String[] args) throws Exception{
       
//create a PowerPoint document
       
Presentation presentation = new Presentation();

       
//append a Triangle and fill the shape with a solid color
       
IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.TRIANGLE, new Rectangle2D.Double(115, 130, 100, 100));
        shape.getFill().setFillType(FillFormatType.
SOLID);
        shape.getFill().getSolidColor().setColor(Color.
orange);
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

       
//append an Ellipse and fill the shape with a picture
       
shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.ELLIPSE, new Rectangle2D.Double(290, 130, 150, 100));
        shape.getFill().setFillType(FillFormatType.
PICTURE);
        shape.getFill().getPictureFill().setFillType(PictureFillType.
STRETCH);
        BufferedImage image = ImageIO.read(
new File("C:\\Users\\Test1\\Desktop\\Image.jpg"));
        shape.getFill().getPictureFill().getPicture().setEmbedImage(presentation.getImages().append(image));
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

       
//append a Heart and fill the shape with a pattern
       
shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.HEART, new Rectangle2D.Double(515, 130, 130, 100));
        shape.getFill().setFillType(FillFormatType.
PATTERN);
        shape.getFill().getPattern().setPatternType(PatternFillType.
CROSS);
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

       
//append a Five-Pointed Star and fill the shape with a gradient color
       
shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.FIVE_POINTED_STAR, new Rectangle2D.Double(115, 300, 100, 100));
        shape.getFill().setFillType(FillFormatType.
GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(
0, KnownColors.BLACK);
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

       
//append a Rectangle and fill the shape with gradient color
       
shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(290, 300, 150, 100));
        shape.getFill().setFillType(FillFormatType.
GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(
0, KnownColors.LIGHT_SKY_BLUE);
        shape.getFill().getGradient().getGradientStops().append(
1, KnownColors.ROYAL_BLUE);
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

       
//append a Bent Up Arrow and fill the shape with gradient color
       
shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.BENT_UP_ARROW, new Rectangle2D.Double(515, 300, 130, 100));
        shape.getFill().setFillType(FillFormatType.
GRADIENT);
        shape.getFill().getGradient().getGradientStops().append(
1f, KnownColors.OLIVE);
        shape.getFill().getGradient().getGradientStops().append(
0, KnownColors.POWDER_BLUE);
        shape.getShapeStyle().getLineColor().setColor(Color.
white);

        
//save the document
       
presentation.saveToFile("output/AddShapes.pptx", FileFormat.PPTX_2010);
    }
}

Output

Sample 2 Add Group shapes

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;

public class GroupShape {
   
public static void main(String[] args) throws Exception{
       
//create a PowerPoint document
       
Presentation ppt = new Presentation();
       
//get the first slide
       
ISlide slide = ppt.getSlides().get(0);

       
//add a rectangle shape to the slide
       
IShape rectangle = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Double(20,100,200,40));
        rectangle.getFill().setFillType(FillFormatType.
SOLID);
        rectangle.getFill().getSolidColor().setKnownColor(KnownColors.
GOLD);
        rectangle.getLine().setWidth(
0.1f);

       
//add a ribbon shape to the slide
       
IShape ribbon = slide.getShapes().appendShape(ShapeType.RIBBON_2, new Rectangle2D.Double(60, 75, 120, 80));
        ribbon.getFill().setFillType(FillFormatType.
SOLID);
        ribbon.getFill().getSolidColor().setKnownColor(KnownColors.
PURPLE);
        ribbon.getLine().setWidth(
0.1f);

       
//add the shapes to a list
       
ArrayList list = new ArrayList();
        list.add((Shape)rectangle);
        list.add((Shape)ribbon);

       
//group the shapes
       
ppt.getSlides().get(0).groupShapes(list);

       
//save the resultant document
       
ppt.saveToFile("output/GroupShapes.pptx", FileFormat.PPTX_2013);
    }
}

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...