Sunday, 6 December 2020

How to print a PDF document in Java

This article will show you how to use a free API called Free Spire.PDF for Java to print a PDF document in Java programs. According to different requirements, there are three aspects to be shown.

l  Silently print a PDF document with default printer

l  Print a PDF document with Print dialog

l  Print a PDF document with customized page size

About Free Spire.PDF for Java

It is a free PDF API that enables Java applications to create, edit, read, convert and print 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).

Maven Dependency

Before typing code snippets, you need to add Spire.Pdf.jar to your project as a dependency. If you’re creating a Maven program, please add the following configuration into 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.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Or you can download the package from the link, unzip it and find Spire.Pdf.jar in the “lib” folder.

Finally manually add it to your project.


Using the code

Silently print a PDF document with default printer

In the process of printing the PDF document to default printer without showing print dialog, we could

also customize some print settings, such as removing the default print margins, setting the number of

copies, etc.

import com.spire.pdf.*;
import java.awt.print.*;

public class SilentlyPrintPDF {
public static void main(String[] args) {
//load the sample document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
PageFormat loPageFormat = loPrinterJob.defaultPage();
Paper loPaper = loPageFormat.getPaper();

//remove the default printing margins
loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

//set the number of copies
loPrinterJob.setCopies(2);

loPageFormat.setPaper(loPaper);
loPrinterJob.setPrintable(pdf,loPageFormat);
try {
loPrinterJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}


Print a PDF document with Print dialog

import com.spire.pdf.*;
import java.awt.print.*;
public class PrintDialog {
public static void main(String[] args) {
//load the sample document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
PageFormat loPageFormat = loPrinterJob.defaultPage();
Paper loPaper = loPageFormat.getPaper();

//remove the default printing margins
loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight());

loPageFormat.setPaper(loPaper);
loPrinterJob.setPrintable(pdf,loPageFormat);

//display the print dialog
if (loPrinterJob.printDialog()) {
try {
loPrinterJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}
}

Print a PDF document with customized page size

import com.spire.pdf.*;
import java.awt.print.*;
public class CustomizedPageSize {
public static void main(String[] args) {
//load the sample document
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PrinterJob loPrinterJob = PrinterJob.getPrinterJob();
PageFormat loPageFormat = loPrinterJob.defaultPage();

//set the print page size
Paper loPaper = loPageFormat.getPaper();
loPaper.setSize(500,600);
loPageFormat.setPaper(loPaper);
loPrinterJob.setPrintable(pdf,loPageFormat);

try {
loPrinterJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}

 

Thursday, 3 December 2020

Highlight text in a Word document in Java

I introduced how to replace text in a Word document using Java codes in my previous tutorial. In this article, I’ll show you how to highlight text in Java programmatically using a free API called FreeSpire.Doc for Java. Normally, we can find all matched text by its content and then highlight it with color, or we can use index to search the location of the text we want to highlight.

About Free Spire.Doc for Java

It is a free and professional Java Word API that enables Java applications to create, manipulate, convert and print Word documents without using Microsoft Office.

A plenty of Word document processing tasks can be performed by Free Spire.Doc for Java, such as insert image, add header and footer, create table, add form field and mail merge field, add bookmark and watermark, add hyperlink, set background color/image, add footnote and endnote, encrypt Word documents.

Create a test environment

Before typing codes, in addition to installing JDK and Intellij IDEA, you need to add Spire.Doc.jar to your project as a dependency. If you’re creating a Maven project, just add the following configurations to the 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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Or you can download the package from the E-iceblue website, unzip it and find Spire.Doc.jar in the

“lib” folder. Finally manually add it to your project.

Using the code

Highlight text by its content

Free Spire.Doc for Java provides two methods to find and highlight text in a Word document:

findString() and findAllString(). The findString() method finds the first matched text, while the

findAllString() method finds all matched text. The below example shows how to find all matched text

using findAllString() method and then highlight the text.

import com.spire.doc.*;
import com.spire.doc.documents.TextSelection;
import java.awt.*;

public class FindAndHighlightText {
public static void main(String[] args) {
//Load Word document
Document document = new Document("C:\\Users\\Test1\\Desktop\\Test.docx");
//Find all “sands” text
TextSelection[] textSelections = document.findAllString("sands", false, true);
//Set highlight color
for (TextSelection selection : textSelections) {
selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
}
//Save the document
document.saveToFile("output/FindAndHightText.docx", FileFormat.Docx_2013);
}
}

Output


Highlight text
by its location

Free Spire.Doc for Java also supports search the location of the text by index and highlight it.

The following codes demonstrates how to highlight the text which is located at the 26th to 29th in

the second paragraph.

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.TextSelection;
import com.spire.doc.fields.TextRange;
import java.awt.*;
import java.util.ArrayList;
import java.util.regex.Pattern;

public class HighlightText {
public static void main(String[] args) {
//Load the file
Document document = new Document();
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.docx");
//Find all words of the document
String pattern = "\\d+.\\d+|\\w+";
Pattern rgx=Pattern.compile(pattern);
TextSelection[] textSelections = document.findAllPattern(rgx);
//Define a TextRange list
ArrayList<TextRange> textrangeList = new ArrayList<TextRange>();
//If the found word in second paragraph, then add it to list
for (TextSelection selection: textSelections) {
TextRange tr = selection.getAsOneRange();
Paragraph oPara = selection.getAsOneRange().getOwnerParagraph();
Section sec = (Section)(selection.getAsOneRange().getOwnerParagraph().getOwner().getOwner()) ;
int paraIndex = sec.getBody().getParagraphs().indexOf(oPara);
if (paraIndex==1)
{
textrangeList.add(tr);
}
}
//Highlight the fifth to eighth words
for (int i = 25; i < 29; i++)
{
textrangeList.get(i).getCharacterFormat().setHighlightColor(Color.YELLOW);
}
document.saveToFile("output/HighlightText.docx", FileFormat.Docx);

}
}

Output


Sunday, 29 November 2020

Add Watermark to Excel Worksheets in Java

Actually, Microsoft Excel doesn’t have a built-in feature to add watermark in Excel worksheets. But there are still several ways to do it, such as adding header image or WordArt to worksheets to simulate the look of a watermark. This article will show you how to create and insert a header image in Excel to mimic a watermark using Java codes.

In addition to JDK and Intellij IDEA, you need a third-party library to build our test environment. Here I’ll recommend a free API called Free Spire.XLS for Java, which is a free and professional Java Excel API that enables developers to create, manipulate, convert and print Excel worksheets without using Microsoft Office.

Add Spire.Xls.jar as a dependency

There are two ways to add Spire.Xls.jar located in the free API to your project as a dependency. If you’re creating a Maven project in IDEA, the best choice is specifying the following configuration 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>

If you are a non-maven user, then download the package from the website page, and add Spire.Xls.jar

to run the sample code given in this tutorial.

The screenshot below is shown what it finally looks like.


Using the code

Here are some steps to add text watermark to Excel worksheets in Java using Free Spire.XLS for Java.

Please note that the watermark can only be shown when the view mode is Layout, so don’t forget to

change the view mode.

Step 1: Define a custom function called DrawText() to create an image based on the text content of a

string. The string can be “Confidential”, “draft”, “Sample” or any text which you want to be shown as

watermark.

Step 2: Initialize a Workbook instance and load the test file.

Step 3: Call DrawText() method to create an image, set the image as left header image.

Step 4: Save the resulting document.

import com.spire.xls.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import static java.awt.image.BufferedImage.TYPE_INT_ARGB;

public class AddTextWatermark {
public static void main(String[] args) {
//Initialize a Workbook instance and load the test file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.xlsx");

//Set text content of watermark and its size
Font font = new Font("Arial", Font.PLAIN, 50);
String watermark = "Draft";

for (Worksheet sheet : (Iterable<Worksheet>) workbook.getWorksheets()) {
//Call DrawText() method to insert the image
BufferedImage imgWtrmrk = drawText(watermark, font, Color.pink, Color.white, sheet.
getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth());

//Set the image as left header
sheet.getPageSetup().setLeftHeaderImage(imgWtrmrk);
sheet.getPageSetup().setLeftHeader("&G");

//Set the Viewmode as Layout
sheet.setViewMode(ViewMode.Layout);
}

//Save the document
workbook.saveToFile("output/AddWatermark.xlsx", ExcelVersion.Version2010);
}
private static BufferedImage drawText (String text, Font font, Color textColor, Color backColor,double height, double width)
{
//Create an image with specified width and height
BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB);
Graphics2D loGraphic = img.createGraphics();

//set the font size
FontMetrics loFontMetrics = loGraphic.getFontMetrics(font);
int liStrWidth = loFontMetrics.stringWidth(text);
int liStrHeight = loFontMetrics.getHeight();

//set the text format
loGraphic.setColor(backColor);//paint the background
loGraphic.fillRect(0, 0, (int) width, (int) height);
loGraphic.translate(((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
loGraphic.rotate(Math.toRadians(-35)); //Rotate text
//reset translate transform
loGraphic.translate(-((int) width - liStrWidth) / 2, -((int) height - liStrHeight) / 2);
loGraphic.setFont(font);
loGraphic.setColor(textColor);
//draw text on the image at center position
loGraphic.drawString(text, ((int) width - liStrWidth) / 2, ((int) height - liStrHeight) / 2);
loGraphic.dispose();
return img;
}
}

Output




 

Thursday, 26 November 2020

Insert HTML in PowerPoint in Java using a free API

Usually, HTML can include text, image, audio or video. In this article, I’ll use a free API to separately demonstrate how to insert HTML formatted text or HTML with an image into PowerPoint slides using Java code.

The free API I used in this tutorial is called Free Spire.Presentation for Java which is a free and professional PowerPoint API that enables developers to create, read, write, convert and save PowerPoint documents in Java Applications without installing Microsoft Office.

Before running codes, you need to insert Spire.Presentation.jar into your project. If you’re creating a Maven project, you just need to specify the following configuration in your Maven pom.xml and then click the “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>

Finally, it will look like the screenshot below.


Insert HTML formatted text in a PowerPoint slide

Free Spire.Presentation for Java provides the addFromHTML method to support inserting HTML

formatted text in a PowerPoint slide. In the process of it, you can set the font color of the text. Here

are code snippets to do it.

import java.awt.Color;
import java.awt.Rectangle;
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

public class AddHTMLText {
public static void main(String[] args) throws Exception {
//Initiate a Presentation object
Presentation ppt = new Presentation();
//Add a Shape to the first slide, and set its size and location
IAutoShape shape = ppt.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(50, 50, 350, 120));
//Set the format type of the shape
shape.getFill().setFillType(FillFormatType.SOLID);
shape.getFill().getSolidColor().setColor(Color.white);
shape.getShapeStyle().getLineColor().setColor(Color.black);
//Clear the default paragraph
shape.getTextFrame().getParagraphs().clear();
//Insert html string with text in the shape
String code = "<ul><li style=\"color:blue\">Introduction to Brand Marketing</li><li style=\"color:green\">Brand Positioning Personality</li>" +
"<li style=\"color:gray\">Brand Design</li><li style=\"color:red\">Brand Communication Advertising</li></ul>";
shape.getTextFrame().getParagraphs().addFromHtml(code);
//Saving the resulting document
String outputFile = "output/AddHTMLStringToPPT.pptx";
ppt.saveToFile(outputFile, FileFormat.PPTX_2010);
}
}

Output


Insert
HTML with text and an image in a PowerPoint slide

You can insert HTML with an image through adding the local link of an image to the HTML String.

import com.spire.presentation.*;
import com.spire.presentation.collections.ShapeList;

public class AddHTMLWithImages {
public static void main(String[] args) throws Exception {
//Initiate a Presentation object
Presentation ppt = new Presentation();
//Get the shapes on the first slide
ShapeList shapes = ppt.getSlides().get(0).getShapes();
//Add HTML with text and an image to the shapes
String code ="<html><body><li style=\"color:blue\">Producer's Perspective</li><p>Emphasize the external performance of the brand</p>" +
"<img src='C:\\Users\\Test1\\Desktop\\Image.jpg'/></body></html>";
shapes.addFromHtml(code);
//Saving the resulting document
String outputFile = "output/AddHTMLWithImages.pptx";
ppt.saveToFile(outputFile,FileFormat.PPTX_2010);
}
}

Output



Monday, 23 November 2020

Create a PDF document in Java using a free API

Usually, we can get a PDF document only by converting other document formats. Here, I will introduce a method to directly create a PDF document with a head, paragraph and image, which is that using Java code to do it programmatically.

It is worth noting that I used a free API called Free Spire.PDF for Java in this tutorial. It enables Java applications to create, read, convert and save PDF documents without installing Adobe Acrobat.

Before running codes, please download the Free Spire.PDF for Java package from the link, unzip it and find Spire.Pdf.jar in the “lib” folder. Finally just manually add the jar file to your project.

Of course, if you’re creating a Maven project, just add the following configuration into the 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>3.9.0</version>
</dependency>
</dependencies>

Using the code

After finishing the steps above, the next thing you need to do is following the code snippets in order to

generate a PDF document.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

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

//add a page
PdfPageBase page = doc.getPages().add();

//create two solid brushes
PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.BLUE));
PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

//create two fonts
PdfFont font1 = new PdfFont(PdfFontFamily.Helvetica, 15f, PdfFontStyle.Bold);
PdfFont font2 = new PdfFont(PdfFontFamily.Helvetica, 12f);

//initialize x, y coordinates
float x = 0;
float y = 0;

//title
String title = "Java-Overview";

//align text to center via PdfTextAlignment class
PdfTextAlignment alignment = PdfTextAlignment.Center;

//draw title on the center of the page
drawTitle(page, title, font1, brush1, (float) page.getClientSize().getWidth() / 2, y, alignment);
y = y + 30;

//paragraph text
String paragraph = "Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is a general-purpose 
programming language intended to let application developers write once, run anywhere, meaning 
that compiled Java code can run on all platforms that support Java without the need for 
recompilation. Java applications are typically compiled to bytecode that can run on any 
Java virtual machine (JVM) regardless of the underlying computer architecture. The syntax of Java
is similar to C and C++, but has fewer low-level facilities than either of them. The Java 
runtime provides dynamic capabilities (such as reflection and runtime code modification)that are
typically not available in traditional compiled languages. As of 2019, Java was one of the most 
popular programming languages in use according to GitHub, particularly for client-server web applications, with a reported 9 million developers.";
        //draw paragraph on the page
PdfLayoutResult layoutResult = drawParagraph(page, paragraph, font2, brush2, x, y);
y = y + (float) layoutResult.getBounds().getHeight() + 10;

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

//draw image on the page
drawImage(page, image, x, y);
y = y + (float) image.getPhysicalDimension().getHeight() + 10;

//save to file
doc.saveToFile("output/CreatePdf.pdf");
}
public static void drawTitle(PdfPageBase page, String text, PdfFont font, PdfBrush brush,
float x, float y, PdfTextAlignment alignment) {

//set the text alignment via PdfStringFormat class
PdfStringFormat format = new PdfStringFormat();
format.setAlignment(alignment);

//draw title on the page
page.getCanvas().drawString(text, font, brush, x, y, format);
}
public static PdfLayoutResult drawParagraph(PdfPageBase page, String text, PdfFont font, PdfBrush
brush, float x, float y) {

//create a PdfTextWidget object
PdfTextWidget widget = new PdfTextWidget(text, font, brush);

//set the PdfLayoutType to Paginate to make the content paginated automatically
PdfTextLayout layout = new PdfTextLayout();
layout.setLayout(PdfLayoutType.Paginate);

//create a rectangle where the paragraph will be placed
Rectangle2D.Float rect = new Rectangle2D.Float(0, y, (float) page.getClientSize().getWidth(),
(float) page.getClientSize().getHeight());

//draw paragraph on the page
PdfLayoutResult layoutResult = widget.draw(page, rect, layout);
return layoutResult;
}
public static void drawImage(PdfPageBase page, PdfImage image, float x, float y) {

//draw image on the page
page.getCanvas().drawImage(image, x, y);
}
}

Output




Friday, 20 November 2020

How to replace text in a Word document in Java

Introduction

This article will mainly introduce how to replace text in a Word document using Java code. According to different requirements, there will be divided into three aspects to demonstrate it as follows.

l  Replace all matched text with new text

l  Replace the first matched text with new text

l  Replace all matched text with an image

The third-party library I used in this tutorial is Free Spire.Doc for Java. It is a free and professional Java API that enables Java applications to create, manipulate, convert and print Word documents without using Microsoft Office.

Before typing codes, please make sure that the Jar file located at Free Spire.Doc for Java is inserted in your project. If you’re creating a Maven project, just add the following configurations to the 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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Or you can download the package from the E-iceblue website, unzip it and find Spire.Doc.jar in the
“lib” folder. Finally manually add it to your project.
Using the code

Replace all matched text with new text
import com.spire.doc.*;
public class ReplaceTextWithNewText {
public static void main(String[] args) {
//Load the Word document
Document document = new Document("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Replace the specified text with new text
document.replace("society", "NewText", false, true);

//Save the document
document.saveToFile("output/ReplaceAllMatchedText.docx", FileFormat.Docx_2013);
}
}

Output


Replace the first matched text with new text

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

//Set to replace only the first occurrence of the specified text
document.setReplaceFirst(true);

//Replace with new text
document.replace("Society", "NewText", false, true);

//Save the document
document.saveToFile("output/ReplaceFirstMatchedText.docx", FileFormat.Docx_2013);
}
}

Output


Replace all matched text with an Image

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
public class ReplaceTextWithImage {
public static void main(String[] args) {
//Load a sample Word file
Document document = new Document();
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Find the string 'E-iceblue' in the document
TextSelection[] selections = document.findAllString("society", true, true);

//Replace the string with an image
int index = 0;
TextRange range = null;
for (Object obj : selections) {

TextSelection textSelection = (TextSelection)obj;
DocPicture pic = new DocPicture(document);
pic.loadImage("C:\\Users\\Test1\\Desktop\\Image.png");
range = textSelection.getAsOneRange();
index = range.getOwnerParagraph().getChildObjects().indexOf(range);
range.getOwnerParagraph().getChildObjects().insert(index,pic);
range.getOwnerParagraph().getChildObjects().remove(range);
}

//Save the document
document.saveToFile("output/ReplaceTextWithImage.docx", FileFormat.Docx_2013);
}
}

Output


Conclusion

In addition to replacing text, Free Spire.Doc for Java supports numerous functions of manipulating

Word documents. If there is any problem about codes or installation steps, please make a note on the

Comment or Forum.

 


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