A digital signature confirms that the document content originates from the signer and has not been changed. In this article, you will learn how to add a digital signature to your PowerPoint documents as well as remove all digital signatures using Spire.Presentation for Java.

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

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

Add a Digital Signature to PowerPoint

The following are the steps to add a digital signature to a PowerPoint document.

  • Create an object of Presentation class.
  • Load the sample PowerPoint document using Presentation.loadFromFile() method.
  • Add a digital signature to the document using Presentation.addDigitalSignature(String pfxPath, String password, String comments, java.util.Date signTime) method.
  • Save the result to a .pptx file using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

import java.util.Date;

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

        //Create a Presentation object
        Presentation presentation = new Presentation();

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

        //Add a digital signature
        String pfxPath = "C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx";
        String password = "e-iceblue";
        String comment = "Modification is not allowed";
        presentation.addDigitalSignature(pfxPath,password,comment,new Date());

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

Java: Add or Remove Digital Signatures in PowerPoint

Remove all Digital Signaters from PowerPoint

The following are steps to remove all digital signatures from a PowerPoint document.

  • Create an object of Presentation class.
  • Load the sample PowerPoint document using Presentation.loadFromFile() method.
  • Determine if the document contains digital signatures using Presentation.isDigitallySigned() method.
  • Remove all signatures using Presentation.removeAllDigitalSignatures() method.
  • Save the result to a .pptx file using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;

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

        //Create a Presentation object
        Presentation presentation = new Presentation();

        //Load the sample PowerPoint document
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddDigitalSignature.pptx");

        //Determine if the document is digitally signed
        if (presentation.isDigitallySigned() == true)
        {
            //Remove all digital signatures
            presentation.removeAllDigitalSignatures();
        }

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

Java: Add or Remove Digital Signatures in 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.

Wednesday, 29 September 2021 08:40

Java: Convert RTF to Word Doc/Docx and Vice Versa

RTF, short for Rich Text Format, is created by Microsoft in 1987 for the purpose of cross-platform document interchange. It is supported by many word processing applications, and the most popular one among them is Microsoft Word. In certain circumstances, you may need to convert an RTF document to Word Doc/Docx format or convert a Word Doc/Docx document to RTF. In this article, you will learn how to accomplish this task 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.

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

Convert RTF to Word Doc/Docx

The following are the steps to convert an RTF document to Word Doc/Docx using Spire.Doc for Java:

  • Create a Document instance.
  • Load an RTF document using Document.loadFromFile(String, FileFormat) method.
  • Save the RTF to Doc/Docx format using Document.saveToFile(String, FileFormat) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Load a RTF document
        document.loadFromFile("Input.rtf", FileFormat.Rtf);

        //Save the document to Doc
        document.saveToFile("toDoc.doc", FileFormat.Doc);

        //Save the document to Docx
        document.saveToFile("toDocx.docx", FileFormat.Docx_2013);
    }
}

Java: Convert RTF to Word Doc/Docx and Vice Versa

Convert Word Doc/Docx to RTF

The steps to convert a Word Doc/Docx document to RTF is very similar with that of the above example:

  • Create a Document instance.
  • Load a Doc or Docx document using Document.loadFromFile(String) method.
  • Save the Doc/Docx document to RTF using Document.saveToFile(String, FileFormat) method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

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

        //Load a Docx document
        document.loadFromFile("input.docx");

        //Load a Doc document
        //document.loadFromFile("sample.doc");

        //Save the document to RTF
        document.saveToFile("toRTF.rtf", FileFormat.Rtf);
    }
}

Java: Convert RTF to Word Doc/Docx 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.

Tuesday, 28 September 2021 02:49

Java: Accept or Reject Tracked Changes in Excel

An Excel document with Track Changes turned on will let you know what changes have been made to the document since the author has saved it. If you have the full authority over the document, you can accept or reject each revision. This article covers how to accept or reject all tracked changes at once 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.

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

Accept Tracked Changes in a Workbook

To determine whether a workbook has tracked changes, use Workbook.hasTrackedChanegs() method. If yes, you can accept all changes at once using Workbook.acceptAllTrackedchanges() method. The following are the steps to accept tracked changes in an Excel workbook.

  • Create a Workbook object.
  • Load the sample Excel document using Workbook.loadFromFile() method.
  • Determine if the workbook has tracked changes by Workbook.hasTrackedChanegs() method.
  • Accept tracked changes using Workbook.acceptAllTrackedChanges() method.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class AcceptTrackedChanges {

    public static void main(String[] args) {

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

        //Load the sample Excel file
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\Employees.xlsx");

        //Determine if the workbook has tracked changes
        if (wb.hasTrackedChanges())
        {
            //Accept tracked changes in the workbook
            wb.acceptAllTrackedChanges();
        }

        //Save to file
        wb.saveToFile("output/AcceptChanges.xlsx", FileFormat.Version2013);
    }
}

Java: Accept or Reject Tracked Changes in Excel

Reject Tracked Changes in a Workbook

If the tracked changes have been proven to exist in a workbook, you can reject them using Workbook.rejectAllTrackedChanges() method. The following are the steps to achieve this.

  • Create a Workbook object.
  • Load the sample Excel document using Workbook.loadFromFile() method.
  • Determine if the workbook has tracked changes by Workbook.hasTrackedChanegs() method.
  • Reject all tracked changes using Workbook.rejectAllTrackedChanges() method.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class RejectTrackedChanges {

    public static void main(String[] args) {

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

        //Load the sample Excel file
        wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\Employees.xlsx");

        //Determine if the workbook has tracked changes
        if (wb.hasTrackedChanges())
        {
            //Reject tracked changes in the workbook
            wb.rejectAllTrackedChanges();
        }

        //Save to file
        wb.saveToFile("output/RejectChanges.xlsx", FileFormat.Version2013);
    }
}

Java: Accept or Reject Tracked Changes in Excel

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.

LaTeX is a powerful tool to typeset mathematical equations. It supports plenty of mathematical symbols and notations to create mathematical equations, for instance, fractions, integrals and more.

Spire.Presentation API provides developers with the ability to create and add mathematical equations to PowerPoint shape using LaTeX code. The following steps demonstrate how to achieve this function using Spire.Presentation:

  • Create a Presentation instance.
  • Get the reference of a slide by using its index.
  • Use ShapeList.AppendShape method to add a shape to the first slide.
  • Use ParagraphCollection.AddParagraphFromLatexMathCode(string) method to create a mathematical equation from LaTeX code and add it to the shape.
  • Save the result document using Presentation.SaveToFile(string, FileFormat) method.

The following code shows how to add mathematical equations to PowerPoint in C#.

using Spire.Presentation;
using System.Drawing;

namespace MathEquations
{
    class Program
    {
        static void Main(string[] args)
        {            
            //The LaTeX codes
            string latexCode1 = @"x^{2} + \sqrt{x^{2}+1}=2";
            string latexCode2 = @"F(x) &= \int^a_b \frac{1}{3}x^3";
            string latexCode3 = @"\alpha + \beta  \geq \gamma";
            string latexCode4 = @"\overrightarrow{abc}";
            string latexCode5 = @"\begin{bmatrix} 1 & 0 & \cdots & 0\\ 1 & 0 & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 1 & 0 & 0 & 0 \end{bmatrix}";
            string latexCode6 = @"\log_a{b}";

            //Create a Presentation instance
            Presentation ppt = new Presentation();

            //Get the first slide by using its index
            ISlide slide = ppt.Slides[0];

            //Add a shape to the slide
            IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(30, 100, 200, 30));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode1);

            //Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(240, 100, 200, 40));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode2);

            //Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(30, 180, 200, 40));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode3);

            //Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(240, 180, 200, 40));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode4);

            //Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(30, 280, 200, 70));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode5);

            //Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(240, 280, 200, 40));
            shape.TextFrame.Paragraphs.Clear();
            //Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode6);

            for (int i = 0; i < slide.Shapes.Count; i++)
            {
                slide.Shapes[i].Fill.FillType = Spire.Presentation.Drawing.FillFormatType.None;
                slide.Shapes[i].Line.FillType = Spire.Presentation.Drawing.FillFormatType.None;
            }

            //Save the result document
            ppt.SaveToFile("MathEquations.pptx", FileFormat.Pptx2013);
        }
    }
}

The following code shows how to add mathematical equations to PowerPoint in VB.NET.

Imports Spire.Presentation
Imports System.Drawing

Namespace MathEquations
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'The LaTeX codes
            Dim latexCode1 As String = "x^{2} + \sqrt{x^{2}+1}=2"
            Dim latexCode2 As String = "F(x) &= \int^a_b \frac{1}{3}x^3"
            Dim latexCode3 As String = "\alpha + \beta  \geq \gamma"
            Dim latexCode4 As String = "\overrightarrow{abc}"
            Dim latexCode5 As String = "\begin{bmatrix} 1 & 0 & \cdots & 0\\ 1 & 0 & \cdots & 0\\ \vdots & \vdots & \ddots & \vdots\\ 1 & 0 & 0 & 0 \end{bmatrix}"
            Dim latexCode6 As String = "\log_a{b}"

            'Create a Presentation instance
            Dim ppt As Presentation = New Presentation()

            'Get the first slide by using its index
            Dim slide As ISlide = ppt.Slides(0)

            'Add a shape to the slide
            Dim shape As IAutoShape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(30, 100, 200, 30))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode1)

            'Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(240, 100, 200, 40))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode2)

            'Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(30, 180, 200, 40))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode3)

            'Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(240, 180, 200, 40))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode4)

            'Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(30, 280, 200, 70))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode5)

            'Add a shape to the slide
            shape = slide.Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(240, 280, 200, 40))
            shape.TextFrame.Paragraphs.Clear()
            'Add a math equation to the shape using the LaTeX code 
            shape.TextFrame.Paragraphs.AddParagraphFromLatexMathCode(latexCode6)

            For i As Integer = 0 To slide.Shapes.Count - 1
                slide.Shapes(i).Fill.FillType = Spire.Presentation.Drawing.FillFormatType.None
                slide.Shapes(i).Line.FillType = Spire.Presentation.Drawing.FillFormatType.None
            Next

            'Save the result document
            ppt.SaveToFile("MathEquations.pptx", FileFormat.Pptx2013)
        End Sub
    End Class
End Namespace

The following is the output document after adding mathematical equations:

Add Math Equations to PowerPoint using LaTeX Code in C#, VB.NET

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.

Tuesday, 27 September 2022 09:01

Java: Find and Remove Blank Pages from PDF

If you are going to print or share a PDF document, it’s better to check if there are blank pages in the document, because they will lead to a waste of paper and a less professional look for your document. However, it will take much time to look through every page to find the empty pages and then delete them. A better way to deal with this problem is to use Spire.PDF for Java. In this article, you will learn how to use Spire.PDF for Java to find and remove blank pages from PDF document easily by programming.

Install Spire.PDF for Java

First, you're required to add the Spire.Pdf.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.

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

Find and Delete Blank Pages from a PDF Document

Spire.PDF for Java provides a method PdfPageBase.isBlank() to detect if a PDF page is absolutely blank. But some pages that look blank actually contain white images, these pages won't be deemed as blank using the PdfPageBase.isBlank() method. Therefore, it is necessary create a custom method isBlankImage() to be used in conjunction with PdfPageBase.isBlank() method to detect blank and white but non-blank pages.

Note: This solution will convert PDF pages into images and detect if an image is blank. It is necessary to apply a license to remove the evaluation message in the converted images. Otherwise, this method won't work properly. If you do not have a license, contact sales@e-iceblue.com for a temporary one for evaluation purpose.

The detailed steps are as follows:

  • Create an object of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through the pages in the PDF document to detect if the pages are blank using PdfPageBase.isBlank() method.
  • For absolutely blank pages, delete them using PdfDocument.getPages().remove() method.
  • For pages that are not absolutely blank, save them as images using PdfDocument.saveAsImage() method, detect if the converted images are blank using custom method isBlankImage() and then remove the pages that are “balnk” using PdfDocument.getPages().remove().
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImageType;

import java.awt.*;
import java.awt.image.BufferedImage;

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

        //Create a PdfDocument class instance
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Sample.pdf");

        BufferedImage image;
        //Loop through pages in the PDF
        for(int i = pdf.getPages().getCount()-1; i>=0; i--)
        {
            PdfPageBase page = pdf.getPages().get(i);
            //Detect if a page is blank
            if(page.isBlank())
            {
                //Remove the absolutely blank page
                pdf.getPages().remove(page);
            }
            else
            {
                //Save PDF page as image
                image = pdf.saveAsImage(i, PdfImageType.Bitmap);

                //Detect if the converted image is blank
                if (isBlankImage(image))
                {
                    //Remove the page
                    pdf.getPages().remove(page);
                }
            }

        }

        //Save the result document
        pdf.saveToFile("RemoveBlankPages.pdf");
    }
    //Detect if an image is blank
    public static boolean isBlankImage(BufferedImage image)
    {
        BufferedImage bufferedImage = image;

        Color pixel;
        for (int i = 0; i < bufferedImage.getWidth(); i++)
        {
            for (int j = 0; j < bufferedImage.getHeight(); j++)
            {
                pixel = new Color(bufferedImage.getRGB(i, j));
                if (pixel.getRed() < 240 || pixel.getGreen() < 240 || pixel.getBlue() < 240)
                {
                    return false;
                }
            }
        }
        return true;
    }
}

Java: Find and Remove Blank Pages from PDF

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.

Monday, 06 September 2021 08:50

Set the Slide Size in PowerPoint in Java

SlideSize.setType() method is used to set or change the slide size to a predefined size like Widescreen 16x9, Overhead, A3, A4, Banner, B4, and B5. To customize the slide size, set the size type to custom, and then apply a customized width and height to slide using the SlideSize.setSize() method.

Set slide size to a predefined size

import com.spire.presentation.*;

import java.awt.geom.Rectangle2D;

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

        //Create a Presentation object
        Presentation presentation = new Presentation();

        //Set the slide size to Screen 16x9
        presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

        //Add a shape to the first slide
        IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(20, 50, 500, 50));
        shape.getTextFrame().setText("This example shows you how to set slide size to Widescreen 16X9.");

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

Set the Slide Size in PowerPoint in Java

Customize slide size

import com.spire.presentation.*;

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

public class CustomizeSlideSize {

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

        //Create a Presentation object
        Presentation presentation = new Presentation();

        //Set the slide size type to custom
        presentation.getSlideSize().setType(SlideSizeType.CUSTOM);

        //Set the slide size to a custom size 
        presentation.getSlideSize().setSize(new Dimension(800,400));

        //Add a shape to the first slide
        IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, new Rectangle2D.Float(20, 50, 500, 50));
        shape.getTextFrame().setText("This example shows you how to customize the slide size.");

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

Set the Slide Size in PowerPoint in Java

Spire.XLS for Java provides the getStyle() method and setStyle() method under the IXLSRange interface to get or set the style of a specific cell range. To copy formatting from one cell to another, get the style first and then apply it to another cell.

import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

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

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

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

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

        //Get the number of rows used
        int rowCount = sheet.getRows().length;
        
        //Loop through the rows
        for (int i = 1; i < rowCount + 1; i++)
        {
            //Copy the formatting from a certain cell to another
            sheet.getRange().get(String.format("C%d",i)).setStyle(sheet.getRange().get(String.format("A%d",i)).getStyle());
        }

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

Copy Formatting from One Cell Range to Another in Java

Spire.XLS for Java provides you with the ability to shrink text to fit in a cell by using the setShrinkToFit method of the CellStyleObject class. The setShrinkToFit method accepts the following parameter:

boolean: specify whether to shrink text to fit in a cell.

The following example shows how to shrink text to fit in a cell in Excel using Spire.XLS for Java.

import com.spire.xls.*;

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

        //Load the Excel file
        workbook.loadFromFile("Sample.xlsx");

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

        //Get the cell range to shrink text
        CellRange cell = sheet.getRange().get("B2:B3");

        //Enable “shrink to fit”
        cell.getCellStyle().setShrinkToFit(true);

        //Save the file
        workbook.saveToFile("ShrinkTextToFitInACell.xlsx", ExcelVersion.Version2013);
    }
}

The input Excel:

Shrink Text to Fit in a Cell in Excel in Java

The output Excel:

Shrink Text to Fit in a Cell in Excel in Java

Tuesday, 24 August 2021 06:51

Change Font Styles in PowerPoint in Java

This article demonstrates how to change font styles (font name, font size, font color, bold, italic and underlined) of an existing PowerPoint document by using Spire.Presentation for Java.

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 object
        Presentation presentation = new Presentation();

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

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

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

        //Get the second paragraph and make the text bold, italic and unlined
        paragraph = shape.getTextFrame().getParagraphs().get(1);
        textRange = paragraph.getFirstTextRange();
        textRange.getFormat().isBold(TriState.TRUE);
        textRange.getFormat().isItalic(TriState.TRUE);
        textRange.getFormat().setTextUnderlineType(TextUnderlineType.DASHED);

        //Get the third paragraph and change the font name and size
        paragraph = shape.getTextFrame().getParagraphs().get(2);
        textRange = paragraph.getFirstTextRange();
        textRange.getFormat().setLatinFont(new TextFont("Segoe Print"));
        textRange.getFormat().setFontHeight(22f);

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

Change Font Styles in PowerPoint in Java

Spire.Presentation for .NET provides you with the ability to replace text with regular expression using the ReplaceTextWithRegex method of IShape class. The ReplaceTextWithRegex method accepts the following parameters:

Regex: the regular expression to search text.

string: the text to replace with.

The following example demonstrates how to replace text with regular expression in a PowerPoint document using Spire.Presentation for .NET.

C#
using Spire.Presentation;
using System.Text.RegularExpressions;

namespace ReplaceTextWithRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation instance
            Presentation ppt = new Presentation();
            //Load a sample document
            ppt.LoadFromFile("Sample.pptx");

            //Get the first slide
            ISlide slide = ppt.Slides[0];

            //Replace "ABC" and the subsequent to the end of the line as "ABC DEF"
            Regex regex = new Regex("ABC.*");
            string newvalue = "ABC DEF";
            foreach (IShape shape in slide.Shapes)
            {
                shape.ReplaceTextWithRegex(regex, newvalue);
            }

            //Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013);
        }
    }
}
VB.NET
Imports Spire.Presentation
Imports System.Text.RegularExpressions

Namespace ReplaceTextWithRegex
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Presentation instance
            Dim ppt As Presentation = New Presentation()
            'Load the sample document
            ppt.LoadFromFile("Sample.pptx")

            'Get the first slide
            Dim slide As ISlide = ppt.Slides(0)

            'Replace "ABC" and the subsequent to the end of the line as "ABC DEF"
            Dim regex As Regex = New Regex("ABC.*")
            Dim newvalue As String = "ABC DEF"

            For Each shape As IShape In slide.Shapes
                shape.ReplaceTextWithRegex(regex, newvalue)
            Next

            'Save the result document
            ppt.SaveToFile("ReplaceTextWithRegex.pptx", FileFormat.Pptx2013)
        End Sub
    End Class
End Namespace

The input PowerPoint document:

Replace Text with Regular Expression (Regex) in PowerPoint in C#, VB.NET

The output PowerPoint document:

Replace Text with Regular Expression (Regex) in PowerPoint in C#, VB.NET