Spire.PDF supports to convert PDF to HTML and save the resulted HTML file to stream by calling the method PdfDocument.saveToStream(). When converting PDF to HTML, it also supports to set the convert options with embedded SVG/Image on the resulted HTML file. This article will demonstrate how to convert the PDF pages to HTML with embedded SVG and embedded image.

import com.spire.pdf.*;
import java.io.*;

public class PDFtoHTML {
    public static void main(String[] args) throws FileNotFoundException {

        String inputFile = "Sample.pdf";
        String outputFile = "output/toHTML_out.html";

        //Load the sample document file
        PdfDocument pdf = new PdfDocument();

        pdf .loadFromFile(inputFile);

        //Set the bool useEmbeddedSvg and useEmbeddedImg as true 
        pdf .getConvertOptions().setPdfToHtmlOptions(true,true);

        //Save to stream
        File outFile = new File(outputFile);
        OutputStream outputStream = new FileOutputStream(outFile);
        pdf.saveToStream(outputStream, FileFormat.HTML);
        pdf.close();

    }
}

This article demonstrates how to highlight the highest and lowest value in a cell rang through conditional formatting. You can also highlight the top 5 or bottom 5 values by passing 5 to setRank() method in the code snippet below.

import com.spire.xls.*;

import java.awt.*;

public class HighlightTopBottom {

    public static void main(String[] args) {

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

        //Load the sample Excel file
        workbook.loadFromFile("G:\\360MoveData\\Users\\Administrator\\Desktop\\sales report.xlsx");

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

        //Apply conditional formatting to range "B2:E5" to highlight the highest value
        ConditionalFormatWrapper format1 = sheet.getCellRange("B2:E5").getConditionalFormats().addCondition();
        format1.setFormatType(ConditionalFormatType.TopBottom);
        format1.getTopBottom().setType(TopBottomType.Top);
        format1.getTopBottom().setRank(1);
        format1.setBackColor(Color.red);

        //Apply conditional formatting to range "B2:E5" to highlight the lowest value
        ConditionalFormatWrapper format2 = sheet.getCellRange("B2:E5").getConditionalFormats().addCondition();
        format2.setFormatType(ConditionalFormatType.TopBottom);
        format2.getTopBottom().setType(TopBottomType.Bottom);
        format2.getTopBottom().setRank(1);
        format2.setBackColor(Color.yellow);

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

Highlight Highest and Lowest Value in Excel in Java

PDF annotations help users make comments and mark up text. They are used in many situations where PDF files are involved, such as giving feedback on reports, making explanations for difficult words, and taking notes while reading articles. Users can add many types of annotations to PDF documents, such as pop-up, text box, link, and line annotations. This article will show how to add pop-up and text box annotations in PDF documents using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, 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>
    

Add a Pop-Up Annotation to a PDF Document

Pop-up annotations are displayed as buttons in PDF documents. They do not show annotation text on PDF pages, but only in the Comments widget of PDF viewers. The detailed steps for adding a pop-up annotation to a PDF document are as follows.

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page of the document using PdfDocument.getPages().get() method.
  • Find the text to annotate using PdfPageBase.findText().getFinds() method.
  • Create a PdfPopupAnnotation object and set the text and position of the annotation.
  • Set the style and color of the annotation using methods under PdfPopupAnnotation class.
  • Add the annotation to the page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
import com.spire.pdf.general.find.PdfTextFind;

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

        //Create an instance of PdfDocument class
        PdfDocument pdf = new PdfDocument();

        //Load a PDF Document
        pdf.loadFromFile("Born That Way.pdf");

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

        //Find the text to add annotation
        PdfTextFind[] find = page.findText("developmental scientists").getFinds();

        //Create a PdfPopupAnnotation object and set the text and position of the annotation
        String text = "Developmental scientists are researchers who explores and summarizes the growth process of children.";
        float a = (float)(find[0].getPosition().getX() + find[0].getSize().getWidth() - 20);
        float b = (float)(find[0].getPosition().getY());
        Rectangle2D rectangle2D = new Rectangle.Float();
        rectangle2D.setFrame(new Point2D.Double(a,b),new Dimension());
        PdfPopupAnnotation annotation = new PdfPopupAnnotation(rectangle2D, text);

        //Set the text, position, and style of the annotation
        annotation.setIcon(PdfPopupIcon.Note);
        annotation.setColor(new PdfRGBColor(Color.red));

        //Add the annotation to the page
        page.getAnnotationsWidget().add(annotation);

        //Save the document
        pdf.saveToFile("PopUpAnnotation.pdf");
        pdf.close();
    }
}

Java: Add Pop-Up and Text Box Annotations to PDF

Add a Text Box Annotation to a PDF Document

Pop-up annotations are displayed as buttons on PDF pages. The annotation text of pop-up annotations is not displayed directly on the page, but it will appear on the page when the mouse cursor is moved to the button. Readers can also directly open the "Comments" interface to view pop-up annotations directly. The detailed steps to add a text box annotation to a PDF document are as follows.

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Find the text to annotate using PdfPageBase.findText.getFinds() method.
  • Create a PdfFreeTextAnnotation object and set the position of the annotation.
  • Set the text, font, text color, and text box format of the annotation using methods under PdfFreeTextAnnotation class.
  • Add the annotation to the page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
import com.spire.pdf.general.find.PdfTextFind;
public class PDFTextBoxAnnotation {
    public static void main(String[] args)  {

        //Create an instance of PdfDocument class 
        PdfDocument doc = new PdfDocument();

        //Load a PDF document
        doc.loadFromFile("Born That Way.pdf");

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

        //Find the text to annotate
        PdfTextFind[] find = page.findText("developmental scientists").getFinds();

        //Create a PdfFreeTextAnnotation object and set the position of the annotation
        float x = (float)(find[0].getPosition().getX() + find[0].getSize().getWidth());
        float y = (float)(find[0].getPosition().getY() + find[0].getSize().getHeight());
        Rectangle2D.Float rect = new Rectangle2D.Float(x, y, 150, 30);
        PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);

        //Set the text, font, text color, and text box format of the annotation
        textAnnotation.setMarkupText("Scientists who research the growth process of children.");
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",0, 11));
        textAnnotation.setFont(font);
        PdfAnnotationBorder border = new PdfAnnotationBorder(0.3f);
        textAnnotation.setBorder(border);
        textAnnotation.setBorderColor(new PdfRGBColor(Color.pink));
        textAnnotation.setColor(new PdfRGBColor(Color.YELLOW));
        textAnnotation.setOpacity(0.7f);
        textAnnotation.setTextMarkupColor(new PdfRGBColor(Color.black));

        //Add the annotation to the page
        page.getAnnotationsWidget().add(textAnnotation);

        //Save the document
        doc.saveToFile("TextBoxAnnotation.pdf");
        doc.close();
    }
}

Java: Add Pop-Up and Text Box Annotations to 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.

This article demonstrates how to highlight the duplicate and unique values in a selected range through conditional formatting using Spire.XLS for Java.

import com.spire.xls.*;

import java.awt.*;

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

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

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

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

        //Use conditional formatting to highlight duplicate values in the range "A2:A11" with red 
        ConditionalFormatWrapper format1 = sheet.getCellRange("A2:A11").getConditionalFormats().addCondition();
        format1.setFormatType(ConditionalFormatType.DuplicateValues);
        format1.setBackColor(Color.red);
        
        //Use conditional formatting to highlight unique values in the range "A2:A11" with yellow
        ConditionalFormatWrapper format2 = sheet.getCellRange("A2:A11").getConditionalFormats().addCondition();
        format2.setFormatType(ConditionalFormatType.UniqueValues);
        format2.setBackColor(Color.yellow);

        //Save the document
        workbook.saveToFile("HighlightDuplicates.xlsx", ExcelVersion.Version2016);
    }
}

Highlight Dulicate and Unique Values in Excel in Java

A watermark in a Word document is a semitransparent text or image background that is used to highlight something important about the document, such as using text watermark to remind the reader that the document is confidential or just a draft and declaring copyright through a picture of your company. Sometimes watermarks can affect the readability of documents, and if we want to remove them, Spire.Doc for Java will be of great help. This article shows the detailed steps of removing watermarks from Word documents with the help of Spire.Doc for Java.

Install Spire.Doc for Java

First, 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>12.4.1</version>
    </dependency>
</dependencies>
    

Remove the Watermark from a Word Document

The detailed steps of removing a watermark are as follows:

  • Create an object of Document.
  • Load a Word document from disk using Document.loadFromFile() method.
  • Set the watermark to null to remove the watermark using Document.setWatermark() method.
  • Save the Word document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;

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


        //Create an object of Document
        Document document = new Document();

        //Load a Word document from disk
        document.loadFromFile("D:/testp/test.docx");

        //Set the watermark value to null to remove the watermark
        document.setWatermark(null);

        //Save the Word document
        String output = "D:/javaOutput/removeWatermark.docx";
        document.saveToFile(output, FileFormat.Docx_2013);
    }
}

Java: Remove Watermarks from Word Documents

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, 06 July 2022 08:37

Java: Create a Pivot Table in Excel

Pivot table is a powerful tool in Excel that supports categorizing, sorting, filtering, and summarizing data. It is often used in situations where data needs to be aggregated and analyzed for reporting. This article will demonstrate how to programmatically create a pivot table in Excel using Spire.XLS for Java.

Install Spire.XLS for Java

First, 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>
    

Create a Pivot Table in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Select the data source range using Worksheet.getCellRange() method, and then create a PivotCache to save the data information using Workbook.getPivotCaches().add(CellRange range) method.
  • Add a pivot table to the specified worksheet and set the location and cache of it using Worksheet.getPivotTables().add(java.lang.String name, CellRange location, PivotCache cache) method.
  • Define row labels of the pivot table and then add fields to the data area to calculate data using PivotTable.getDataFields().add(IPivotField iField, java.lang.String name, SubtotalTypes subtotal) method.
  • Set the pivot table style using PivotTable.setBuiltInStyle(PivotBuiltInStyles builtInStyle) method.
  • Save the result document using Workbook.saveToFile() method.
  • Java
import com.spire.xls.*;

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

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

        //Load a sample Excel document
        workbook.loadFromFile("E:\\Files\\sample.xlsx");

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

        //Select the data source range
        CellRange dataRange = sheet.getCellRange("B1:F11");
        PivotCache cache = workbook.getPivotCaches().add(dataRange);

        //Add a PivotTable to the worksheet and set the location and cache of it
        PivotTable pt = sheet.getPivotTables().add("Pivot Table", sheet.getCellRange("H3"), cache);

        //Define row labels
        PivotField pf=null;
        if (pt.getPivotFields().get("Country") instanceof PivotField){
            pf= (PivotField) pt.getPivotFields().get("Country");
        }
        pf.setAxis(AxisTypes.Row);

        PivotField pf2 =null;
        if (pt.getPivotFields().get("Product") instanceof PivotField){
            pf2= (PivotField) pt.getPivotFields().get("Product");
        }
        pf2.setAxis(AxisTypes.Row);

        //Add data fields to calculate data
        pt.getDataFields().add(pt.getPivotFields().get("Quantity"), "SUM of Quantity", SubtotalTypes.Sum);
        pt.getDataFields().add(pt.getPivotFields().get("Total Amount"), "SUM of Total Amount", SubtotalTypes.Sum);

        //Set pivot table style
        pt.setBuiltInStyle(PivotBuiltInStyles.PivotStyleMedium10);

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

Java: Create a Pivot Table 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.

In Microsoft Excel, the blank rows or columns usually indicate the boundaries of data ranges. Therefore, if a blank row or blank column appears in the wrong place will prevent Excel from recognizing the data range correctly when applying some built-in features such as sorting, removing duplicates and subtotals. In such a case, you can delete the blank rows or columns to create a tidy dataset that fit for further processing and analysis. This article will introduce how to programmatically delete blank rows and columns in an Excel document 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>
    

Delete Blank Rows and Columns in Excel

The detailed steps are as follows.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Get a specified worksheet using Workbook.getWorksheets().get() method.
  • Loop through all used rows in the specified worksheet and determine whether the row is blank using XlsRange.isBlank() method.
  • Delete the blank rows using Worksheet.deleteRow() method.
  • Loop through all used columns in the specified worksheet and determine whether the column is blank using XlsRange.isBlank() method.
  • Delete the blank columns using Worksheet.deleteColumn() method.
  • Save the result 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 DeleteBlankRowsAndColumns {

    public static void main(String[] args) {

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

        //Load a sample Excel document
        wb.loadFromFile("sample.xlsx ");

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

        //Loop through all used rows
        for (int i = sheet.getLastRow(); i >= 1; i--)
        {
            //Detect if a row is blank
            if (sheet.getRows()[i-1].isBlank())
            {
                //Remove blank rows
                sheet.deleteRow(i);
            }
        }

        //Loop through all used columns
        for (int j = sheet.getLastColumn(); j >= 1; j--)
        {
            //Detect if a column is blank
            if (sheet.getColumns()[j-1].isBlank())
            {
                //Remove blank columns
                sheet.deleteColumn(j);
            }
        }

        //Save the document
        wb.saveToFile("DeleteBlankRowsAndColumns.xlsx", ExcelVersion.Version2016);
    }
}

Java: Delete Blank Rows and Columns 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.

In this article, we will introduce how to set style and border of a Word table using Spire.Doc for Java.

The following screenshot shows the table before setting style and border:

Set Style and Border of Table in Word in Java

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.Table;
import com.spire.doc.documents.BorderStyle;
import com.spire.doc.documents.DefaultTableStyle;

import java.awt.*;

public class SetTableStyleAndBorder {
    public static void main(String[] args){
        //create a Document instance
        Document document = new Document();
        //Load the Word document
        document.loadFromFile("tableSample.docx");

        Section section = document.getSections().get(0);

        //get the first table
        Table table = section.getTables().get(0);

        //apply the table style
        table.applyStyle(DefaultTableStyle.Colorful_List);

        //set right border of table
        table.getTableFormat().getBorders().getRight().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getRight().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getRight().setColor(Color.RED);

        //set top border of table
        table.getTableFormat().getBorders().getTop().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getTop().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getTop().setColor(Color.GREEN);

        //set left border of table
        table.getTableFormat().getBorders().getLeft().setBorderType(BorderStyle.Hairline);
        table.getTableFormat().getBorders().getLeft().setLineWidth(1.0F);
        table.getTableFormat().getBorders().getLeft().setColor(Color.YELLOW);

        //set bottom border of table
        table.getTableFormat().getBorders().getBottom().setBorderType(BorderStyle.Dot_Dash);

        //set vertical and horizontal border
        table.getTableFormat().getBorders().getVertical().setBorderType(BorderStyle.Dot);
        table.getTableFormat().getBorders().getHorizontal().setBorderType(BorderStyle.None);
        table.getTableFormat().getBorders().getVertical().setColor(Color.ORANGE);

        //save the result file
        document.saveToFile("setTableStyleAndBorder.docx", FileFormat.Docx_2013);
    }
}

The following screenshot shows the table after setting style and border:

Set Style and Border of Table in Word in Java

By default, an animation plays only one time and does not repeat. However, we can make the animation to play more than once by setting the repeat type of it. This article demonstrates how to accomplish this function using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.animation.AnimationEffect;

public class RepeatAnimation {
    public static void main(String[] args) throws Exception {
        //Create a Presentation instance
        Presentation ppt = new Presentation();
        //Load a PowerPoint document
        ppt.loadFromFile("Animation.pptx");
        
        //Get the first slide
        ISlide slide = ppt.getSlides().get(0);
        
        //Get the first animation effect on the slide
        AnimationEffect animation = slide.getTimeline().getMainSequence().get(0);
        //Set the animation effect to repeat forever until the end of slide.
        animation.getTiming().setAnimationRepeatType(AnimationRepeatType.UtilEndOfSlide);

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

Output:

How to Repeat an Animation in PowerPoint in Java

This article demonstrates how to insert subscript and superscript in an Excel document using Spire.XLS for Java.

import com.spire.xls.*;

import java.awt.*;

public class InsertSubscriptSuperscript {

    public static void main(String[] args) {

        //Create a Workbook instance
        Workbook workbook = new Workbook();
        
        //Get the first worksheet
        Worksheet sheet = workbook.getWorksheets().get(0);

        //Insert text to B2 and D2
        sheet.getCellRange("B2").setText("This is an example of Subscript:");
        sheet.getCellRange("D2").setText("This is an example of Superscript:");

        //Insert text to B3 and apply subscript effect
        CellRange range = sheet.getCellRange("B3");
        range.getRichText().setText("R100-0.06");
        ExcelFont font = workbook.createFont();
        font.isSubscript(true);
        font.setColor(Color.red);
        range.getRichText().setFont(4, 8, font);

        //Insert text to D3 and apply superscript effect
        range = sheet.getCellRange("D3");
        range.getRichText().setText("a2 + b2 = c2");
        font = workbook.createFont();
        font.isSuperscript(true);
        range.getRichText().setFont(1, 1, font);
        range.getRichText().setFont(6, 6, font);
        range.getRichText().setFont(11, 11, font);

        //Auto fit column width
        sheet.getAllocatedRange().autoFitColumns();
        
        //Save the docuemnt
        workbook.saveToFile("output/SubSuperScript.xlsx", ExcelVersion.Version2016);
    }
}

Insert Subscript and Superscript in Excel in Java