Spire.Office Knowledgebase Page 18 | E-iceblue

When dealing with Excel worksheets, there are times when the existing layout needs to be adjusted. Inserting rows and columns serves as an effective solution for such scenarios. It allows users to seamlessly expand their data, add new information, or re-structure the spreadsheet in a way that optimizes both data entry and analysis. This action not only makes room for more content, but also enhances the overall organization and readability of the data. In this article, you will learn how to insert rows and columns in Excel in React using Spire.XLS for JavaScript.

Install Spire.XLS for JavaScript

To get started with inserting or deleting picture in Excel in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:

npm i spire.xls 

After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.

For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project

Insert a Row and a Column in Excel in JavaScript

Using Spire.XLS for JavaScript, a blank row or a blank column can be inserted into an Excel worksheet via the Worksheet.InsertRow(rowIndex) or Worksheet.InsertColumn(columnIndex) method. The following are the main steps.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert a row into the worksheet using the Worksheet.InsertRow(rowIndex) method.
  • Insert a column into the worksheet using the Worksheet.InsertColumn(columnIndex) method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to insert a row and a column 
  const InsertRowColumn = async () => {
    if (wasmModule) {  
      // Load the input file into the virtual file system (VFS)
      const inputFileName='input1.xlsx';
      await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}/`);

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

      // Load the Excel file
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let worksheet = workbook.Worksheets.get(0);
        
      // Insert a blank row as the 5th row in the worksheet
      worksheet.InsertRow(5);
        
      // Insert a blank column as the 4th column in the worksheet
      worksheet.InsertColumn(4);
        
      //Save result file
      const outputFileName = 'InsertRowAndColumn.xlsx';
      workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});

      //Dispose resources
      workbook.Dispose();

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };
  
  return (
  <div style={{ textAlign: 'center', height: '300px' }}>
    <h1>Insert Row and Column in Excel Using JavaScript in React</h1>
    <button onClick={InsertRowColumn} disabled={!wasmModule}>
      Process
      </button>
      </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click the "Process" button to insert rows and columns in Excel:

Run the code to launch the React app at localhost:3000

Below is the result file:

Insert a blank row and a blank column in an Excel worksheet

Insert Multiple Rows and Columns in Excel in JavaScript

To insert multiple rows or columns, use the Worksheet.InsertRow(rowIndex: number, rowCount: number) or Worksheet.InsertColumn(columnIndex: number, columnCount: number) methods. The first parameter represents the index at which the new row/column will be inserted, and the second argument represents the number of rows/columns to be inserted. The following are the main steps.

  • Create a Workbook object using the wasmModule.Workbook.Create() method.
  • Load an Excel file using the Workbook.LoadFromFile() method.
  • Get a specific worksheet using the Workbook.Worksheets.get() method.
  • Insert multiple rows into the worksheet using the Worksheet.InsertRow(rowIndex: number, rowCount: number) method.
  • Insert multiple columns into the worksheet using Worksheet.InsertColumn(columnIndex: number, columnCount: number) method.
  • Save the result file using the Workbook.SaveToFile() method.
  • JavaScript
import React, { useState, useEffect } from 'react';

function App() {

  // State to hold the loaded WASM module
  const [wasmModule, setWasmModule] = useState(null);

  // useEffect hook to load the WASM module when the component mounts
  useEffect(() => {
    const loadWasm = async () => {
      try {

        // Access the Module and spirexls from the global window object
        const { Module, spirexls } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirexls);
        };
      } catch (err) {

        // Log any errors that occur during loading
        console.error('Failed to load WASM module:', err);
      }
    };

    // Create a script element to load the WASM JavaScript file
    const script = document.createElement('script');
    script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
    script.onload = loadWasm;

    // Append the script to the document body
    document.body.appendChild(script);

    // Cleanup function to remove the script when the component unmounts
    return () => {
      document.body.removeChild(script);
    };
  }, []); 

  // Function to insert multiple rows and columns 
  const InsertRowsColumns = async () => {
    if (wasmModule) {  
      // Load the input file into the virtual file system (VFS)
      const inputFileName='input1.xlsx';
      await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}/`);

      // Create a new workbook
      const workbook = wasmModule.Workbook.Create();

      // Load the Excel file
      workbook.LoadFromFile({fileName: inputFileName});

      // Get the first worksheet
      let worksheet = workbook.Worksheets.get(0);
        
      // Insert three blank rows into the worksheet
      worksheet.InsertRow({rowIndex:5, rowCount:3});
        
      // Insert two blank columns into the worksheet
      worksheet.InsertColumn({columnIndex:4, columnCount:2});

      //Save result file
      const outputFileName = 'InsertRowsAndColumns.xlsx';
      workbook.SaveToFile({fileName: outputFileName, version:wasmModule.ExcelVersion.Version2016});

      //Dispose resources
      workbook.Dispose();

      // Read the saved file and convert it to a Blob object
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
      const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    
      // Create a URL for the Blob and initiate the download
      const url = URL.createObjectURL(modifiedFile);
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
    }
  };
  
  return (
  <div style={{ textAlign: 'center', height: '300px' }}>
    <h1>Insert Rows and Columns in Excel Using JavaScript in React</h1>
    <button onClick={InsertRowsColumns} disabled={!wasmModule}>
      Process
      </button>
      </div>
  );
}

export default App;

Insert three blank rows and two blank columns in an Excel worksheet

Get a Free License

To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.

Java: Crop PDF Pages

2025-04-03 01:21:47 Written by Koohji

When working with PDF files, you may need to adjust the page size to emphasize important content, remove extra white space, or fit specific printing and display requirements. Cropping PDF pages helps streamline the document layout, making the content more readable and well-organized. It also reduces file size, improving both accessibility and sharing. Additionally, precise cropping enhances the document's visual appeal, giving it a more polished and professional look. This article will demonstrate how to crop PDF pages in Java using the Spire.PDF for Java library.

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

Crop a PDF Page in Java

Spire.PDF for Java provides the PdfPageBase.setCropBox(Rectangle2D rect) method to set the crop area for a PDF page. The detailed steps are as follows.

  • Create an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() method.
  • Get a specific page from the PDF using the PdfDocument.getPages().get(int pageIndex) method.
  • Create an instance of the Rectangle2D class to define the crop area.
  • Use the PdfPageBase.setCropBox(Rectangle2D rect) method to set the crop area for the page.
  • Save the cropped PDF using the PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import java.awt.geom.Rectangle2D;

public class CropPdfPage {
    public static void main(String[] args) {
        // Create an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        // Load the PDF file
        pdf.loadFromFile("example.pdf");

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

        // Define the crop area (parameters: x, y, width, height)
        Rectangle2D rectangle = new Rectangle2D.Float(0, 40, 600, 360);
        // Set the crop area for the page
        page.setCropBox(rectangle);

        // Save the cropped PDF
        pdf.saveToFile("cropped.pdf");

        // Close the document and release resources
        pdf.close();
    }
}

Crop a PDF Page in Java

Crop a PDF page and Export the Result as an Image in Java

After cropping a PDF page, developers can use the PdfDocument.saveAsImage(int pageIndex, PdfImageType type) method to export the result as an image. The detailed steps are as follows.

  • Create an instance of the PdfDocument class.
  • Load a PDF document using the PdfDocument.loadFromFile() class.
  • Get a specific page from the PDF using the PdfDocument.getPages().get(int pageIndex) mthod.
  • Create an instance of the Rectangle2D class to define the crop area.
  • Use the PdfPageBase.setCropBox(Rectangle2D rect) method to set the crop area for the page.
  • Use the PdfDocument.saveAsImage(int pageIndex, PdfImageType type) method to export the cropped page as an image.
  • Save the image as an image file.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfImageType;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CropPdfPageAndSaveAsImage {
    public static void main(String[] args) {
        // Create an instance of the PdfDocument class
        PdfDocument pdf = new PdfDocument();
        // Load the PDF file
        pdf.loadFromFile("example.pdf");

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

        // Define the crop area (parameters: x, y, width, height)
        Rectangle2D rectangle = new Rectangle2D.Float(0, 40, 600, 360);
        // Set the crop area for the page
        page.setCropBox(rectangle);

        // Export the cropped page as an image
        BufferedImage image = pdf.saveAsImage(0, PdfImageType.Bitmap);

        // Save the image as a PNG file
        File outputFile = new File("cropped.png");
        try {
            ImageIO.write(image, "PNG", outputFile);
            System.out.println("Cropped page saved as: " + outputFile.getAbsolutePath());
        } catch (IOException e) {
            System.err.println("Error saving image: " + e.getMessage());
        }

        // Close the document and release resources
        pdf.close();
    }
}

Crop a PDF page and Export the Result as an Image in Java

Get a Free License

To fully experience the capabilities of Spire.PDF for Java without any evaluation limitations, you can request a free 30-day trial license.

Word documents often contain extensive text, and applying emphasis marks is an effective way to highlight key information. Whether you need to accentuate important terms or enhance text clarity with styled formatting, emphasis marks can make your content more readable and professional. Instead of manually adjusting formatting, this guide demonstrates how to use Spire.Doc for Python to efficiently apply emphasis to text in Word with Python, saving time while ensuring a polished document.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

If you are unsure how to install, please refer to this tutorial: How to Install Spire.Doc for Python on Windows.

Apply Emphasis Marks to First Matched Text in Word Documents

When crafting a Word document, highlighting keywords or phrases can improve readability and draw attention to important information. With Spire.Doc's CharacterFormat.EmphasisMark property, you can easily apply emphasis marks to any text, ensuring clarity and consistency.

Steps to apply emphasis marks to the first matched text in a Word document:

  • Create an object of the Document class.
  • Load a source Word document from files using Document.LoadFromFile() method.
  • Find the text that you want to emphasize with Document.FindString() method.
  • Apply emphasis marks to the text through CharacterFormat.EmphasisMark property.
  • Save the updated Word document using Document.SaveToFile() method.

Below is the code example showing how to emphasize the first matching text of "AI-Generated Art" in a Word document:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")

# Customize the text that you want to apply an emphasis mark to
matchingtext = doc.FindString("AI-Generated Art", True, True)

# Apply the emphasis mark to the matched text
matchingtext.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.CommaAbove

# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_FirstMatch.docx", FileFormat.Docx2013)
doc.Close()

Apply Emphasis Marks to the First Matched Text in Word Documents

Apply Emphasis Marks to All Matched Text in Word Files

In the previous section, we demonstrated how to add an emphasis mark to the first matched text. Now, let's take it a step further—how can we emphasize all occurrences of a specific text? The solution is simple: use the Document.FindAllString() method to locate all matches and then apply emphasis marks using the CharacterFormat.EmphasisMark property. Below, you'll find detailed steps and code examples to guide you through the process.

Steps to apply emphasis marks to all matched text:

  • Create an instance of Document class.
  • Read a Word file through Document.LoadFromFile() method.
  • Find all the matching text using Document.FindAllString() method.
  • Loop through all occurrences and apply the emphasis effect to the text through  CharacterFormat.EmphasisMark property.
  • Save the modified Word document through Document.SaveToFile() method.

The following code demonstrates how to apply emphasis to all occurrences of "AI-Generated Art" while ignoring case sensitivity:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")

# Customize the text that you want to apply an emphasis mark to
textselections = doc.FindAllString("AI-Generated Art", False, True)

# Loop through the text selections and apply the emphasis mark to the text
for textselection in textselections:
    textselection.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.CircleAbove

# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_AllMatch.docx", FileFormat.Docx2013)
doc.Close()

Python to Emphasize All Matched Text in Word Documents

Apply Emphasis Marks to Text in Word Documents with Regular Expression

Sometimes, the text you want to highlight may vary but follow a similar structure, such as email addresses, phone numbers, dates, or patterns like two to three words followed by special symbols (#, *, etc.). The best way to identify such text is by using regular expressions. Once located, you can apply emphasis marks using the same method. Let's go through the steps!

Steps to apply emphasis marks to text using regular expressions:

  • Create a Document instance.
  • Load a Word document from the local storage using Document.LoadFromFile() method.
  • Find text that you want to emphasize with Document.FindAllPattern() method.
  • Iterate through all occurrences and apply the emphasis effect to the text through  CharacterFormat.EmphasisMark property.
  • Save the resulting Word file through Document.SaveToFile() method.

The code example below shows how to emphasize "AI" and the word after it in a Word document:

  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
doc = Document()
doc.LoadFromFile("/AI-Generated Art.docx")

# Match "AI" and the next word using regular expression
pattern = Regex(r"AI\s+\w+")

# Find all matching text
textSelections = doc.FindAllPattern(pattern)

# Loop through all the matched text and apply an emphasis mark
for selection in textSelections:
    selection.GetAsOneRange().CharacterFormat.EmphasisMark = Emphasis.DotBelow

# Save the document as a new one
doc.SaveToFile("/ApplyEmphasisMark_Regex.docx", FileFormat.Docx2013)
doc.Close()

Apply Emphasis Marks to Text Using Regular Expressions in Word

Get a Free License

To fully experience the capabilities of Spire.Doc for Python without any evaluation limitations, you can request a free 30-day trial license.

page 18