Monday, 29 November 2021

Convert PDF to Image with Transparent Background

In a previous article, I introduced how to use the PdfDocument.saveAsImage() method provided by Free Spire.PDF for Java to convert each page of a PDF document to a normal image. This tutorial will demonstrate how to set the background transparency of the image converted from PDF using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you need to download the product package from the link, and then manually add the Spire.Pdf.jar file as a dependency in the Java program. Or you can create a Maven project in the Java application, and add the following code to 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.pdf</artifactId>
<version>4.11.1</version>
</dependency>
</dependencies>

Using the code

Spire.PDF for Java provides PdfDocument.getConvertOptions().setPdfToImageOptions() method to set the transparent value of the resulted image’s background. The following are detailed steps for your reference.

l  Create a PdfDocument instance.

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

l  Set the background transparent value of the image converted from PDF using PdfDocument.getConvertOptions().setPdfToImageOptions() method.

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

import com.spire.pdf.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PdfToImage {
public static void main(String[] args) throws IOException {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();

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

//Set the background transparent value as 0
pdf.getConvertOptions().setPdfToImageOptions(0);

//Save the document to a .png image
BufferedImage image = pdf.saveAsImage(0);
File file = new File( String.format("output/ToImage.png"));
ImageIO.write(image, "PNG", file);
}
}



Thursday, 25 November 2021

Java: Convert Excel to CSV and Vice Versa

A CSV (Comma Separated Values) file is a plain text file that contains only text and numbers and you can create and edit it in Excel. Rather than storing information in columns, A CSV file stores information separated by commas. This article will show you how to convert Excel to CSV and convert CSV to Excel using Java codes.

DEPENDENCY

In this code sample, we’ll use a third-party library called Spire.XLS for Java. First of all, we can get the product package from the link, and add the Spire.Xls.jar file as a dependency in the Java program. Or create a Maven project and then add the following code to the pom.xml file to add the JAR file to the Java application.

<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 </artifactId>
<version>4.11.3</version>
</dependency>
</dependencies>

Convert Excel to CSV

Spire.XLS for Java supports converting Excel to CSV with only several lines of codes. Here are steps to follow.

l  Create a Workbook instance.

l  Load a sample Excel document using Workbook.loadFromFile() method.

l  Get a specific worksheet of the document using Workbook.getWorksheets().get() method.

l  Save the worksheet to CSV using Worksheet.saveToFile() method.

import com.spire.xls.*;
import java.nio.charset.Charset;

public class ExcelToCSV {
public static void main(String[] args) {

//Create a workbook
Workbook workbook = new Workbook();

//Load a sample excel file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.xlsx");

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

//Save the document to CSV
sheet.saveToFile("output/ToCSV_out.csv", ",", Charset.forName("UTF-8"));
}
}

Convert CSV to Excel

In addition to converting Excel to CSV, Free Spire.XLS for Java also supports converting CSV to Excel by using Workbook.saveToFile() method. In this process, we can set ignore error options when setting numbers in cells as text and can adjust the height of rows and width of columns too. The following are detailed steps for your reference.

l  Create a Workbook instance and load a sample CSV file using Workbook.loadFromFile() method.

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

l  Specify the cell range using Worksheet.getCellRange() method and ignore errors when setting numbers in the cells as text using CellRange.setIgnoreErrorOptions(java.util.EnumSet<IgnoreErrorType> ignoreErrorOptions) method.

l  Automatically adjust the height of rows and width of columns using methods provided by CellRange class.

l  Save the document to an XLSX file using Workbook.saveToFile() method.

import com.spire.xls.*;
import java.util.EnumSet;

public class CSVToExcel {
public static void main(String[] args) {
//Create a workbook
Workbook workbook = new Workbook();
//Load a sample CSV file
workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\test.csv", ",", 1, 1);

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

//Specify the cell range and ignore errors when setting numbers in the cells as text
sheet.getCellRange("A1:D6").setIgnoreErrorOptions(EnumSet.of(IgnoreErrorType.NumberAsText));

//Automatically adjust the height of the rows and width of the columns
sheet.getAllocatedRange().autoFitColumns();
sheet.getAllocatedRange().autoFitRows();

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



Monday, 22 November 2021

Create a Scatter Chart in PowerPoint using Java

A scatter chart, also known as an XY scatter chart, refers to a chart consisting of some scattered points, where each point has its own X and Y values. We can choose whether to connect these points or not as needed. This article will introduce how to create a scatter chart in a PowerPoint slide using Java codes with Free Spire.Presentation for Java.

ABOUT FREE SPIRE.PRESENTATION FOR JAVA

Free Spire.Presentation for Java is a free professional PowerPoint API that enables developers to create, read, write, convert and save PowerPoint documents in Java Applications. As an independent Java library, it doesn't need Microsoft PowerPoint to be installed on system.

DEPENDENCY

First of all, we need to download the Spire.Presentation.jar file from the link, and add it to the Java program as a dependency. Or we can create a Maven project and add the following code to the pom.xml file to import the JAR file in the application.

<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>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.Presentation for Java offers ShapeCollection.appendChart(ChartType type, Rectangle2D rectangle, boolean init) method to insert a specific type of charts into a presentation slide. The ChartType enumeration pre-defines 73 chart types, including scatter chart, column chart, pie chart, etc. Here are detailed steps to follow.

l  Create a Presentation object.

l  Add a scatter chart to the specific slide using ShapeCollection.appendChart() method.

l  Set the chart data through ChartData.get().setValue() method.

l  Set the chart title, axes titles, series labels, etc. using the methods under IChart interface.

l  Set the grid line style and data point line style.

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

import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideSizeType;
import com.spire.presentation.TextLineStyle;
import com.spire.presentation.charts.ChartType;
import com.spire.presentation.charts.IChart;
import com.spire.presentation.charts.entity.ChartDataLabel;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

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

//Add a scatter chart to the first slide
IChart chart = presentation.getSlides().get(0).getShapes().appendChart(ChartType.SCATTER_SMOOTH_LINES_AND_MARKERS,new Rectangle2D.Float(40, 80, 550, 320),false);

//Set the chart title
chart.getChartTitle().getTextProperties().setText("Scatter Chart");
chart.getChartTitle().getTextProperties().isCentered(true);
chart.getChartTitle().setHeight(20f);
chart.hasTitle(true);

//Set the chart data
Double[] xData = new Double[] { 1.0, 2.4, 5.0, 8.9 };
Double[] yData = new Double[] { 5.3, 15.2, 6.7, 8.0 };
chart.getChartData().get(0,0).setText("X-Values");
chart.getChartData().get(0,1).setText("Y-Values");
for (int i = 0; i < xData.length; i++) {
chart.getChartData().get(i+1,0).setValue(xData[i]);
chart.getChartData().get(i+1,1).setValue(yData[i]);
}

//Set the series label
chart.getSeries().setSeriesLabel(chart.getChartData().get("B1","B1"));

//Set the X and Y values
chart.getSeries().get(0).setXValues(chart.getChartData().get("A2","A5"));
chart.getSeries().get(0).setYValues(chart.getChartData().get("B2","B5"));

//Add data labels
for (int i = 0; i < 4; i++)
{
ChartDataLabel dataLabel = chart.getSeries().get(0).getDataLabels().add();
dataLabel.setLabelValueVisible(true);
}

//Set the primary axis title and the secondary axis title
chart.getPrimaryValueAxis().hasTitle(true);
chart.getPrimaryValueAxis().getTitle().getTextProperties().setText("X-Axis Title");
chart.getSecondaryValueAxis().hasTitle(true);
chart.getSecondaryValueAxis().getTitle().getTextProperties().setText("Y-Axis Title");

//Set the grid line
chart.getSecondaryValueAxis().getMajorGridTextLines().setFillType(FillFormatType.SOLID);
chart.getSecondaryValueAxis().getMajorGridTextLines().setStyle(TextLineStyle.THIN_THIN);
chart.getSecondaryValueAxis().getMajorGridTextLines().getSolidFillColor().setColor(Color.GRAY);
chart.getPrimaryValueAxis().getMajorGridTextLines().setFillType(FillFormatType.NONE);

//Set the data point line
chart.getSeries().get(0).getLine().setFillType(FillFormatType.SOLID);
chart.getSeries().get(0).getLine().setWidth(0.1f);
chart.getSeries().get(0).getLine().getSolidFillColor().setColor(Color.BLUE);

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



Wednesday, 17 November 2021

Java: Hide a Specific Paragraph in Word

When working with a Word document, we can encrypt the document to ensure its confidentiality. As an alternative, we can also choose to hide specific text content to prevent others from seeing them. This article will demonstrate how to programmatically hide a specific paragraph in a Word document using Java codes.

DEPENDENCY

In order to realize the function of hiding a specific paragraph in Word, we’ll need to use a free third-party library called Free Spire.Doc for Java. First of all, we can get the library from the link, and then add Spire.Doc.jar as a dependency in Java program. Or directly import it by adding the following Maven configuration 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.doc.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.Doc for Java provides TextRange.getCharacterFormat().setHidden(boolean value) method to hide a specific paragraph in a Word document. The following are detailed steps.

l  Create a Document instance.

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

l  Get a specific section of the Word document using Document.getSections().get() method.

l  Get a specific paragraph of the section using Section.getParagraphs().get() method.

l  Loop through the child objects of the paragraph, and convert each child object as a text range if it is plain text. Then hide the text range using TextRange.getCharacterFormat().setHidden(boolean value) method.

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

import com.spire.doc.*;

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

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

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

//Get a specific section of Word
Section sec = document.getSections().get(0);

//Get a specific paragraph of the section
Paragraph para = sec.getParagraphs().get(1);

//Loop through the child objects
for (Object docObj : para.getChildObjects()) {
DocumentObject obj = (DocumentObject)docObj;

//Determine if a child object is an instance of TextRange
if ((obj instanceof TextRange)) {
TextRange range = ((TextRange)(obj));

//Hide the text range
range.getCharacterFormat().setHidden(true);
}
}

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


Sunday, 14 November 2021

Apply Data Bars in Excel using Java

In Excel, Data Bars is the combination of Data and a Bar Chart inside the cell, which shows the percentage of selected data or the position of the selected value on the bars inside the cell. This article will show you how to programmatically apply Data Bars in a specific range of cells in Excel using Java codes.

DEPENDENCY

In order to finish the operation above, you need to use a third-party library called Free Spire.XLS for Java. First of all, you need to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be gotten from this link, or you can easily import the JAR file by adding the following code to 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.xls.free</artifactId>
<version>3.9.1</version>
</dependency>
</dependencies>

USING THE CODE

Actually Data Bars is a type of Conditional Formatting offered by Microsoft Excel. Free Spire.XLS for Java provides ConditionalFormats.addCondition() method to add a new conditional formatting and ConditionalFormatWrapper.setFormatType() method to set the type of the new conditional formatting as DataBar. Here are detailed steps to follow.

l  Create a Workbook instance.

l  Load a sample Excel file using Workbook.loadFromFile() method.

l  Get a specific worksheet in Excel using Workbook.getWorksheets().get() method.

l  Get a specific cell range using Worksheet.getCellRange() method.

l  Add a new conditional formatting to the cell range using ConditionalFormats. addCondition(), and then set the type of the new conditional formatting as DataBar using ConditionalFormatWrapper.setFormatType() method.

l  Set the color of the Data Bar using DataBar.setBarColor() method.

l  Save the document using Workbook.saveToFile() method.

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

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

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

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

//Get the specific cell range
CellRange range = sheet.getCellRange("D3:D6");

//Add the conditional formatting of data bars in the cell range
IConditionalFormat format = range.getConditionalFormats().addCondition();
format.setFormatType( ConditionalFormatType.DataBar);

//Set color for the data bars
format.getDataBar().setBarColor( Color.PINK);

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




Thursday, 11 November 2021

Java: Find Text and Add Hyperlinks for Them in PDF

In PDF, a hyperlink allows viewers to jump to another document or a website. In this article, I’ll show you how to automatically add hyperlinks to all matching text on a specific PDF page by using Java codes.

DEPENDENCY

I used a free third-party library called Free Spire.PDF for Java to finish the operation above. First of all, I’ll add the Spire.PDF.jar file as a dependency in Java program. The JAR file can be downloaded from this link, or directly add the following Maven configuration to 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.pdf.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.PDF for Java will use the method provided by PdfTextFindCollection class to find all matched text

in a specific PDF page and set hyperlinks for them. Here are the detailed steps to follow.

l  Create a PdfDocument instance and load a sample PDF document using PdfDocument.loadFromFile() method.

l  Get a specific page of the document using PdfDocument.getPages().get() method.

l  Find all matched text in the page using PdfPageBase.findText(String searchPatternText, boolean isSearchWholeWord)

method, and return a PdfTextFindCollection object.

l  Create a PdfUriAnnotation instance based on the bounds of a specific find result.

l  Set a URL address for the annotation using PdfUriAnnotation.set(String value) method and set its border and color as well.

l  Add the URL annotation to the PDF annotation collection as a new annotation using PdfPageBase.getAnnotationWidget().add()

method.

l  Save the document using PdfDocument.saveToFile() method.

import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.general.find.*;
import com.spire.pdf.graphics.PdfRGBColor;
import java.awt.*;

public class SearchTextAndAddHyperlink {
public static void main(String[] args) {
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();

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

//Get the first page
PdfPageBase page = pdf.getPages().get(0);

//Find all matched strings and return a PdfTextFindCollection object
PdfTextFindCollection collection = page.findText("Java", false);

//loop through the find collection
for(PdfTextFind find : collection.getFinds())
{
// Create a PdfUriAnnotation instance to add hyperlinks for the searched text
PdfUriAnnotation uri = new PdfUriAnnotation(find.getBounds());
uri.setUri("https://www.oracle.com/index.html");
uri.setBorder(new PdfAnnotationBorder(1f));
uri.setColor(new PdfRGBColor(Color.blue));
page.getAnnotationsWidget().add(uri);
}

//Save the document
pdf.saveToFile("output/searchTextAndAddHyperlink.pdf");
}
}

Monday, 8 November 2021

Set Transparency for Images in PowerPoint using Java

In a PowerPoint document, we can set the transparency of the pictures in the shapes to enable the text in the shapes to be displayed on top of the picture without being obscured by it. In this article, I’ll introduce how to set transparency for images in PowerPoint using Java codes.

DEPENDENCY
We need to use a free third-party library called Free Spire.Presentation for Java in order to realize the 
function above. First of all, we add the Spire.Presentation.jar file as a dependency in Java program. It can 
be gotten from the link, or we can directly import it by adding the following code to the project's 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.presentation.free</artifactId>
<version>3.9.0</version>
</dependency>
</dependencies>
USING THE CODE
The code sample will insert an image to a specified slide in PowerPoint, and then set its transparency 
in order to show the text in the shape above the image. The following are some steps to do that.
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 insert a shape to the specified position of
the slide using ShapeList.appendShape(ShapeType.shapeType, Rectangle2D.Double) method.
l  Fill the shape with an image and set the fill format type using IAutoShape.getFill().setFillType(FillFormatType.value) method.
l  Get the picture fill format using IAutoShape.getFill().getPictureFill() method. 
l  Set the picture fill mode using PictureFillFormat.setFillType(PictureFillType.value) method, set the image’s URL 
using PictureFillFormat.getPicture().setUrl(java.lang.String value) method, and set the transparency of the image 
using PictureFillFormat.getPicture().setTransparency() method.
l  Save the document using Presentation.saveToFile() method.
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;
import java.awt.geom.Rectangle2D;

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

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

//Insert a shape to the specified position of the first slide
Rectangle2D.Double rect1 = new Rectangle2D.Double(220, 65, 260, 70);
IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, rect1);

//Fill the shape with an image
shape.getLine().setFillType(FillFormatType.NONE);//Sets the fill format type
shape.getFill().setFillType(FillFormatType.PICTURE);//Sets the type of filling
shape.getFill().getPictureFill().getPicture().setUrl("C:\\Users\\Test1\\Desktop\\Picture.png");//Sets the linked image's URL
shape.getFill().getPictureFill().setFillType(PictureFillType.STRETCH);//Sets the picture fill mode

//Set transparency of the image
shape.getFill().getPictureFill().getPicture().setTransparency(50);

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

Output



Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...