Friday, 26 November 2021 06:18

Java: Convert Word to EPUB

EPUB (short for electronic publication) is a popular file format for e-books. EPUB files can be read on numerous e-readers and most smartphones, tablets and computers. In some circumstances, you might need to convert your Word document to EPUB file format to make it readable on various devices. This article will show you how to achieve this task programmatically in Java using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<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</artifactId>
        <version>4.11.8</version>
    </dependency>
</dependencies>

Convert Word to EPUB

The following are the steps to convert a Word document to EPUB file format:

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Save the Word document to EPUB using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class ConvertWordToEpub {
    public static void main(String[] args){
        //Create a Document instance
        Document doc = new Document();
        //Load a Word document
        doc.loadFromFile("Sample.docx");

        //Save the Word document to EPUB format
        doc.saveToFile("ToEpub.epub", FileFormat.E_Pub);
    }
}

Java: Convert Word to EPUB

Convert Word to EPUB with a Cover Image

The following are the steps to convert a Word document to EPUB with a cover image:

  • Create a Document instance.
  • Load a Word document using Document.loadFromFile() method.
  • Create a DocPicture instance.
  • Load an image using DocPicture.loadImage() method.
  • Save the Word document to EPUB with cover image using Document.saveToEpub(String, DocPicture) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.fields.DocPicture;

public class ConvertWordToEpubWithCoverImage {
    public static void main(String[] args){
        //Create a Document instance
        Document doc = new Document();
        //Load a Word document
        doc.loadFromFile("Sample.docx");

        //Create a DocPicture instance
        DocPicture picture = new DocPicture(doc);
        //Load an image
        picture.loadImage("Cover.png");

        //Save the Word document to EPUB with cover image
        doc.saveToEpub("ToEpubWithCoverImage.epub", picture);
    }
}

Java: Convert Word to EPUB

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Friday, 26 November 2021 01:49

Spire.Office 6.11.2 is released

We are excited to announce the release of Spire.Office 6.11.2. This version brings some new features, for example, Spire.XLS supports to set drop lines for line chart and area chart; Spire.Doc adds two new method; Spire.PDF supports converting PDF to linearized PDF; Spire.Presentation supports getting the display color of the table cell border. Meanwhile, a lot of bugs have been successfully fixed. More details are listed as follow.

In this version, the most recent versions of Spire.Doc, Spire.PDF, Spire.XLS, Spire.Presentation, Spire.Email, Spire.DocViewer, Spire.PDFViewer, Spire.Spreadsheet, Spire.OfficeViewer, Spire.DataExport, Spire.Barcode are included.

DLL Versions:

  • Spire.Doc.dll v9.11.6
  • Spire.Pdf.dll v7.11.1
  • Spire.XLS.dll v11.11.2.
  • Spire.Email.dll v4.11.1
  • Spire.DocViewer.Forms.dll v6.8.0
  • Spire.PdfViewer.Forms.dll v6.11.1
  • Spire.PdfViewer.Asp.dll v6.11.1
  • Spire.Presentation.dll v6.11.4
  • Spire.Spreadsheet v5.10.0
  • Spire.OfficeViewer.Forms.dll v6.11.2
  • Spire.Barcode.dll v5.9.4
  • Spire.DataExport.dll v4.1.9
  • Spire.DataExport.ResourceMgr.dll v2.1.0
  • Spire.License.dll v1.4.0
Click the link to get the version Spire.Office 6.11.2
More information of Spire.Office new release or hotfix:

Here is a list of changes made in this release

Spire.XLS

Category ID Description
New feature SPIREXLS-1805 Supports to set border for data bar of chart.
XlsConditionalFormats cfs = sheet.ConditionalFormats[0];
IConditionalFormat cf = cfs[0];
Spire.Xls.DataBar dataBar1 = cf.DataBar;
dataBar1.BarBorder.Type = Spire.Xls.Core.Spreadsheet.ConditionalFormatting.DataBarBorderType.DataBarBorderSolid;
dataBar1.BarBorder.Color = Color.GreenYellow; 
New feature SPIREXLS-3453 Supports to set drop lines for line chart and area chart.
chart.Series[0].HasDroplines = true; 
New feature SPIREXLS-3487 Supports to set the customized page size when converting an excel file to pdf.
workbook.Worksheets[0].PageSetup.SetCustomPaperSize(width, height); 
Bug SPIREXLS-2906 Fixes the issue that the location of picture was incorrect when converting an excel file to html
Bug SPIREXLS-3456 Fixes the issue that the content was clipped when converting an excel file to pdf file
Bug SPIREXLS-3461 Fixes the issue that the content was incorrect when converting a combination chart to image
Bug SPIREXLS-3515 Fixes the issue that the application hung when loading an ods file
Bug SPIREXLS-3516 Fixes the issue that the content was incorrect when converting an excel file to pdf
Bug SPIREXLS-3542 Fixes the issue that MS Excel failed to open the saved xlsx file

Spire.PDF

Category ID Description
New feature SPIREPDF-4594 Supports getting the page number of the attachment.
int page = pdf.Attachments.GetAttachmentPage("attachmentFileName");
New feature - Supports converting PDF to linearized PDF.
PdfToLinearizedPdfConverter converter = new PdfToLinearizedPdfConverter("inputFile");
converter.ToLinearizedPdf("outputFile");
Bug SPIREPDF-2356 Fixes the issue that the content was incorrect after converting PDF to Word.
Bug SPIREPDF-4311 Optimizes the time for converting PDF to images.
Bug SPIREPDF-4587 Fixes the issue that an error prompted when opening the result file after compressing the PDF file.
Bug SPIREPDF-4609 Fixes the issue that some digital signatures were missing after merging PDF files.
Bug SPIREPDF-4622 Fixes the issue that it didn't get the correct name of the used font.
Bug SPIREPDF-4637 Fixes the issue that the barcodes were incorrect after converting PDF to images.
Bug SPIREPDF-4660 Optimizes the memory consumption for converting PDF to PDFA.
Bug SPIREPDF-4701 Fixes the issue that the application threw the error "Header checksum illegal" when loading the PDF file.
Bug SPIREPDF-4703 Fixes the issue that the extracted content was incomplete.
Bug SPIREPDF-4721 Fixes the issue that the font size of the inserted checkbox field was incorrect.
Bug SPIREPDF-4736
SPIREPDF-4727
Optimizes the time for adding watermarks.
Bug SPIREPDF-4731 Fixes the issue that setting line width for the PdfPolyLineAnnotation did not take effect.
Bug SPIREPDF-4732 Fixes the issue that the content extracted from PDF tables was incorrect.
Bug SPIREPDF-4739 Fixes the issue that the content extracted from the specified rectangular area was incorrect.
Bug SPIREPDF-4745 Fixes the issue that the application threw the error "Object reference not set to an instance of an object" when converting PDF to images.

Spire.Doc

Category ID Description
New feature - Adds a new method "SetColumnWidth" to set table column width.
table.SetColumnWidth(int columnIndex, float columnWidth, CellWidthType columnWidthType); 
New feature - Adds a new method "UseNewEngine" to use new engine to convert Word to PDF.
Document doc = new Document();
doc.LoadFromFile("input.docx");
doc.UseNewEngine = true;
doc.SaveToFile("result.pdf", FileFormat.PDF); 
Adjustment - Adjusts the method of setting table cell width.
//Old method
//tableCell.Width //Deprecated
//tableCell.CellWidthType //Deprecated

//New method
tableCell.SetCellWidth(float width, CellWidthType widthType); 

Spire.Presentation

Category ID Description
New feature SPIREPPT-1687 Supports getting the fill color of table cells.
table.TableRows[i][j].DisplayColor;
New feature SPIREPPT-1701 Supports setting the data label range for charts.
Presentation ppt = new Presentation();
IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.ColumnStacked, new RectangleF(100, 100, 500, 400));
CellRange cellRange = chart.ChartData["F1"];
cellRange.Text = "aaa";
cellRange = chart.ChartData["F2"];
cellRange.Text = "bbb";
cellRange = chart.ChartData["F3"];
cellRange.Text = "ccc";
cellRange = chart.ChartData["F4"];
cellRange.Text = "ddd";
chart.Series[0].DataLabelRanges = chart.ChartData["F1", "F4"];
ChartDataLabel dataLabel1 = chart.Series[0].DataLabels.Add();
dataLabel1.ID = 0;
dataLabel1.LabelValueVisible = true;
dataLabel1.ShowDataLabelsRange = true;
New feature SPIREPPT-1707 Supports to get the path data of the custom animation.
foreach (AnimationEffect effect in shape.Slide.Timeline.MainSequence)
{
    if (effect.ShapeTarget.Equals(shape as Spire.Presentation.Shape))
    {
        MotionPath path = ((AnimationMotion)effect.CommonBehaviorCollection[0]).Path;
        foreach (MotionCmdPath motionCmdPath in path)
        {
            PointF[] points = motionCmdPath.Points;
            MotionCommandPathType type = motionCmdPath.CommandType;
        }
    }
}
New feature SPIREPPT-1708 Adds a new method "IShape.SaveAsImage()" to convert shape to images.
Image image = shape.SaveAsImage();
New feature SPIREPPT-1744 Supports getting the display color of the table cell border.
table[0, 0].BorderLeftDisplayColor;
table[0, 0].BorderTopDisplayColor;
table[0, 0].BorderRightDisplayColor;
table[0, 0].BorderBottomDisplayColor; 
Bug SPIREPPT-1453 Fixes the issue that the newly inserted shape did not have default line width and color.
Bug SPIREPPT-1667 Fixes the issue that the images were not clear enough after converting PPT to images.
Bug SPIREPPT-1699 Fixes the issue that it couldn't get the background color of the theme.
Bug SPIREPPT-1709 Fixes the issue that the content was incorrect after converting shape to image.
Bug SPIREPPT-1717 Fixes the issue that it didn't get the correct display color of the TextRange.
Bug SPIREPPT-1731 Fixes the issue that the inserted clustered column chart was incorrect.
Bug SPIREPPT-1723 Fixes the issue that the image converted from PowerPoint formula was blurred
Bug SPIREPPT-1732 Fixes the issue that the symbol lost when converting PowerPoint to PDF
Bug SPIREPPT-1738 Fixes the issue that the obtained font size of the text was incorrect
Bug SPIREPPT-1739 Fixes the issue that the application threw "Spire.Presentation.AppException" when loading a PPT file.
Bug SPIREPPT-1743 Fixes the issue that the application threw "System.NullReferenceException" when replacing text
Bug SPIREPPT-1751 Fixes the issue that the application threw "System.ArgumentException" when converting group shpes to image

Spire.Email

Category ID Description
Bug SPIREEMAIL-48 Fixes the issue that the addresser was incorrect when saving the email extracted from a PST file to eml format
Friday, 26 November 2021 01:39

Java: Convert Excel to CSV and Vice Versa

As its name suggests, a Comma Separated Values (CSV) file is a plain text file containing only numbers and letters, usually separated by commas. It can be used for exchanging data between applications. This article demonstrates how to convert Excel to CSV and convert CSV to Excel using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<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.2</version>
    </dependency>
</dependencies>

Convert Excel to CSV

Spire.XLS for Java supports converting Excel to CSV with only several lines of codes. To get started, follow these steps.

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specific worksheet of the document using Workbook.getWorksheets().get() method.
  • Save the worksheet to CSV using Worksheet.saveToFile() method.
  • Java
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"));
    }
}

Java: Convert Excel to CSV and Vice Versa

Convert CSV to Excel

The following are detailed steps to convert CSV to Excel.

  • Create a Workbook instance and load a sample CSV file using Workbook.loadFromFile() method.
  • Get a specific worksheet using Workbook.getWorksheets().get() method.
  • 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 ignoreErrorOptions) method.
  • Automatically adjust the height of rows and width of columns using methods provided by CellRange class.
  • Save the document to an XLSX file using Workbook.saveToFile() method.
  • Java
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 an XLSX file
        workbook.saveToFile("output/CSVToExcel_out.xlsx", ExcelVersion.Version2013);
    }
}

Java: Convert Excel to CSV and Vice Versa

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

We are happy to announce the release of Spire.XLS 11.11.2. This version supports to set border for data bar of chart, and set drop lines for line chart and area chart, as well as set the customized page size when converting an excel file to pdf. It also enhances the conversion from Excel to PDF, Excel to HTML. In addition, it fixes some known issues like MS Excel failed to open the saved xlsx file. More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature SPIREXLS-1805 Supports to set border for data bar of chart.
XlsConditionalFormats cfs = sheet.ConditionalFormats[0];
IConditionalFormat cf = cfs[0];
Spire.Xls.DataBar dataBar1 = cf.DataBar;
dataBar1.BarBorder.Type = Spire.Xls.Core.Spreadsheet.ConditionalFormatting.DataBarBorderType.DataBarBorderSolid;
dataBar1.BarBorder.Color = Color.GreenYellow; 
New feature SPIREXLS-3453 Supports to set drop lines for line chart and area chart.
chart.Series[0].HasDroplines = true; 
New feature SPIREXLS-3487 Supports to set the customized page size when converting an excel file to pdf.
workbook.Worksheets[0].PageSetup.SetCustomPaperSize(width, height); 
Bug SPIREXLS-2906 Fixes the issue that the location of picture was incorrect when converting an excel file to html
Bug SPIREXLS-3456 Fixes the issue that the content was clipped when converting an excel file to pdf file
Bug SPIREXLS-3461 Fixes the issue that the content was incorrect when converting a combination chart to image
Bug SPIREXLS-3515 Fixes the issue that the application hung when loading an ods file
Bug SPIREXLS-3516 Fixes the issue that the content was incorrect when converting an excel file to pdf
Bug SPIREXLS-3542 Fixes the issue that MS Excel failed to open the saved xlsx file
Click the link to download Spire.XLS 11.11.2
More information of Spire.XLS new release or hotfix:

We are happy to announce the release of Spire.XLS for Java 4.11.3. This version enhances the conversion from Excel to PDF, it also fixes some known issues like the checked "Align with page margins" item was missing. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREXLS-2736 Fixes the issue that the format was not correct when converting an excel to PDF
Bug SPIREXLS-3158 Fixes the issue that the obtained cell value of the date format was wrong
Bug SPIREXLS-3485 Fixes the issue that the checked "Align with page margins" item was missing
Click the link to download Spire.XLS for Java 4.11.3
Thursday, 25 November 2021 08:55

Java: Preform Mail Merge with a Region

When you run mail merge with a region, all merge fields within the region are repeated for each record in the data source. This is useful when you want to dynamically add rows to a Word table. In this article, you will learn how to perform mail merge with a region using Spire.Doc for Java.

Install Spire.Doc for Java

First of all, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<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</artifactId>
        <version>4.11.8</version>
    </dependency>
</dependencies>

Create a Template

To create a mail merge region, you need to specify the start point and the end point of the region. For example, the following Word template contains the region "Country" which is marked by «TableStart:Country» and «TableEnd:Country». Mail Merge will repeat that region for each record in the data source.

Java: Preform Mail Merge with a Region

The following is the sample XML file that will be used as the data source.

  • Package Manager
<?xml version="1.0" encoding="UTF-8"?>
<Data>
	<Country>
		<Capital>Buenos Aires</Capital>
		<Name>Argentina</Name>
		<Continent>South America</Continent>
		<Area>2777815</Area>
		<Population>32300003</Population>
	</Country>
	<Country>
		<Capital>La Paz</Capital>
		<Name>Bolivia</Name>
		<Continent>South America</Continent>
		<Area>1098575</Area>
		<Population>7300000</Population>
	</Country>
	<Country>
		<Capital>Brasilia</Capital>
		<Name>Brazil</Name>
		<Continent>South America</Continent>
		<Area>8511196</Area>
		<Population>150400000</Population>
	</Country>	
	<Country>
		<Capital>Buenos Aires</Capital>
		<Name>Argentina</Name>
		<Continent>South America</Continent>
		<Area>2777815</Area>
		<Population>32300003</Population>
	</Country>
	<Country>
		<Capital>La Paz</Capital>
		<Name>Bolivia</Name>
		<Continent>South America</Continent>
		<Area>1098575</Area>
		<Population>7300000</Population>
	</Country>
</Data>

Preform Mail Merge with a Region

The following are the steps to preform mail merge with a region.

  • Create a Document object.
  • Load the Word template file using Document.loadFromFile() method.
  • Execute mail merge with a region using Document.getMailMerge().executeWidthRegion() method.
  • Save the changes to another file using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class MailMergeWithRegions {

    public static void main(String[] args) throws Exception {

        //Create a Document object
        Document doc = new Document();

        //Load the Word template file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\MailMergeTemplate.docx");

        //Execute mail merge with a region
        doc.getMailMerge().executeWidthRegion("C:\\Users\\Administrator\\Desktop\\Data.xml");

        //Save the changes to another file
        doc.saveToFile("output/MailMergeWithRegions.docx", FileFormat.Docx_2013);
    }
}

Java: Preform Mail Merge with a Region

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

We are glad to announce the release of Spire.Presentation 6.11.4. This version supports getting the display color of the table cell border. In addition, it enhances the conversion from PowerPoint to images, PowerPoint to PDF, and also fixes the issue that the obtained font size of the text was incorrect. More details are listed below.

Here is a list of changes made in this release

Category ID Description
New feature SPIREPPT-1744 Supports getting the display color of the table cell border.
table[0, 0].BorderLeftDisplayColor;
table[0, 0].BorderTopDisplayColor;
table[0, 0].BorderRightDisplayColor;
table[0, 0].BorderBottomDisplayColor; 
Bug SPIREPPT-1723 Fixes the issue that the image converted from PowerPoint formula was blurred
Bug SPIREPPT-1732 Fixes the issue that the symbol lost when converting PowerPoint to PDF
Bug SPIREPPT-1738 Fixes the issue that the obtained font size of the text was incorrect
Bug SPIREPPT-1739 Fixes the issue that the application threw "Spire.Presentation.AppException" when loading a PPT file.
Bug SPIREPPT-1743 Fixes the issue that the application threw "System.NullReferenceException" when replacing text
Bug SPIREPPT-1751 Fixes the issue that the application threw "System.ArgumentException" when converting group shpes to image
Click the link below to download Spire.Presentation 6.11.4
More information of Spire.Presentation new release or hotfix:
Wednesday, 24 November 2021 09:00

Java: Convert Excel to XPS

XPS (XML Paper Specification) is a fixed-layout document format designed for sharing and publishing purposes. The format was originally created as an attempt to take the place of PDF file format, but it failed for a number of reasons. Regardless, the XPS file format is still being used in some occasions, and sometimes you may need to convert your Excel files to XPS files. This article will introduce how to accomplish this task using Spire.XLS for Java.

Install Spire.XLS for Java

First of all, you're required to add the Spire.Xls.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<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</artifactId>
        <version>4.11.2</version>
    </dependency>
</dependencies>

Convert Excel to XPS

The Workbook.saveToFile() method offered by Spire.XLS for Java enables you to easily convert Excel files to XPS with just a few lines of code. The detailed steps are as follows.

  • Create a Workbook instance.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Save the document to XPS file format using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

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

        //Load an Excel document
        workbook.loadFromFile("test.xlsx");

        //Convert Excel to XPS
        workbook.saveToFile("ToXPS.xps", FileFormat.XPS);
    }
}

Java: Convert Excel to XPS

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

We are happy to announce the release of Spire.Email 4.11.1. This version fixes the issue that the addresser was incorrect when saving the email extracted from a PST file to eml format. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREEMAIL-48 Fixes the issue that the addresser was incorrect when saving the email extracted from a PST file to eml format
Click the link to download Spire.Email 4.11.1:

When we add a trademark, copyright or other symbol to our presentation, we might want the symbol to appear slightly above or below a certain text. In Microsoft PowerPoint, we can implement this effect simply by applying superscript or subscript formatting to the symbol. In this article, we will demonstrate how to achieve this task programmatically in Java using Spire.Presentation for Java.

Install Spire.Presentation for Java

First of all, you're required to add the Spire.Presentation.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

  • Package Manager
<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</artifactId>
        <version>4.11.4</version>
    </dependency>
</dependencies>

Add Superscript and Subscript

Spire.Presentation for Java provides the PortionEx.getFormat().setScriptDistance(float value) method for applying superscript or subscript formatting to text. The value can be set as positive or negative. The bigger the positive value, the higher the superscript will appear above your text. The smaller the negative value, the lower the subscript will appear below your text.

The following are the steps to add superscript or subscript to a PowerPoint document:

  • Create a Presentation instance and load a PowerPoint document using Presentation.loadFromFile() method.
  • Get the desired slide using Presentation.getSlides().get() method.
  • Add a shape to the slide using ISlide.getShapes().appendShape() method and set shape fill type and line color.
  • Access the text frame of the shape using IAutoShape.getTextFrame() method, then clear the default paragraph in the text frame using ITextFrameProperties.getParagraphs().clear() method.
  • Create a paragraph using ParagraphEx class, and add normal text to the paragraph using ParagraphEx.setText() method.
  • Create a portion with text using PortionEx class, and then apply superscript or subscript formatting to the text using PortionEx.getFormat().setScriptDistance(float value) method.
  • Set text color, font and font size for the normal text and the superscript or subscript text.
  • Append the paragraph to the text frame of the shape using ITextFrameProperties.getParagraphs().append() method.
  • Save the result document using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.*;
import com.spire.presentation.drawing.*;

import java.awt.*;

public class AddSuperscriptAndSubscript {
    public static void main(String []args) throws Exception {

        //Load a PowerPoint document
        Presentation presentation = new Presentation();
        presentation.loadFromFile("template.pptx");

        //Get the first slide
        ISlide slide = presentation.getSlides().get(0);

        //Add a shape to the slide
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle(150, 100, 200, 50));
        shape.getFill().setFillType(FillFormatType.NONE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //Access the text frame of the shape
        ITextFrameProperties textFrame = shape.getTextFrame();
        //Clear the default paragraph in the text frame
        textFrame.getParagraphs().clear();

        //Create a paragraph with normal text
        ParagraphEx para = new ParagraphEx();
        para.setText("E=mc");
        
        //Create a portion with superscript text
        PortionEx tr = new PortionEx("2");
        tr.getFormat().setScriptDistance(40);
        
        //Append the portion to the paragraph
        para.getTextRanges().append(tr);
        
        para.getTextRanges().append(new PortionEx("\n"));

        //Set text color, font and font size for the normal text
        tr = para.getTextRanges().get(0);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(new Color(128,0,128));
        tr.setFontHeight(20);
        tr.setLatinFont(new TextFont("Arial"));
        
        //Set text color and font for the superscript text
        tr = para.getTextRanges().get(1);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(Color.BLUE);
        tr.setLatinFont(new TextFont("Arial"));

        //Append the paragraph to the text frame of the shape
        textFrame.getParagraphs().append(para);
        
        //Create another paragraph with normal text
        para = new ParagraphEx();
        para.setText("X");
        
        //Create a portion with subscript text
        tr = new PortionEx("100");
        tr.getFormat().setScriptDistance(-25);
        
        //Append the portion to the paragraph
        para.getTextRanges().append(tr);

        //Set text color, font and font size for the normal text
        tr = para.getTextRanges().get(0);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(new Color(128,0,128));
        tr.setFontHeight(20);
        tr.setLatinFont(new TextFont("Arial"));
        
        //Set text color and font for the subscript text
        tr = para.getTextRanges().get(1);
        tr.getFill().setFillType(FillFormatType.SOLID);
        tr.getFill().getSolidColor().setColor(Color.BLUE);
        tr.setLatinFont(new TextFont("Arial"));

        //Append the paragraph to the text frame of the shape
        textFrame.getParagraphs().append(para);

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

Output:

Java: Add Superscript and Subscript to PowerPoint

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 6 of 148