Monday, 28 September 2020

Merge Word Documents in Java using Spire.Doc for Java

For most people, when you want to combine multiple Word documents into one, what you’ll often do is copying content from each and pasting it into another document. To be honest, this method is time-consuming, especially when dealing with several documents or complex formatting. Here I’ll introduce a more efficient and convenient idea that merge Word documents in Java programmatically.

Before typing codes, please add Spire.Doc.jar into your project as a dependency. There are two method to do it. One is that download Free Spire.Doc for Java package from the link, unzip it and find Spire.Doc.jar in the “lib” folder. Finally add Spire.Doc.jar into IDEA. The other is that install Free Spire.Doc for Java from Maven repository. Create a Maven program, type the following codes in the pom.xml file, and click the button “Import Changes”.

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

Using the code

Free Spire.Doc for Java provides an insertTextFromFile() method which supports merging Word

documents by inserting content from a document into another document. In the resulting document,

the inserted content will start from a new page.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class MergeFiles1 {
   
public static void main(String[] args) {
       
//Load the first Word Document
       
Document document = new Document("C:\\Users\\Test1\\Desktop\\Sample1.docx");

        //Using insertTextFromFile method to insert the second document into the first document
       
document.insertTextFromFile("C:\\Users\\Test1\\Desktop\\Sample2.docx", FileFormat.
Docx_2013);
       
//Save the resulting document
       
document.saveToFile("Output/MergeFiles1.docx", FileFormat.Docx_2013);
    }
}

Output

Besides, if you want the inserted content to follow the last paragraph of the destination document

instead of starting from a new page, use the following method to clone sections of the source document

and then append to the last section of the destination document.

import com.spire.doc.Document;

import com.spire.doc.DocumentObject;

import com.spire.doc.FileFormat;
import com.spire.doc.Section;
public class MergeFiles2 {
   
public static void main(String[] args) {
      
//Load the first Word document
       
Document document1 = new Document("C:\\Users\\Test1\\Desktop\\Sample1.docx");
       
//Load the second Word document
       
Document document2 = new Document("C:\\Users\\Test1\\Desktop\\Sample2.docx");
       
//Get the last section of the first document
        
Section lastSection = document1.getLastSection();
       
//Add the sections of the second document to the last section of the first document
       
for (Section section:(Iterable <Section>)document2.getSections()) {
           
for (DocumentObject obj:(Iterable <DocumentObject>)section.getBody().getChildObjects()
            ) {                 lastSection.getBody().getChildObjects().add(obj.deepClone());
            }
        }
       
//Save the resulting document
       
document1.saveToFile("Output/MergeFiles2.docx", FileFormat.Docx_2013);
    }
}

Output



Thursday, 24 September 2020

Insert, Extract and Delete Images in Excel using Java

Although Excel documents are primarily used as a calculation program, in some situations you may want to store pictures along with data and associate an image with a particular piece of information. In this tutorial, I will show you how to insert an image to Excel, extract and delete images in Excel using Java programmatically without Microsoft Office installed in your system.

I.       How to insert an image to Excel

II.     How to extract images in Excel

III.   How to delete images in Excel

   A.  How to delete a specific image in Excel

   B.  How to delete all images in Excel

The Java API I used in this tutorial is Free Spire.XLS for Java, which enables developers to create, manage, manipulate, convert and print Excel worksheets without using Microsoft Office or Microsoft Excel.

Add Spire.Xls.jar to your project as a dependency

Method 1: Download the package Free Spire.XLS for Java from the link, unzip it and you’ll find Spire.Xls.jar in the “lib” folder. Finally just manually add it to your project as a dependency.

Method 2(Recommend): Install Spire.XLS for Java from Maven repository. Please create a Maven project, and specify e-iceblue Maven Repository configuration and define Spire.PDF for Java API dependency in your pom.xml as follows.

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

Finally, just click “Import Changes” to import the Spire.Pdf.jar. The following screenshot is what

it looks like finally.


How to insert an image to Excel?

Free Spire.XLS for Java offers the ExcelPicture method to insert an image to Excel file.

import com.spire.xls.ExcelPicture;

import com.spire.xls.ExcelVersion;

import com.spire.xls.Workbook;

import com.spire.xls.Worksheet;
public class AddImage {
   
public static void main(String[] args) {
       
//Create a Workbook instance
       
Workbook workbook = new Workbook();
       
//Load an Excel file
       
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);
       
//Add an image to the specific cell
       
ExcelPicture pic = sheet.getPictures().add(4, 2,"C:\\Users\\Test1\\Desktop\\Image.png");
       
//Set width and height of the image
       
pic.setWidth(400);
        pic.setHeight(
200);
       
//Save the resulting file
       
workbook.saveToFile("output/InsertImage.xlsx", ExcelVersion.Version2013);
    }
}

Output


How to extract images in Excel?

The first thing to extract images in Excel is load an Excel file and get the image in it, and then save

the image to disk.

import com.spire.xls.ExcelPicture;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ReadImage {
   
public static void main(String[] args) throws IOException {
       
//Create a Workbook instance
       
Workbook workbook = new Workbook();
        
//Load an Excel file
       
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImage.xlsx");
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);         //Get the first image in the worksheet
       
ExcelPicture pic = sheet.getPictures().get(0);
        BufferedImage loImage = pic.getPicture();
       
//Save to disk
       
ImageIO.write(loImage,"jpg",new File("output/ReadImage.jpg"));
    }
}

Output


Delete Images in Excel

Free Spire.XLS for Java not only supports deleting a specific image in Excel file by its index, but also

can delete all images using the “for” loop method.

l  Delete Specific Image

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class DeleteSpecificImage {
   
public static void main(String[] args) {
       
//Create a Workbook object
       
Workbook workbook = new Workbook();
       
//Load an Excel file
       
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImage.xlsx");
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);
       
//Delete a specific image by its index
       
sheet.getPictures().get(1).remove();
       
//Save the document
       
workbook.saveToFile("output/DeleteSpecificImage.xlsx", ExcelVersion.Version2013);
    }
}

l  Delete All images

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class DeleteAllImage {
   
public static void main(String[] args) {
       
//Create a Workbook object
       
Workbook workbook = new Workbook();
       
//Load an Excel file
       
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\InsertImage.xlsx");
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);
       
//Loop through the images inside the worksheet
       
for (int i = sheet.getPictures().getCount() - 1; i >= 0; i--) {
           
//Delete all images
            
sheet.getPictures().get(i).remove();
        }
       
//Save the document
       
workbook.saveToFile("output/DeleteAllImages.xlsx", ExcelVersion.Version2013);
    }
}

Conclusion

Through this tutorial, I believe you can better manipulate images in Excel file using Java programmatically.

In addition to those functions, Free Spire.XLS for Java has the ability to support amounts of other features.

Click the link for knowing more information.

Wednesday, 16 September 2020

Replace Text and an Image in PowerPoint in Java

It’s time-consuming to create a beautiful PowerPoint document completely through Java program. Here I recommend a method which not only saves time but also can achieve a perfect result. First, you need to use Microsoft Office to create a PowerPoint template, and then replace the text and pictures in the template through Java program.

Before typing codes, please make sure you have a required test environment which includes Intellij Idea2019.1, JDK 1.8.0 and Spire.Presentation.jar.

How to add Spire.Presentation.jar to your project?

Method 1: Download Free Spire.Presentation for Java package from the link, unzip it and find Spire.Presentation.jar in the “lib” folder, and add it into IDEA as a dependency.

Method 2: add Spire.Presentation.jar in your maven-based project using the following repository and dependency information.

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

    </dependency>

</dependencies>

Creating a PowerPoint template

Here I use Microsoft Office to create a PowerPoint template with text and an image. Meanwhile, we can set the font, font size and color of the text in advance so that the new text that is replaced into the document can retain the desired format.

 

Replace Text in PPT

Free Spire.Presentation for Java provides the replaceText method to replace text in PPT.

The following are some steps to achieve the result.

Step 1: load the PowerPoint template and get the first slide

Step 2: create a Map object and add the original text and text that is replaced into the file to the Map.

Step 3: using the replaceText method to replace text and save the resulting file.

import com.spire.presentation.*;
import java.util.HashMap;
import java.util.Map;

public class ReplaceText {
   
public static void main(String[] args) throws Exception {
       
//create a Presentation object
       
Presentation presentation = new Presentation();
       
//load the template file
       
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//get the first slide
       
ISlide slide= presentation.getSlides().get(0);
       
//create a Map object
       
Map<String, String> map = new HashMap<String, String>();
       
//add several pairs of keys and values to the map
       
map.put("# Name#","the Forbidden city");
        map.put(
"# Place#","Beijing,China");
        String description =
"The Forbidden City is the imperial palace of the Ming and Qing Dynasties in China. " +
               
"It is located in the center of the central axis of Beijing and is the essence of ancient Chinese palace architecture. " +
               
"The Forbidden City is centered on three halls, covering an area of 720,000 square meters, " +
               
"with a construction area of about 150,000 square meters, more than 70 large and small palaces, " +
               
"and more than 9,000 houses. It is one of the largest and best-preserved ancient wooden structure buildings in the world.";
        map.put(
"# Introduction#",description);
       
//replace text in the slide
       
replaceText(slide,map);
       
//save to another file
       
presentation.saveToFile("output/ReplaceText.pptx", FileFormat.PPTX_2013);
    }
   
/*
     * Replace text within a slide
     * @param slide Specifies the slide where the replacement happens
     * @param map Where keys are existing strings in the document and values are the new strings to replace the old ones
     */
   
public static void replaceText(ISlide slide, Map<String, String> map) {
       
for (Object shape : slide.getShapes()
        ) {
           
if (shape instanceof IAutoShape) {

               
for (Object paragraph : ((IAutoShape) shape).getTextFrame().getParagraphs()
                ) {
                    ParagraphEx paragraphEx =(ParagraphEx)paragraph;
                   
for (String key : map.keySet()
                    ) {
                       
if (paragraphEx.getText().contains(key)) {
                            paragraphEx.setText(paragraphEx.getText().replace(key, map.get(key)));
                        }
                    }
                }
            }
        }
    }
}

Output


Replace an Image in PPT

Free Spire.Presentation for Java also supports replacing an image in PPT through the following code snippets.

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;
import javax.imageio.ImageIO; import java.awt.image.BufferedImage;
import java.io.FileInputStream;
public class ReplaceImage {
   
public static void main(String[] args) throws Exception {
       
//create a Presentation object
       
Presentation presentation= new Presentation();
       
//load the sample PowerPoint file
       
presentation.loadFromFile("C:\\Users\\Test1\\Desktop\\ReplaceText.pptx");
       
//add an image to the image collection
       
String imagePath ="C:\\Users\\Test1\\Desktop\\palace.png";
        BufferedImage bufferedImage = ImageIO.read(
new FileInputStream(imagePath));
        IImageData image = presentation.getImages().append(bufferedImage);
       
//get the shape collection from the first slide
       
ShapeCollection shapes = presentation.getSlides().get(0).getShapes();
       
//loop through the shape collection
       
for (int i = 0; i < shapes.getCount(); i++) {
           
//determine if a shape is a picture
           
if (shapes.get(i) instanceof SlidePicture) {
               
//fill the shape with a new image
               
((SlidePicture)shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
               
break;  }
        }
       
//save to file
       
presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);
    }
}

Output


Conclusion

Through the tutorial, we can easily create a beautiful PowerPoint document by using replace text and

pictures in the template through Java program. If there is any question about code snippets, please leave

a note on our Forum.

Wednesday, 9 September 2020

How to duplicate a page in PDF using Java

This article will introduce two methods to duplicate a page in PDF using Java programmatically.

  •         Duplicate a page in a PDF file to another PDF file
  •       Duplicate a page to other pages in the same PDF file

Test environment I used:

·    Intellij Idea2019.1

·    JDK 1.8.0

·    Spire.Pdf.jar

Add Spire.Pdf.jar to your project as a dependency

Method 1: Download the Free Spire.PDF for Java zip from the link, unzip it and find Spire.Pdf.jar in the “lib” folder. Finally add Spire.Pdf.jar to IDEA as a dependency.

Method 2: Create a Maven project, and specify e-iceblue Maven Repository configuration and define Spire.PDF for Java API dependency in your pom.xml as follows.

<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.0.0</version>

    </dependency>

</dependencies>

Finally, you only need to click “Import Changes” to import the Spire.PDF jars.

Using the code

Duplicate a page in a PDF file to another PDF file

The following code snippets are used to achieve the purpose that duplicating the first page of Sample 1 to the front of Sample 2. Specific steps are listed below.

Step 1: Load two sample PDF files using the PdfDocument instance.

Step 2: Get the first page of Sample 1 and its size using getPages() and getSize() methods.

Step 3: Create a template based on the page and insert it to the front of Sample 2.

Step 4: Using the saveToFile method to save the Sample 2.

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfTemplate;
import java.awt.*;
import java.awt.geom.Dimension2D;

public class DuplicatePage1 {
   
public static void main(String[] args) {
       
//Load two sample PDF documents
       
PdfDocument pdf1 = new PdfDocument("C:\\Users\\Test1\\Desktop\\Sample1.pdf");
        PdfDocument pdf2 =
new PdfDocument("C:\\Users\\Test1\\Desktop\\Sample2.pdf");

       
//Get the first page of Sample1 document
       
PdfPageBase page = pdf1.getPages().get(0);
       
//Get the page size
       
Dimension2D size = page.getSize();
       
//Create an template based on the page
       
PdfTemplate template = page.createTemplate();

       
//Insert the template to the first page of Sample2
       
pdf2.getPages().insert(0,size,new PdfMargins(0,0));
        pdf2.getPages().get(
0).getCanvas().drawTemplate(template,new Point(0,0));

       
//Save to Sample2 document
       
pdf2.saveToFile("output/result1.pdf",FileFormat.PDF);
        pdf2.dispose();
    }
}

Output


Duplicate a page to other pages in the same PDF file

Free Spire.PDF for Java also supports duplicating a page to other pages in the same PDF file. The tutorial below is to duplicate the first page in a PDF file to the front and end of the file.

import com.spire.pdf.*;
import com.spire.pdf.graphics.PdfMargins;
import com.spire.pdf.graphics.PdfTemplate;
import java.awt.*;
import java.awt.geom.Dimension2D;
public class DuplicatePage2 {
   
public static void main(String[] args) {
       
//Load a Sample PDF document
       
PdfDocument pdf = new PdfDocument("C:\\Users\\Test1\\Desktop\\Sample2.pdf");
       
//Get the first page
       
PdfPageBase page = pdf.getPages().get(0);
       
//Get the page size
       
Dimension2D size = page.getSize();
       
//Create a template based on the page
       
PdfTemplate template = page.createTemplate();
       
//Insert two templates cyclically to the end of the sample document
       
for(int i=0; i<2; i++){
            page = pdf.getPages().add(size,
new PdfMargins(0));//Add a new page to the document
           
page.getCanvas().drawTemplate(template, new Point(0, 0));//Draw template on the new page
       
}
       
//Insert one template to the front of the sample document
       
pdf.getPages().insert(0,size,new PdfMargins(0,0));//Add a new page to the document
       
pdf.getPages().get(0).getCanvas().drawTemplate(template,new Point(0,0));//Draw template on the new page
        //Save the PDF file
       
pdf.saveToFile("output/result2.pdf",FileFormat.PDF);
    }

} 

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