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

Thursday, 03 August 2023 08:50

Java: Change the Slide Size in PowerPoint

The slide size is one of the important aspects of the visual design of PowerPoint presentations. It influences the aspect ratio and dimensions of the presentation and can have a significant impact on the overall appearance and atmosphere of the presentation. If the default slide size does not meet the visual design requirements or does not match the size of the screen showing the presentation, it is necessary to change the size of the slides to another preset size or customize a slide size. This article will demonstrate how to change the slide size of PowerPoint presentations through Java programs 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.

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

Change the Slide Size to a Preset Size

Spire.Presentation for Java provides the Presentation.getSlideSize().setType() method to change the slide size to a preset size. The detailed steps are as follows:

  • Create an object of Presentation class.
  • Load a PowerPoint presentation using Presentation.loadFromFile() method.
  • Change the slide type of the presentation using Presentation.getSlideSize().setType() method.
  • Save the presentation using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideSizeType;

public class changeSlideSizePreset {
    public static void main(String[] args) throws Exception {
        //Create an object of Presentation class
        Presentation pt = new Presentation();

        //Load a presentation file
        pt.loadFromFile("Sample.pptx");

        //Change the slide size of the presentation to A4
        pt.getSlideSize().setType(SlideSizeType.A4);

        //Save the presentation file
        pt.saveToFile("A4Size.pptx", FileFormat.AUTO);
        pt.dispose();
    }
}

Java: Change the Slide Size in PowerPoint

Change the Slide Size to a Custom Size

Customizing the size of slides requires changing the slide size type to custom. After that, the Presentation.getSlideSize().setSize() method can be used to customize the slide size. The detailed steps are as follows:

  • Create an object of Presentation class.
  • Load a PowerPoint presentation using Presentation.loadFromFile() method.
  • Change the slide size type to custom using Presentation.getSlideSize().setType() method.
  • Customize the slide size using Presentation.getSlideSize().setSize() method.
  • Save the presentation using Presentation.saveToFile() method.
  • Java
import com.spire.presentation.FileFormat;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideSize;
import com.spire.presentation.SlideSizeType;

import java.awt.*;

public class changeSlideSizeCustom {
    public static void main(String[] args) throws Exception {
        //Create an object of Presentation class
        Presentation pt = new Presentation();

        //Load a PowerPoint presentation
        pt.loadFromFile("Sample.pptx");

        //Change the slide size type to custom
        pt.getSlideSize().setType(SlideSizeType.CUSTOM);

        //Set the slide size
        pt.getSlideSize().setSize(new Dimension(600, 600));

        //Save the presentation file
        pt.saveToFile("CustomSize.pptx", FileFormat.AUTO);
        pt.dispose();
    }
}

Java: Change the Slide Size 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.

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

Wednesday, 18 August 2021 06:16

Add Multiline Watermarks to PowerPoint in Java

This article demonstrates how to add multiline watermarks to a PowerPoint slide using Spire.Presentation for Java. To add watermarks to all slides, use one more for loop outside the two for loops in the following code snippet.

import com.spire.pdf.graphics.PdfTrueTypeFont;
import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

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

public class AddMultilineWatermarks {

    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\\Spire.Presentation.pptx");

        //Specify watermark text
        String watermarkText = "E-iceblue";

        //Get the size of the watermark text
        Font font = new java.awt.Font("Arial", java.awt.Font.BOLD, 20);
        PdfTrueTypeFont trueTypeFont = new PdfTrueTypeFont(font);
        Dimension2D strSize = trueTypeFont.measureString(watermarkText);

        //Initialize x and y coordinate
        float x = 30;
        float y = 80;

        for (int rowNum = 0; rowNum < 4; rowNum++) {
            for (int colNum = 0; colNum < 5; colNum++) {

                //Add a rectangle shape
                Rectangle2D rect = new Rectangle2D.Float(x, y, (float) strSize.getWidth() + 10, (float) strSize.getHeight());
                IAutoShape shape = presentation.getSlides().get(0).getShapes().appendShape(ShapeType.RECTANGLE, rect);

                //Set the style of the shape
                shape.getFill().setFillType(FillFormatType.NONE);
                shape.getShapeStyle().getLineColor().setColor(new Color(1, 1, 1, 0));
                shape.setRotation(-45);
                shape.getLocking().setSelectionProtection(true);
                shape.getLine().setFillType(FillFormatType.NONE);

                //Add watermark text to the shape
                shape.getTextFrame().setText(watermarkText);
                PortionEx textRange = shape.getTextFrame().getTextRange();

                //Set the style of the text range
                textRange.getFill().setFillType(FillFormatType.SOLID);
                textRange.getFill().getSolidColor().setColor(Color.pink);
                textRange.setLatinFont(new TextFont(trueTypeFont.getName()));
                textRange.setFontMinSize(trueTypeFont.getSize());

                x += (100 + strSize.getWidth());

            }
            x = 30;
            y += (100 + strSize.getHeight());
        }

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

Add Multiline Watermarks to PowerPoint in Java

Thursday, 06 January 2022 06:29

Java: Wrap or Unwrap Text in Excel Cells

In the process of manipulating Excel worksheets, sometimes you may encounter the situation where the text in a cell is so long that some of it is hidden. At this time, it’s recommended to wrap the extra-long text into multiple lines so you can see it all. This article will demonstrate how to programmatically wrap or unwrap text in Excel cells 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>14.4.1</version>
    </dependency>
</dependencies>
    

Wrap or Unwrap Text in Excel cells

Spire.XLS for Java supports wrapping or unwrapping text in Excel cells using the setWrapText() method provided by the IStyle interface. Below are detailed steps for your reference.

  • 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.
  • Get a specific cell of the worksheet using Worksheet.getRange().get() method.
  • Get the style of the specified cell using XlsRange.getStyle() method and set whether the text is wrapped or not using setWrapText() method provided by IStyle interface.
  • Save the document to another file using Workbook.saveToFile() method.
  • Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class WrapOrUnwrapText {
    public static void main(String[] args) {
        //Create a Workbook instance
        Workbook workbook = new Workbook();
        //Load a sample Excel document
        workbook.loadFromFile("C:\\Users\\Test1\\Desktop\\sample.xlsx");

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

        //Wrap text in the cell "D8"
        sheet.getRange().get("D8").getStyle().setWrapText(true);

        //Unwrap text in the cell "D6"
        sheet.getRange().get("D6").getStyle().setWrapText(false);

        //Save the document to another file
        workbook.saveToFile("output/WrapOrUnwrapText.xlsx", ExcelVersion.Version2013);
    }
}

Java: Wrap or Unwrap Text in Excel Cells

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, 10 August 2021 07:43

Embed a Zip File in PowerPoint in Java

This article shows you how to embed a zip file as an OLE object in a PowerPoint document using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;

public class InsertZip {

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

        //Create a Presentation object
        Presentation presentation = new Presentation();
        presentation.getSlideSize().setType(SlideSizeType.SCREEN_16_X_9);

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

        //Load a zip file and convert it to a byte[] object
        String filePath = "C:\\Users\\Administrator\\Desktop\\sample.zip";
        File zipFile = new File(filePath);
        FileInputStream inputStream = new FileInputStream(zipFile);
        byte[] data = new byte[(int) zipFile.length()];
        inputStream.read(data, 0, data.length);

        //Load an image file as the display icon
        File file = new File("C:\\Users\\Administrator\\Desktop\\winrar-icon.png");
        BufferedImage image = ImageIO.read(file);
        IImageData oleImage = presentation.getImages().append(image);
        
        //Insert the zip file as an OLE object to the first slide
        Rectangle2D rect = new Rectangle2D.Float(60, 60, image.getWidth(), image.getHeight());
        IOleObject oleObject = slide.getShapes().appendOleObject("zip", data, rect);
        oleObject.getSubstituteImagePictureFillFormat().getPicture().setEmbedImage(oleImage);
        oleObject.setProgId("Package");
        
        //Save to file
        presentation.saveToFile("output/InsertZip.pptx", FileFormat.PPTX_2013);
    }
}

 

Embed a Zip File in PowerPoint in Java

This article demonstrates how to convert shapes and SmartArt graphics in Excel to Image in C# using Spire.XLS for .NET.

The input Excel file:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET

C#
using Spire.Xls;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;

namespace Convert_Shapes_and_SmartArt_to_Image
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a SaveShapeTypeOption object
            SaveShapeTypeOption shapelist = new SaveShapeTypeOption();
            //Save shapes and SmartArt graphics in the worksheet to images
            List images = sheet.SaveShapesToImage(shapelist);

            //Save images to file
            int index = 0;
            foreach (Image img in images)
            {
                img.Save("Image/" + "toImage" + index + ".Png", ImageFormat.Png);
                index++;
            }
        }
    }
}
VB.NET
Imports Spire.Xls
Imports System.Collections.Generic
Imports System.Drawing.Imaging

Namespace Convert_Shapes_and_SmartArt_to_Image
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Create a Workbook object
            Dim workbook As Workbook = New Workbook()
            'Load the Excel file
            workbook.LoadFromFile("Sample.xlsx")

            'Get the first worksheet
            Dim sheet As Worksheet = workbook.Worksheets(0)

            'Create a SaveShapeTypeOption object
            Dim shapelist As SaveShapeTypeOption = New SaveShapeTypeOption()
            'Save shapes and SmartArt graphics in the worksheet to images
            Dim images As List(Of Bitmap) = sheet.SaveShapesToImage(shapelist)

            'Save images to file
            Dim index As Integer = 0

            For Each img As Image In images
                img.Save("Image/" & "toImage" & index & ".Png", ImageFormat.Png)
                index += 1
            Next
        End Sub
    End Class
End Namespace

Converted images:

Convert Shapes and SmartArt in Excel to Image in C#, VB.NET