Wednesday, 20 April 2022

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 client or colleague is using. This article will show you how to programmatically change the PDF version using Java.

DEPENDENCY

First of all, you’re required to add Spire.Pdf.jar to your Java program. Download the package of Free Spire.PDF for Java from this link, find it in the lib folder. Or if you use Maven, just type the following codes in the pom.xml file to import the JAR file to IntelliJ IDEA.

<repositories>
<repository>
<id>com.e-iceblue</id>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf</artifactId>
<version>5.4.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.PDF for Java supports changing the version of a PDF document using PdfDocument.getFileInfo().setVersion() method. The detailed steps are listed below.

l  Create a PdfDocument instance.

l  Load a PDF sample document using PdfDocument.loadFromFile() method.

l  Change the PDF version to a specified version using PdfDocument.getFileInfo().setVersion() method.

l  Save the output document to another file using PdfDocument.saveToFile() method.

import com.spire.pdf.*;

public class ChangePdfVersion {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument document = new PdfDocument();

//Load a sample PDF file
document.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.pdf");

//Change the PDF to version 1.7
document.getFileInfo().setVersion(PdfVersion.Version_1_7);

//Save to file
document.saveToFile("output/ChangePdfVersion.pdf", FileFormat.PDF);
document.close();
}
}


Set the Indentation, Margin and Spacing for Paragraphs in PowerPoint Slides

To make the text on PowerPoint slides easier to read, you might want to set indentation, margin and spacing for the paragraph where the text is located. This article will demonstrate how to programmatically perform the operation using Java codes.

DEPENDENCY

Before running codes, you need to download the package of Free Spire.Presentation for Java from this link, find Spire.Presentation.jar in the lib folder and add it to your Java program. Or if you use Maven, just type the following code in the pom.xml file to import the JAR file to IntelliJ IDEA.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.Presentation for Java supports setting the indentation, margin and spacing for a specified paragraph in a PowerPoint slide. The following are detailed steps.

l  Create a Presentation instance and load a PowerPoint sample document using Presentation.loadFromFile() method.

l  Get a specified slide using Presentation.getSlides().get() method and get a specified shape in the slide using ShapeList.get() method.

l  Get a specified paragraph in the shape using ParagraphList.get() method and set the indentation, margin and spacing for the paragraph using ParagraphPropertiesEx.setIndent(),ParagraphPropertiesEx.setLeftMargin() and ParagraphPropertiesEx.setSpaceBefore() methods.

l  Save the output document to another file using Presentation.saveToFile() method.

import com.spire.presentation.*;

public class IndentStyle {
public static void main(String[] args) throws Exception {
//Load the sample document
Presentation presentation = new Presentation();
presentation.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.pptx");

//get the shapes
IAutoShape shape = (IAutoShape) presentation.getSlides().get(0).getShapes().get(1);

//set the indent, margin and space for the first paragraph
shape.getTextFrame().getParagraphs().get(1).setIndent(30);
shape.getTextFrame().getParagraphs().get(1).setLeftMargin(10);
shape.getTextFrame().getParagraphs().get(1).setSpaceAfter(10);

//set the indent, margin and space for the third paragraph
shape.getTextFrame().getParagraphs().get(3).setIndent(-150);
shape.getTextFrame().getParagraphs().get(3).setLeftMargin(40);
shape.getTextFrame().getParagraphs().get(3).setSpaceBefore(0);
shape.getTextFrame().getParagraphs().get(3).setSpaceAfter(0);

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


Monday, 18 April 2022

Copy Table Data from PDF to Excel in Java

The PDF is a document exchange and storage program, while Excel is a spreadsheet program. In some cases, you may need to copy or import table from PDF to Excel for analyzing and editing data using Excel. This article will demonstrate how to programmatically copy or import table from PDF to Excel using Java.

DEPENDENCY

Before running codes, you need to import a JAR file to the Java program. Download Free Spire.Office for Java from this link, find Spire.Office.jar in the lib folder and add it to your program. Or if you use Maven, it’s easier to install the Jar file and you just need to type the following code in the pom.xml file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId> e-iceblue </groupId>
<artifactId>spire.office.free</artifactId>
<version>5.3.1</version>
</dependency>
</dependencies>

USING THE CODE

With Free Spire.Office for Java, you can extract all tables from a single page of a PDF document and save them as individual Excel worksheets. The following are detailed steps.

l  Load a PDF sample document while initializing the PdfDocument object.

l  Create a PdfTableExtractor instance, and use PdfTableExtractor.extactTable(int pageIndex) method to extract all tables in a specified page.

l  Create a Workbook instance, and remove all default worksheets using Workbook.getWorksheets().clear() method.

l  Loop through tables in the PdfTable[] array, and get the specific one by its index.

l  Add a worksheet to the workbook using Workbook.getWorksheets.add() method.

l  Loop through rows and columns in the PDF table, and get the value of a specific cell using PdfTable.getText(int rowIndex, int columnIndex) method. Then insert the value to the worksheet using Worksheet.get(int row, int column).setText(String string) method.

l  Save the workbook to an Excel file using Workbook.saveToFile() method.

 import com.spire.pdf.PdfDocument;

import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ExtractTableDataAndSaveInExcel {
public static void main(String[] args) {
//Load a PDF sample document
PdfDocument pdf = new PdfDocument("C:\\Users\\Tina\\Desktop\\sample.pdf");

//Create a PdfTableExtractor instance
PdfTableExtractor extractor = new PdfTableExtractor(pdf);

//Extract tables from the first page
PdfTable[] pdfTables = extractor.extractTable(0);

//Create a Workbook instance
Workbook wb = new Workbook();

//Remove default worksheets
wb.getWorksheets().clear();

//If tables are found
if (pdfTables != null && pdfTables.length > 0) {

//Loop through the tables
for (int tableNum = 0; tableNum < pdfTables.length; tableNum++) {

//Add a worksheet to workbook
String sheetName = String.format("Table - %d", tableNum + 1);
Worksheet sheet = wb.getWorksheets().add(sheetName);

//Loop through rows in the current table
for (int rowNum = 0; rowNum < pdfTables[tableNum].getRowCount(); rowNum++) {

//Loop through columns in the current table
for (int colNum = 0; colNum < pdfTables[tableNum].getColumnCount(); colNum++) {

//Extract data from the current table cell
String text = pdfTables[tableNum].getText(rowNum, colNum);

//Insert data into a specific cell
sheet.get(rowNum + 1, colNum + 1).setText(text);

}
}

//Auto fit column width
for (int sheetColNum = 0; sheetColNum < sheet.getColumns().length; sheetColNum++) {
sheet.autoFitColumn(sheetColNum + 1);
}
}
}

//Save the workbook to an Excel file
wb.saveToFile("output/ExportTableToExcel.xlsx", ExcelVersion.Version2016);
}
}



Java: Set Background Color and Fill Patterns for Excel Cells

In an Excel worksheet, in order to highlight a specific cell or cell range in an Excel worksheet, you can set the background color or fill patterns for it. This article will demonstrate how to programmatically accomplish the operation using Java codes.

BEFORE CODING

First of all, you need to get the product package of Free Spire.XLS for Java from this link, find Spire.Xls.jar in the lib folder and then add it to your Java program. Or if you use Maven, just type the following codes in the pom.xml file to import the JAR file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

USING THE CODE 

Free Spire.XLS for Java supports changing background color for a specified cell range or cell using the CellRange.getStyle().setColor() method, and also supports setting the fill pattern style for a cell range using the CellRange.getStyle().setFillPattern() method. The detailed steps are listed below.

l  Create a Workbook instance.

l  Load an Excel sampel document using Workbook.loadFromFile() method.

l  Get a specified worksheet using Workbook.getWorksheets().get() method.

l  Get a specified cell range using Worksheet.getRange().get() method, and set background color for it using CellRange.getStyle().setColor() method.

l  Get a specified cell using Worksheet.getRange().get() method, and set background color for it using CellRange.getStyle().setColor() method.

l  Get a specified cell range and set the fill pattern style for it using CellRange.getStyle().setFillPattern() method.

l  Save the output document to another file using Workbook.saveToFile() method.

import com.spire.xls.*;
import java.awt.*;

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

//Load an Excel sample document
workbook.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.xlsx");

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

//Set background color for cell range
worksheet.getRange().get("A1:F1").getStyle().setColor(Color.green);
worksheet.getRange().get("A2:A9").getStyle().setColor(Color.yellow);

//Set background color for cell E9
worksheet.getRange().get("E3").getStyle().setColor(Color.red);

//Set fill pattern style for range "C4:D5"
worksheet.getRange().get("C5:D7").getStyle().setFillPattern(ExcelPatternType.Percent25Gray);

//Save the document
workbook.saveToFile("output/CellBackground.xlsx", ExcelVersion.Version2013);
}
}



Friday, 15 April 2022

Change Font Styles of Text in PowerPoint Documents using Java

When manipulating PowerPoint documents, you sometimes set font styles of text for aesthetic or practical reasons. For example, change the font name/font size, change the font color, make font bold, italic or underlined. This article will demonstrate how to programmatically accomplish the operation using Java codes.

DEPENDENCY

First of all, you need to download the package of a third-party library called Free Spire.Presentation for Java from this link, and add Spire.Presentation.jar to the Java program. Or if you use Maven, just type the following code in the pom.xml file to easily import the JAR file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.presentation.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

USING THE CODE

The following are detailed steps to change font styles of text in a PowerPoint document.

l  Create a Presentation instance and load a PowerPoint sample document using Presentation.loadFromFile() method.

l  Get a specific slide of the document using Presentation.getSlides().get() method and get a specific text shape using the method provided by the ISlide interface.

l  Get the object of the TextFrame using IAutoShape.getTextFrame() method, and get a specified paragraph of the object using the method provided by the ITextFrameProperties interface.

l  Get the text content of the paragraph using ParagraphEx.getTextRanges().get() method.

l  Set the filling type of the text content using FillFormat.setFillType(FillFormatType value) method, and set the filling color using ColorFormat.setColor(ColorType value) method.

l  Use similar methods to specify another text shape and set the font styles, such as Italicize, bold, and underline the text.

l  Finally save the output document to another file using Presentation.saveToFile() method.

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

public class ChangeFontStyles {
public static void main(String[] args) throws Exception {
//Create a Presentation instance
Presentation presentation = new Presentation();

//Load a PowerPoint sample file
presentation.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.pptx");

//Get the first text shape
IAutoShape shape1 = (IAutoShape) presentation.getSlides().get(0).getShapes().get(0);

//Get the first paragraph and change its font color
ParagraphEx paragraph = shape1.getTextFrame().getParagraphs().get(0);
PortionEx textRange = paragraph.getFirstTextRange();
textRange.getFormat().getFill().setFillType(FillFormatType.SOLID);
textRange.getFormat().getFill().getSolidColor().setColor(Color.red);

//Get the second text shape
IAutoShape shape2 = (IAutoShape) presentation.getSlides().get(0).getShapes().get(1);

//Get the third paragraph and make the text bold, italic and underlined
paragraph = shape2.getTextFrame().getParagraphs().get(2);
textRange = paragraph.getFirstTextRange();
textRange.getFormat().isBold(TriState.TRUE);
textRange.getFormat().isItalic(TriState.TRUE);
textRange.getFormat().setTextUnderlineType(TextUnderlineType.DASHED);

//Get the eighth paragraph and change its font name and size
paragraph = shape2.getTextFrame().getParagraphs().get(7);
textRange = paragraph.getFirstTextRange();
textRange.getFormat().setLatinFont(new TextFont("Calibri"));
textRange.getFormat().setFontHeight(22f);

//Save the output document
presentation.saveToFile("output/ChangeFontStyles.pptx", FileFormat.PPTX_2013);
}
}



Tuesday, 12 April 2022

Remove Empty Word Paragraphs in Java

If a Word document has 300 pages with hundreds of empty paragraphs, it is time-consuming to manually remove all empty paragraphs one by one. This article will show you how to programmatically remove empty paragraphs in a Word document using Java codes.

DEPENDENCY

First of all, you need to download the package of a free third-party library called Free Spire.Doc for Java from this link, find Spire.Doc.jar in the lib folder, and then add it to your Java program. If you use Maven, just 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>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.Doc for Java supports removing the empty paragraphs in a Word document using ParagraphCollection.remove() method. The following are detailed steps.

l  Create a Document instance.

l  Load a Word sample document using Document.loadFromFile() method.

l  Traverse every section in the document and get sections using Document.getSections().get() method.

l  Traverse every object in the sections and get the types of objects using DocumentObject.getDocumentObjectType() method.

l  Traverse every paragraph and get paragraphs using Section.getParagraphs().get() method.

l  Determine whether the object types are paragraph and the content of paragraphs are blank or not, if the content is empty, remove it using ParagraphCollection.remove() method.

l  Save the output document to another file using Document.saveToFile() method.

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

public class removeBlankLines {
public static void main(String[] args) {
//Create a Document instance
Document doc = new Document();

//Load a Word sample document
doc.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.docx");

//Traverse every section in the document
for(int i = 0; i < doc.getSections().getCount();i++)
{
//Get sections
Section section = doc.getSections().get(i);

//Traverse objects in the sections
for (int j = 0;j < section.getBody().getChildObjects().getCount();j++)
{
//Get the types of objects
Object object = section.getBody().getChildObjects().get(j).getDocumentObjectType();

//Traverse evert paragraph
for(int z = 0 ; z < section.getParagraphs().getCount();z++)
{
//Get paragraphs
Paragraph paragraph = section.getParagraphs().get(z);

//Decide whether the object types are paragraphs or not
if(object.equals(DocumentObjectType.Paragraph))
{
//Determine whether the content of paragraphs are blank
if(paragraph.getChildObjects().getLastItem() == null)
{
//Delete blank paragraphs
section.getBody().getParagraphs().remove(paragraph);
z--;
}
}
}

}
}

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


Thursday, 7 April 2022

Create a Two-Column PDF Document in Java

In general, newspapers, magazines or some publications will use a multi-column layout on one page. So how to segment columns in PDF documents? You can use Java codes to implement the column segmentation effect at the beginning of creating a document. This article will demonstrate how to create a two-column PDF document using Free Spire.PDF for Java.

ABOUT FREE SPIRE.PDF FORJAVA

Free Spire.PDF for Java is a PDF API that enables developers to create, read, convert and save PDF documents on Java applications without using Adobe Acrobat.

DEPENDENCY

First of all, you need to add Spire.Pdf.jar to your Java program as a dependency. You can download the product package from this link, and find it in the lib folder. Or if you use Maven, just type the following code in the pom.xml to easily import the JAR file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
USING THE CODE

The following are steps to create a two-column PDF document.

l  Initialize a PdfDocument object to create a new PDF document.

l  Add a new page to the document using PdfDocument.getPages().add() method.

l  Add a line to the page and set its format using PdfPageBase.getCanvas().drawLine() method.

l  Add text at two separate rectangle areas using PdfPageBase.getCanvas().drawString() method.

l  Save the document to another file using PdfDocument.saveToFile() method.

import com.spire.pdf.FileFormat;
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 CreateTwoColumnPDF {
public static void main(String[] args) {
//Create a pdf document
PdfDocument doc = new PdfDocument();

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

//Set location and width
float x = 0;
float y = 15;
float width = 600;

//Create pen
PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 1f);

//Draw line on the PDF page
page.getCanvas().drawLine(pen, x, y, x + width, y);

//Define paragraph text
String s1 = "Be glad your nose in on your face, \n" +
"not pasted on some other place.\n" +
"For if it were where it is not,\n" +
"You might dislike your nose a lot.\n" +
"\n" +
"Imagine if your precious nose\n" +
"were sandwiched in between your toes,\n" +
"that clearly would not be a treat,\n" +
"For you’d be forced to smell your feet.\n" +
"\n" +
"Your nose would be a source of dread, \n" +
"were it attached atop your head.\n" +
"It soon would drive you to despair,\n" +
"forever tickled by your hair.\n";
String s2 = "Within your ear, your nose would be \n" +
"an absolute catastrophe,\n" +
"For when you were obliged to sneeze,\n" +
"your brain would rattle from the breeze.\n" +
"\n" +
"Your nose, instead, through thick and thin,\n" +
"remains between your eyes and chin,\n" +
"not pasted on some other place--\n" +
"be glad your nose is on your face!\n";

//Get width and height of page
double pageWidth = page.getClientSize().getWidth();
double pageHeight = page.getClientSize().getHeight();

//Create solid brush objects
PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.BLACK));

//Create true type font objects
PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Times New Roman",Font.PLAIN,14));

//Set the text alignment via PdfStringFormat class
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);

//Draw text
page.getCanvas().drawString(s1, font, brush, new Rectangle2D.Double(0, 20, pageWidth / 2 - 8f, pageHeight), format);
page.getCanvas().drawString(s2, font, brush, new Rectangle2D.Double(pageWidth / 2 + 8f, 20, pageWidth / 2 - 8f, pageHeight), format);

//Save the document
String output = "output/createTwoColumnPDF.pdf";
doc.saveToFile(output, FileFormat.PDF);
}
}


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