Tuesday, 27 October 2020

【Java】Insert or Delete Text Boxes in Word Documents

Text boxes in Word documents are a container that saves editable text or images. You add them to documents for extra visual appeal or to call out sections of text within the document. This article will demonstrate how to insert a text box with an image and text in a Word document and delete it from the document using Java programmatically.

Before typing codes

At first, you need to download a free third-party library Free Spire.Doc for Java from the link, unzip it and then find Spire.Doc.jar in the “lib” folder. Finally, add Spire.Doc.jar to your IDEA. Here is a screenshot of final look in IDEA.

Using the code

Insert a Text Box

Free Spire.Doc for Java provides the method Paragraph.AppendTextBox to enable users to insert a text box in specified paragraph of Word document, and an image, text or table can be added to the text box in the process of inserting it. Here are detailed steps to insert a text box with an image and text in Word.

Step 1: Load a Word document and append a text box with specified size to specified paragraph;

Step 2: Set Format properties, including TextWrappingStyle, HorizontalPosition, VerticalPosition, LineStyle and LineColor.

Step 3: Declare a new Paragraph and insert an image using the appendPicture method. Next, set properties for the image, including Height, Width, HorizontalAlignment.

Step 4: insert text by using the appendText method and set CharacterFormat properties, including FontName and FonSize.

Step 5: Using the saveToFile method to saving the resulting document.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;

import java.awt.*;
public class AddTextBox {
   
public static void main(String[] args) {
       
//load a Word document
       
Document doc = new Document();
        doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.docx");

       
//append a textbox to paragraph
       
TextBox tb = doc.getSections().get(0).addParagraph().appendTextBox(100f, 320f);

       
//set the text wrapping style
       
tb.getFormat().setTextWrappingStyle(TextWrappingStyle.Square);

       
//set the position of textbox
       
tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Right_Margin_Area);
        tb.getFormat().setHorizontalPosition(-
100f);
        tb.getFormat().setVerticalOrigin(VerticalOrigin.
Page);
        tb.getFormat().setVerticalPosition(
100f);

       
//set the border style of textbox
       
tb.getFormat().setLineStyle(TextBoxLineStyle.Thin_Thick);
        tb.getFormat().setLineColor(
new Color(240,135,152));

       
//insert an image to textbox as the first paragraph
        
Paragraph para = tb.getBody().addParagraph();
        DocPicture picture = para.appendPicture(
"C:\\Users\\Test1\\Desktop\\Image.jpg");
        picture.setHeight(
60f);
        picture.setWidth(
90f);
        para.getFormat().setHorizontalAlignment(HorizontalAlignment.
Center);
        para.getFormat().setAfterSpacing(
15f);

       
//insert text to textbox as the second paragraph
       
para = tb.getBody().addParagraph();
        TextRange textRange = para.appendText(
"A cashless society is one in which financial transactions are handled " +
               
"through the transfer of digital information instead of physical money in the form of banknotes or coins.");
        textRange.getCharacterFormat().setFontName(
"Times New Roman");
        textRange.getCharacterFormat().setFontSize(
12f);
        para.getFormat().setHorizontalAlignment(HorizontalAlignment.
Center);

       
//save to file
       
doc.saveToFile("output/InsertTextbox.docx", FileFormat.Docx_2013);
    }
}

Output


Remove a Text Box

Using several rows of code snippets provided by Free Spire.Doc for Java, you can easily remove a specified text box or all text boxes in Word.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class DeleteTextBox {
   
public static void main(String[] args) {
       
//load the Word document containing textbox
       
Document doc = new Document();
        doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\InsertTextbox.docx");
       
//remove textbox by index
       
doc.getTextBoxes().removeAt(0);
       
//remove all textboxes
        //doc.getTextBoxes().clear();
        //save to file
       
doc.saveToFile("output/RemoveTextbox.docx", FileFormat.Docx);
    }
}

Conclusion

In addition to inserting a text box with an image and text in Word and deletingit, Free Spire.Doc for Java

supports insert, read and delete table in a text box, and it also can extract text in a text box. In the Free

Spire.Doc for Java package, you can find the “Sample” folder where code demos of all functions are listed. If there is any problem concerning codes, please leave a message on our Forum or directly contact

us through these ways.

 

Wednesday, 21 October 2020

How to insert or remove page breaks in Excel Worksheets using Java

When we’re printing a large Excel worksheet, in order to exactly control which and how many rows and columns appear on the printed pages, we need to insert page breaks to specify where a new page will begin. This article will demonstrate how to insert or remove page breaks in Excel worksheet using Java programmatically. Please note that Page Breaks is only visible in the View menu tab under Workbook Views with the name of Page Break Preview.

Creating a Test Environment

Before typing codes, you should create a test environment by installing JDK, Intellij IDEA and Free Spire.XLS for Java which can be gained through E-iceblue website. After downloading the package, unzip it and manually add Spire.Xls.jar in the “lib” folder to your IDEA.

Of course, if you’re creating a Maven project, the best method is to install Free Spire.XLS for Java from Maven repository. The only thing you need to do is typing the following codes in the pom.xml file and clicking 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.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>

Using the code

Add Page Breaks to Excel worksheet

Free Spire.XLS for Java provides a method to help us insert page breaks horizontally and vertically. After adding page breaks, we can set view mode as Page Break Preview which displays excel as it will be printed.

import com.spire.xls.*;
public class AddPageBreak {
   
public static void main(String[] args) {
       
//Create a Workbook instance and load the sample file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Get the second worksheet
       
Worksheet sheet = workbook.getWorksheets().get(1);
       
//Set Excel Page Break Horizontally
       
sheet.getHPageBreaks().add(sheet.getRange().get("A6"));
       
//Set Excel Page Break Vertically
       
sheet.getVPageBreaks().add(sheet.getRange().get("C1"));
        sheet.getVPageBreaks().add(sheet.getRange().get(
"E1"));
       
// Set the ViewMode as Preview mode
       
workbook.getWorksheets().get(0).setViewMode(ViewMode.Preview);
       
//Save the document
       
workbook.saveToFile("output/AddPageBreak.xlsx", ExcelVersion.Version2013);
    }
}

Output


Remove Page Breaks in Excel worksheet

In addition to inserting page breaks, Free Spire.XLS for Java supports removing the special page breaks in Excel

worksheet. Here comes to the steps of how to do it.

Step 1: Initialize a Workbook instance and load the sample file.

Step 2: Get the second worksheet from the workbook.

Step 3: Clear all the vertical page breaks and remove the first horizontal page break.

Step 4: Set the ViewMode as Preview to see how the page breaks work.

Step 5: Save the resulting document to file.

import com.spire.xls.*;

public class RemovePageBreak {
   
public static void main(String[] args) {
       
//Create a Workbook and load the sample file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\AddPageBreak.xlsx");
       
//Get the second worksheet
       
Worksheet sheet = workbook.getWorksheets().get(1);
       
//Clear all the horizontal page break
       
sheet.getHPageBreaks().clear();
       
//Remove the first vertical Page Break
       
sheet.getVPageBreaks().removeAt(0);
       
//Set the ViewMode as Preview mode
       
sheet.setViewMode(ViewMode.Preview);
        
//Save the document
       
String output = "output/removePageBreak.xlsx";
        workbook.saveToFile(output,ExcelVersion.
Version2013);
    }
}

Output




Wednesday, 14 October 2020

[JAVA] Add, Replace and Delete Comments in PowerPoint

Comments are a great tool for collaborating in PowerPoint. When you're preparing for a big presentation, using comments and leaving them for your colleagues to trade feedback is a great option. In this article, I’ll introduce a quick way to add comments in Java programmatically, and demonstrate how to replace or delete comments in PowerPoint.

Add Spire.Presentation.jar as a dependency

Before typing codes, you need to add Spire.Presentation.jar to your project as a dependency. There are two ways to do it. One is that download Free Spire.Presentation for Java package from the link, unzip it and manually add Spire.Presentation.jar in the “lib” folder to your project. The other is that create a Maven project, write down the following code 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.presentation.free</artifactId>

        <version>3.9.0</version>

    </dependency>

</dependencies>

Using the code

Add Comments to PowerPoint
Free Spire.Presentation for Java allows users to insert comments in PowerPoint slides with several lines 
of core code. The following are four steps to do it.
Step 1: Create a Presentation instance and load a sample file.
Step 2: Call the ICommentAuthor.addAuthor () method to add comment author.

Step 3: Call the ppt.getSlides().addComment() method to add a comment on a specific slide. The 
Comment class includes author who added slide comment, time of creation, the position of comment on 
slide and the comment text.
import com.spire.presentation.*;
import java.awt.geom.Point2D;
public class AddComment {     public static void main(String[] args) throws Exception {
       
//load a sample PowerPoint file
       
Presentation ppt = new Presentation();
        ppt.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.pptx");
       
//Name the comment author
       
ICommentAuthor author = ppt.getCommentAuthors().addAuthor("Tina", "comment:");
       
//Add comments and set their location
       
ppt.getSlides().get(0).addComment(author, "The first comment", new Point2D.Float(21, 13), new java.util.Date());
        ppt.getSlides().get(
0).addComment(author, "The second added comment", new Point2D.Float(24, 28), new java.util.Date());
       
//Save the resulting document
       
ppt.saveToFile("output/AddComment.pptx", FileFormat.PPTX_2010);
        ppt.dispose();
    }
}

Output


Replace and Delete Comments in PowerPoint

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
public class ReplaceAndDeleteComment {
   
public static void main(String[] args) throws Exception {
       
//load the sample PowerPoint file
       
Presentation ppt = new Presentation();
        ppt.loadFromFile(
"C:\\Users\\Test1\\Desktop\\AddComment.pptx");
       
//Replace the first comment
       
ppt.getSlides().get(0).getComments()[0].setText("Replace comment");
       
//Delete the second comment
       
ppt.getSlides().get(0).deleteComment(ppt.getSlides().get(0).getComments()[1]);
       
//Save the resulting document
       
ppt.saveToFile("output/ReplaceAndDeleteComment.pptx", FileFormat.PPTX_2010);
        ppt.dispose();
    }
}
Output

Conclusion

Free Spire.Presentation for Java is especially designed for developers to manipulate PowerPoint

documents in Java without installing Microsoft Office. In addition to the above function of adding, replacing and deleting comments, it supports large numbers of other features.You can know more

detailed information from the link and feel free to take a note on Forum if there is any problem.

Friday, 9 October 2020

Convert PDF to Image and Convert Image to PDF in Java

By using Free Spire.PDF for Java, we can easily convert any specific page of PDF document to BMP and Metafile image in JAVA applications, and it also supports converting multiple image formats such as BMP, JPEG, GIF, PNG, TIFF and ICO to PDF. In this article, I’ll show you how to convert PDF to .png image and convert .jpg image to PDF for example.

Add Spire.Pdf.jar as a dependency

Before running codes, the thing you need to do is adding Spire.Pdf.jar to IDEA as a dependency. There are two methods to do it. One is that download Free Spire.PDF for Java package from the E-iceblue website, unzip it and manually add Spire.Pdf.jar in the “lib” folder to IDEA. The other is that installing Spire.PDF for Java from Maven repository. Create a Maven program, write down the following code snippets in your pom.xml file, and then 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.pdf.free</artifactId>
        <version>3.9.0</version>
    </dependency>

</dependencies>

Using the code

Convert PDF to Image

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;
import com.spire.pdf.PdfDocument;
import javax.imageio.ImageIO;

public class ToImage {
   
public static void main(String[] args) throws IOException {
       
//load the sample PDF
       
PdfDocument doc = new PdfDocument();
        doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.pdf");
       
//save every page of PDF document to .png image
       
BufferedImage image;
       
for (int i = 0; i < doc.getPages().getCount(); i++) {
            image = doc.saveAsImage(i);
            File file =
new File( String.format("output/ToImage-img-%d.png", i));
            ImageIO.write(image,
"PNG", file);
        }
        doc.close();
    }
}

Output


Convert Image to PDF

There are three steps in all to realize the purpose of converting Image to PDF.

Step 1: Create a new PDF file and add a page in it.
Step 2: Load an image in any format, such as jpg, bmp, png, gif, tiff and ico. A .jpg image is loaded and its location
is set in this method.

Step 3: Save the image to PDF file in a specific path.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImage;
import java.awt.geom.Rectangle2D;
public class ImageToPDF {
   
public static void main(String[] args) {
       
//Create a PdfDocument instance
       
PdfDocument pdf = new PdfDocument();
       
//Add a page
       
PdfPageBase page = pdf.getPages().add();
        
//Load the image
       
PdfImage image = PdfImage.fromFile("C:\\Users\\Test1\\Desktop\\Image.jpg");
       
//Draw the image to the specific rectangular area of the page
       
double widthFitRate = image.getPhysicalDimension().getWidth() / page.getCanvas().getClientSize().getWidth();
       
double heightFitRate = image.getPhysicalDimension().getHeight() / page.getCanvas().getClientSize().getHeight();
       
double fitRate = Math.max(widthFitRate, heightFitRate);
       
double fitWidth = image.getPhysicalDimension().getWidth() / fitRate;
       
double fitHeight = image.getPhysicalDimension().getHeight() / fitRate;
        page.getCanvas().drawImage(image,
new Rectangle2D.Double(0, 0, fitWidth, fitHeight));
       
//Save the resulting document
       
pdf.saveToFile("output/ConvertImageToPDF.pdf");
    }
}

Output



Conclusion

In addition to converting PDF to Image or Image to PDF, Free Spire.PDF for Java supports converting

PDF to XPS, SVG, Excel, Word, HTML and PDF/A or convert XPS, SVG, HTML to PDF in high

quality. You can find relevant tutorials from the link and please take a note on our Forum if there is any

question.



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