Tuesday, 30 March 2021

Add navigation buttons to a PDF document in Java

In a PDF document including many pages, we can easily jump from a page to another one by adding a navigation button. The page can be a special page, such as home page, last page or the next page. Meanwhile, it can also be a specified page, such as page 5. This tutorial will demonstrate how to add navigation buttons to a PDF document in Java using Free Spire.PDF for Java library.

First of all, we need to create the required test environment as below.

l  IntelliJ IDEA 2019

l  JDK 1.8

l  Free Spire.PDF for Java

Add required dependency to IDEA:

Method 1: Download Free Spire.PDF for Java package from E-iceblue website, unzip it and manually add Spire.Pdf.jar in the “lib” folder to IDEA.

Method 2: Create a Maven repository in IDEA, and define Spire.PDF for Java API dependency in Maven pom.xml as follows.

<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.PdfPageBase;
import com.spire.pdf.actions.PdfActionDestination;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.actions.PdfNamedAction;
import com.spire.pdf.fields.PdfButtonField;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class NavigationButtons {
public static void main(String[] args) {
//create a PdfDocument object and load a sample PDF file
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

//get the last page
PdfPageBase lastPage = doc.getPages().get(doc.getPages().getCount() - 1);

//allow creating forms in PDF
doc.setAllowCreateForm(true);

//define float variables to specify the location and size of the button
float x = 80;
float y = 420;
float width = 150;
float height = 22;

//create a truetype font
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", Font.PLAIN, 13), true);

//add a button that navigates to the first page
PdfButtonField btn_1 = new PdfButtonField(lastPage, "btn_1");
Rectangle2D.Float rect = new Rectangle2D.Float(x, y, width, height);
btn_1.setBounds(rect);
btn_1.setFont(font);
btn_1.setText("Return to Page 1");
btn_1.setBackColor(new PdfRGBColor(Color.ORANGE));
btn_1.setForeColor(new PdfRGBColor(Color.blue));
btn_1.setBorderColor(new PdfRGBColor(Color.blue));
PdfNamedAction namedAction = new PdfNamedAction(PdfActionDestination.FirstPage);
btn_1.getActions().setMouseDown(namedAction);
doc.getForm().getFields().add(btn_1);

//add a button that navigates to a particular page
PdfButtonField btn_2 = new PdfButtonField(lastPage, "btn_2");
rect = new Rectangle2D.Float( x, y + height + 5, width, height);
btn_2.setBounds(rect);
btn_2.setText("Jump to Page 2");
btn_2.setFont(font);
btn_2.setBackColor(new PdfRGBColor(Color.ORANGE));
btn_2.setForeColor(new PdfRGBColor(Color.blue));
btn_2.setBorderColor(new PdfRGBColor(Color.blue));
PdfGoToAction goToAction = new PdfGoToAction(new PdfDestination(doc.getPages().get(1)));
btn_2.getActions().setMouseDown(goToAction);
doc.getForm().getFields().add(btn_2);

//save to file
doc.saveToFile("output/NavigationButton.pdf", FileFormat.PDF);
doc.close();
}
}

Output



Friday, 26 March 2021

Embed an Excel File in a PowerPoint Document in Java

This tutorial will demonstrate how to insert an Excel file as an OEL object into a PowerPoint document using Java codes. It’s worth mentioning that I used a third-party library called Free Spire.Presentation for Java to accomplish the function above.

Dependency

Before running codes, you need to add Spire.Presentation.jar in the library to your project. You can directly download it from the link, or reference it by using the following Maven configuration.

<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

import com.spire.presentation.FileFormat;
import com.spire.presentation.IOleObject;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideSizeType;
import com.spire.presentation.drawing.IImageData;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

public class InsertOEL {
public static void main(String[] args) throws Exception {
//Create a Presentation object
Presentation ppt = new Presentation();
ppt.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

//Load an image file and add it to the image collection of the presentation
File file = new File("C:\\Users\\Test1\\Desktop\\Image.png");
BufferedImage image = ImageIO.read(file);
IImageData oleImage = ppt.getImages().append(image);

//Load an Excel file and convert it to byte[] object
String excelPath = "C:\\Users\\Test1\\Desktop\\Sample.xlsx";
File excelFile = new File(excelPath);
FileInputStream inputStream = new FileInputStream(excelFile);
byte[] data = new byte[(int) excelFile.length()];
inputStream.read(data, 0, data.length);

//Create a Rectangle2D object
Rectangle2D rect = new Rectangle2D.Float(60, 60, image.getWidth(), image.getHeight());

//Insert the Excel file as an OLE object to the first slide
IOleObject oleObject = ppt.getSlides().get(0).getShapes().appendOleObject("excel", data, rect);
oleObject.getSubstituteImagePictureFillFormat().getPicture().setEmbedImage(oleImage);
oleObject.setProgId("Excel.Sheet.12");

//Save to another file
ppt.saveToFile("output/InsertOle.pptx", FileFormat.PPTX_2013);
}
}

Output



 

Wednesday, 24 March 2021

Enable and Accept/Reject Track Changes in Word documents using Java

Microsoft Word provides Track Changes for users to add, delete or change the content of documents and keeps traces of these changes. When you agree the changes, you can choose to accept Track Changes to make the document keep the final text information, while if you disagree the changes, you can restore the document to its original state by rejecting Track Changes.

In this article, I’ll introduce how to accomplish the functions above in Java applications using Free Spire.Doc for Java library. Before running codes, please download the package from the link, and manually add Spire.doc.jar to IDEA. Or reference it using the following Maven configurations.

<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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

Enable Track Changes

import com.spire.doc.*;
public class OpenTrackChanges {
public static void main(String[] args) {
//Create Word document.
Document document = new Document();

//Load the file from disk.
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.docx");

//Enable the track changes.
document.setTrackChanges(true);

//Save to file.
document.saveToFile("output/enableTrackChanges.docx", FileFormat.Docx_2013);
}
}

Output

Accept or Reject Track Changes

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class SetTrackChanges {
public static void main(String[] args) {
//Create Word document.
Document document = new Document();

//Load the file from disk.
document.loadFromFile("C:\\Users\\Test1\\Desktop\\Accept or Reject TrackChanges.docx");

//Get the first section and the paragraph we want to accept/reject the changes.
Section sec = document.getSections().get(0);
Paragraph para = sec.getParagraphs().get(0);

//Accept the changes or reject the changes.
//para.getDocument().acceptChanges();
para.getDocument().rejectChanges();

//Save to file.
document.saveToFile("output/acceptOrRejectTrackedChanges.docx", FileFormat.Docx_2013);
}
}

Output




Friday, 19 March 2021

Add data validation for an Excel worksheet in Java

In an Excel worksheet, we can use data validation to add some restrictions while entering data in cells, for example, we only enter integers, decimals or dates in cells. This article will use Java codes to demonstrate how to set data validation, so that data can be inputted only when it fits some request.

Dependency

It’s worth mentioning that I used a free third-party library called Free Spire.XLS for Java in this tutorial, and 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>

Using the code

import com.spire.xls.*;

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

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

//Apply decimal validation in the cell B3
sheet.getCellRange("B2").setText("Input number between 1-100:");
CellRange rangeNumber = sheet.getCellRange(
"B3");
rangeNumber.getDataValidation().setCompareOperator(ValidationComparisonOperator.
Between);
rangeNumber.getDataValidation().setFormula1(
"1");
rangeNumber.getDataValidation().setFormula2(
"100");
rangeNumber.getDataValidation().setAllowType(CellDataType.
Decimal);
rangeNumber.getDataValidation().setErrorMessage(
"Please input correct number!");
rangeNumber.getDataValidation().setShowError(
true);
rangeNumber.getCellStyle().setKnownColor(ExcelColors.
Gray25Percent);

//Apply date validation in the cell B6
sheet.getCellRange("B5").setText("Input date between 1/1/2020-12/31/2020:");
CellRange rangeDate = sheet.getCellRange(
"B6");
rangeDate.getDataValidation().setAllowType(CellDataType.
Date);
rangeDate.getDataValidation().setCompareOperator(ValidationComparisonOperator.
Between);
rangeDate.getDataValidation().setFormula1(
"1/1/1970");
rangeDate.getDataValidation().setFormula2(
"12/31/1970");
rangeDate.getDataValidation().setErrorMessage(
"Please input correct date!");
rangeDate.getDataValidation().setShowError(
true);
rangeDate.getDataValidation().setAlertStyle(AlertStyleType.
Warning);
rangeDate.getCellStyle().setKnownColor(ExcelColors.
Gray25Percent);

//Apply text length validation in the cell B9
sheet.getCellRange("B8").setText("Input text less than 5 characters:");
CellRange rangeTextLength = sheet.getCellRange(
"B9");
rangeTextLength.getDataValidation().setAllowType(CellDataType.
TextLength);
rangeTextLength.getDataValidation().setCompareOperator(ValidationComparisonOperator.
LessOrEqual);
rangeTextLength.getDataValidation().setFormula1(
"5");
rangeTextLength.getDataValidation().setErrorMessage(
"Enter a Valid String!");
rangeTextLength.getDataValidation().setShowError(
true);
rangeTextLength.getDataValidation().setAlertStyle(AlertStyleType.
Stop);
rangeTextLength.getCellStyle().setKnownColor(ExcelColors.
Gray25Percent);

//Auto fit column width
sheet.autoFitColumn(2);

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

Output






Monday, 15 March 2021

Add a cross-page seal to a PDF document in Java

Cross-page seals are a way of stamping seals which often used in our work for some important business documents, such as contracts, personnel files and technical documents. Its main role is to prevent documents from being modified, increased or decreased. This tutorial will demonstrate how to add a cross-page seal to a PDF document in Java applications using a free third-party library called Free Spire.PDF for Java.

First of all, let’s look at the screenshot of the resulting document after adding a cross-page seal.

How to add a cross-page seal to a PDF document in Java?

Test environment:

l  IntelliJ IDEA 2019

l  JDK 1.8

l  Free Spire.PDF for Java

Add required dependency to IDEA:

Method 1: Download Free Spire.PDF for Java package from E-iceblue website, unzip it and manually add Spire.Pdf.jar in the “lib” folder to IDEA.

Method 2: Create a Maven repository in IDEA, and define Spire.PDF for Java API dependency in Maven pom.xml as follows.

<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.*;
import com.spire.pdf.graphics.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.io.*;

public class AddSeamSeals {
public static void main(String[] args) throws IOException {
//load a sample document from disk.
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.pdf");

PdfUnitConvertor convert = new PdfUnitConvertor();
PdfPageBase pageBase = null;

//get the segmented seal image.
BufferedImage[] images = GetImage(doc.getPages().getCount());
float x = 0;
float y = 0;

//draw the picture to the designated location on the PDF page.
for (int i = 0; i < doc.getPages().getCount(); i++)
{
BufferedImage image= images[ i ];
pageBase = doc.getPages().get(i);
x = (float)pageBase.getSize().getWidth() - convert.convertUnits(image.getWidth(), PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);
y = (float) pageBase.getSize().getHeight()/ 2;
pageBase.getCanvas().drawImage(PdfImage.fromImage(image), new Point2D.Float(x, y));
}
//save the Pdf file.
doc.saveToFile("output/AddSeamSeals.pdf");
}
//define the GetImage method to segment the seal image according to the number of PDF pages.
static BufferedImage[] GetImage(int num) throws IOException {
String originalImg = "C:\\Users\\Test1\\Desktop\\Image.png";
BufferedImage image = ImageIO.read(new File(originalImg));
int rows = 1;
int cols = num;
int chunks = rows * cols;
int chunkWidth = image.getWidth() / cols;
int chunkHeight = image.getHeight() / rows;
int count = 0;
BufferedImage[] imgs = new BufferedImage[ chunks ];
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
imgs[ count ] = new BufferedImage(chunkWidth, chunkHeight, image.getType());
Graphics2D gr = imgs[ count++ ].createGraphics();
gr.drawImage(image, 0, 0, chunkWidth, chunkHeight,
chunkWidth * y, chunkHeight * x,
chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, Color.WHITE,null);
gr.dispose();
}
}
return imgs;
}
}



Wednesday, 10 March 2021

Add Header and Footer to a PDF document in Java

Free Spire.PDF for Java, a free third-party library to manipulate PDF documents in Java, can not only support adding header and footer when creating a new PDF document, but also accomplish the requirement of adding multiple headers in a single PDF document. This tutorial will demonstrate how to do those in Java applications.

First of all, you need to add Spire.Pdf.jar in the library to IDEA. You can download the package from the link and manually add it, or reference it by adding the following configurations in 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>

Add Header and Footer to a PDF document

Free Spire.PDF for Java has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField,

PdfPageNumberField, etc. We use text string for the header and dynamic fields for the footer

in the following example.

import java.awt.*;
import java.awt.geom.Dimension2D;
import com.spire.pdf.*;
import com.spire.pdf.automaticfields.PdfAutomaticField;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;
public class AddHeaderFooter {
public static void main(String[] args) {
//create a PdfDocument object
PdfDocument doc = new PdfDocument();

//Set margins
PdfMargins margin = new PdfMargins(60,60,40,40);

//Call the method addHeaderAndFooter() to add header and footer
addHeaderAndFooter(doc, PdfPageSize.A4, margin);

//Add two pages to the PDF document and draw string to it.
PdfPageBase page1 = doc.getPages().add();
PdfPageBase page2 = doc.getPages().add();
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 14));
String text1 = "Demo of Spire.PDF for Java";
String text2 = "How to add header and footer to PDF in Java";
page1.getCanvas().drawString(text1, font, PdfBrushes.getBlack(),0,0);
page2.getCanvas().drawString(text2, font, PdfBrushes.getBlack(),0,0);

//Save the document
doc.saveToFile("output/headerFooter.pdf");
doc.close();

}
static void addHeaderAndFooter(PdfDocument doc, Dimension2D pageSize, PdfMargins margin) {

PdfPageTemplateElement header = new PdfPageTemplateElement(margin.getLeft(), pageSize.getHeight());
doc.getTemplate().setLeft(header);

PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.getWidth(), margin.getTop());
topSpace.setForeground(true);
doc.getTemplate().setTop(topSpace);

//Draw header label
PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));

PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String label = "E-iceblue Co.,Ltd";
Dimension2D dimension2D = new Dimension();
dimension2D.setSize(font.measureString(label, format));
float y = topSpace.getHeight() - font.getHeight() - 1;
PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 0.75f);
topSpace.getGraphics().setTransparency(0.5f);
topSpace.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
y = y - 1 - (float) dimension2D.getHeight();
topSpace.getGraphics().drawString(label, font, PdfBrushes.getBlack(), margin.getLeft(), y, format);

PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.getRight(), pageSize.getHeight());
doc.getTemplate().setRight(rightSpace);


//Draw dynamic fields as footer
PdfPageTemplateElement footer = new PdfPageTemplateElement(pageSize.getWidth(), margin.getBottom());
footer.setForeground(true);
doc.getTemplate().setBottom(footer);

y = font.getHeight() + 1;
footer.getGraphics().setTransparency(0.5f);
footer.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
y = y + 1;
PdfPageNumberField pageNumber = new PdfPageNumberField();
PdfPageCountField pageCount = new PdfPageCountField();
PdfCompositeField pageNumberLabel = new PdfCompositeField();
pageNumberLabel.setAutomaticFields(new PdfAutomaticField[]{pageNumber, pageCount});
pageNumberLabel.setBrush(PdfBrushes.getBlack());
pageNumberLabel.setFont(font);
format = new PdfStringFormat(PdfTextAlignment.Right);
pageNumberLabel.setStringFormat(format);
pageNumberLabel.setText("page {0} of {1}");
pageNumberLabel.setBounds(footer.getBounds());
pageNumberLabel.draw(footer.getGraphics(), - margin.getLeft(), y);
}
}

Output


Add multiple headers to a PDF document

The multiple headers on PDF means that different page has different header on the same PDF

document.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
public class MultipleHeaders {
public static void main(String[] args) {
//load the sample PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.pdf");
String header1 =
"Spire.PDF for Java";
String header2 =
"Add Multiple headers";

//define style
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD,12));
PdfBrush brush= PdfBrushes.
getBlue();
Rectangle2D rect =
new Rectangle2D.Float();
Dimension2D dimension2D =
new Dimension();
dimension2D.setSize(doc.getPageSettings().getSize().getWidth(),
50f);
rect.setFrame(
new Point2D.Float(0, 20), dimension2D);
PdfStringFormat format=
new PdfStringFormat();
format.setAlignment(PdfTextAlignment.
Center);
//draw header string for the first page
doc.getPages().get(0).getCanvas().drawString(header1,font,brush,rect,format);

//draw header string for the second page
format.setAlignment( PdfTextAlignment.Left);
doc.getPages().get(
1).getCanvas().drawString(header2, font, brush, rect, format);

//save the document
doc.saveToFile("output/addDifferentHeaders.pdf", FileFormat.PDF);
}
}

Output



Monday, 8 March 2021

Add Barcodes and QR-codes to Word documents in Java

In daily life, barcodes are mainly used in product identification, anti-counterfeiting, supermarket checkouts and so on, while compared with barcodes, QR-codes can contains more information including URLs, text, pictures, etc. This article will introduce how to add barcodes and QR-codes to Word documents using Java, and the adding position can not only be the paragraph of the document, but also the header or footer of the documents.

Dependency

In this tutorial, I used a free third-party library called Free Spire.Office for Java. Before running 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.Office.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.office.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
Using the code

Add Barcodes to a Word document

The following codes are used to add a barcode to the paragraph of the Word document, and

add another barcode to the footer of the document.

import com.spire.barcode.*;
import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

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

//Get all sections
for (int i = 0 ; i < doc.getSections().getCount();i++)
{
Section section = doc.getSections().get(i);

//Create a Barcode and save it as an image using the BarcodeSettings and BarcodeGenerator methods in Spire.Barcode
BarcodeSettings settings = new BarcodeSettings();
settings.setType(BarCodeType.Code_128);
settings.setData("123456789");
settings.setData2D("123456789");
settings.setShowText(false);
settings.setBarHeight(4);
settings.setX(0.3f);
settings.hasBorder(true);
settings.setBorderWidth(0.5f);
settings.setBorderColor(new Color(135,206,250));
settings.setBackColor(new Color(240,255,255));
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
BufferedImage bufferedImage = barCodeGenerator.generateImage();
ImageIO.write(bufferedImage, "png", new File("output/Barcode.png"));

//Add the Barcode image to the paragraph of Word document
Paragraph paragraph = section.addParagraph();
paragraph.setText("Receiving code:");
paragraph.appendPicture("output/Barcode.png");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

//Add the Barcode image to the footer of Word document
HeaderFooter footer = section.getHeadersFooters().getFooter();
Paragraph footerpara = footer.addParagraph();
footerpara.setText("Scan Barcode to know the authenticity:");
footerpara.appendPicture("output/Barcode.png");
footerpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
}

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

Output

Add QR-codes to a Word document

The following codes are used to add a QR-code to the paragraph of the Word document, and

add another QR-code to the header of the document.

import com.spire.barcode.*;
import com.spire.doc.*;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

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

//Get all sections
for (int i = 0 ; i < doc.getSections().getCount();i++)
{
Section section = doc.getSections().get(i);

//Create a QR-code and save it as an image using the BarcodeSettings and BarcodeGenerator methods in Spire.Barcode
BarcodeSettings settings = new BarcodeSettings();
settings.setType(BarCodeType.QR_Code);
settings.setData("123456");
settings.setData2D("123456");
settings.setX(0.7f);
settings.setLeftMargin(0);
settings.setShowTextOnBottom(true);
settings.setQRCodeECL(QRCodeECL.Q);
settings.setQRCodeDataMode(QRCodeDataMode.Numeric);
BarCodeGenerator generator = new BarCodeGenerator(settings);
Image image = generator.generateImage();
ImageIO.write((RenderedImage) image, "png", new File("output/QRCode.png"));

//Add the QR-code image to the paragraph of Word document
Paragraph paragraph = section.addParagraph();
paragraph.appendPicture("output/QRCode.png");
paragraph.getFormat().setHorizontalAlignment(HorizontalAlignment.Right);

//Add the QR-code image to the footer of Word document
HeaderFooter header = section.getHeadersFooters().getHeader();
Paragraph headerpara = header.addParagraph();
headerpara.appendPicture("output/QRCode.png");
headerpara.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
}

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





Thursday, 4 March 2021

How to print Excel worksheets in Java

In our daily work or study, we often encounter situations where we need to print out the prepared Excel worksheet and post it on the bulletin board or workspace. This tutorial will demonstrate how to print Excel worksheets in Java using a free third-party library called Free Spire.XLS for Java. Normally, printing can be done from the following two methods:

l  Printing Excel worksheets using default printer

l  Printing Excel worksheets using specified printer

Dependency

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>

Using the code

Print Excel worksheets using default printer

import com.spire.xls.*;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintByDefault {
public static void main(String[] args) {
//Create a workbook and load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\Sample.xlsx");

//Create a PrinterJob object
PrinterJob printerJob = PrinterJob.getPrinterJob();

//Create a PageFormat object and set it to the default size and orientation
PageFormat pageFormat = printerJob.defaultPage();

//Return a copy of the Paper object associated with this PageFormat
Paper paper = pageFormat.getPaper();

//Set the imageable area of this Paper
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());

//Set the Paper object for this PageFormat.
pageFormat.setPaper(paper);

//Set the number of copies
printerJob.setCopies(1);

//Call painter to render the pages in the specified format
printerJob.setPrintable(workbook, pageFormat);

//execute print
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}

Print Excel worksheets using specified printer

import com.spire.xls.*;
import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class SpecifiedPrinter {
public static void main(String[] args) throws PrinterException {
//Create a workbook and load an Excel file
Workbook workbook = new Workbook();
workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

//Create a PrinterJob object
PrinterJob printerJob = PrinterJob.getPrinterJob();

//Specify printer name
PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
printerJob.setPrintService(myPrintService);

//Create a PageFormat object and set it to the default size and orientation
PageFormat pageFormat = printerJob.defaultPage();

//Return a copy of the Paper object associated with this PageFormat.
Paper paper = pageFormat .getPaper();

//Set the imageable area of this Paper.
paper.setImageableArea(0,0,pageFormat .getWidth(),pageFormat .getHeight());

//Set the Paper object for this PageFormat.
pageFormat .setPaper(paper);

//Set the number of copies
printerJob .setCopies(1);

//Call painter to render the pages in the specified format
printerJob .setPrintable(workbook,pageFormat);

//execute print
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
//Get print service by printer name
private static PrintService findPrintService(String printerName) {

PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals(printerName)) {
return printService;
}
}
return null;
}
}




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