Spire.Office Knowledgebase Page 19 | E-iceblue

Export Excel charts and shapes as standalone images is a critical feature for enhancing data visualization workflows. Converting charts and shapes into image formats enables seamless integration of dynamic data into reports, dashboards, or presentations, ensuring compatibility across platforms where Excel files might not be natively supported. By programmatically generating images from Excel charts and shapes within web applications using Spire.XLS for JavaScript API, developers can automate export workflows, ensure consistent visualization, and deliver dynamically updated visuals to end-users without extra manual processing steps.

In this article, we will explore how to use Spire.XLS for Java Script to save charts and shapes in Excel workbooks as images using JavaScript in React applications.

Install Spire.XLS for JavaScript

To get started with saving Excel charts and shapes as images 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

Save Excel Charts to Images with JavaScript

By processing Excel files using the Spire.XLS WebAssembly module, we can utilize the Workbook.SaveChartAsImage() method to save a specific chart from an Excel worksheet as an image and store it in the virtual file system (VFS). The saved image can then be downloaded or used for further processing.

The detailed steps are as follows:

  • Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the wasmModule.FetchFileToVFS() method.
  • Create a Workbook instance using the wasmModule.Workbook.Create() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Iterate though the charts and save them as images using the Workbook.SaveChartAsImage() method, specifying the worksheet and chart index as parameters.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 convert charts to images
  const SaveExcelChartAsImage = async () => {
    if (wasmModule) {
      // Specify the input file name
      const inputFileName = 'Sample62.xlsx';

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Create the image folder in the VFS
      const imageFolderName = `Images`;
      wasmModule.FS.mkdir(imageFolderName, 0x1FF);

      // Create an instance of the Workbook class
      const workbook = wasmModule.Workbook.Create();

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

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each chart in the worksheet
        for (let j = 0; j < sheet.Charts.Count; j++) {
          // Save the current chart to an image
          let image = workbook.SaveChartAsImage({ worksheet: sheet, chartIndex: j})
          // Save the image to the VFS
          const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
          image.Save(`${imageFolderName}/${cleanSheetName}_Chart-${j}.png`, 0x1FF)
        }
      }

      // Recursive function to add a directory and its contents to the ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = wasmModule.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Attempt to read file data
            const fileData = wasmModule.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it's a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Pack the image folder to a zip file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the result zip file and trigger a download
      zip.generateAsync({type:"blob"})
          .then(function(content) {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(content);
            link.download = 'Charts.zip';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
          }).catch(function(err) {
        console.error("There was an error generating the zip file:", err);
      });
    }
  };

  return (
      <div style={{ textAlign: 'center', height: '300px' }}>
        <h1>Save Excel Charts as Images Using JavaScript in React</h1>
        <button onClick={SaveExcelChartAsImage} disabled={!wasmModule}>
          Export Charts
        </button>
      </div>
  );
}

export default App;

Excel chart exported as PNG image using JavaScript in React

Save Excel Shapes to Images with JavaScript

We can retrieve shapes from an Excel worksheet using the Worksheet.PrstGeomShapes.get() method and save them as images using the shape.SaveToImage() method. The images can then be stored in the virtual file system (VFS) and downloaded or used for further processing.

Below are the detailed steps:

  • Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
  • Fetch the Excel file and font files into the VFS using the wasmModule.FetchFileToVFS() method.
  • Create a Workbook instance using the wasmModule.Workbook.Create() method.
  • Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
  • Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
  • Get a shape from the worksheet or iterate through all shapes using the Worksheet.PrstGeomShapes.get() method.
  • Save the shapes as images using the shape.SaveToImage() method.
  • Save the images to the VFS using the image.Save() method.
  • Download the images or use them as needed.
  • JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';

function App() {

  // State to store 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 module loading
        console.error('Failed to load the 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 convert shapes to images
  const SaveExcelShapeAsImage = async () => {
    if (wasmModule) {
      // Specify the input file name
      const inputFileName = 'Sample62.xlsx';

      // Fetch the input file and add it to the VFS
      await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);

      // Fetch the font file and add it to the VFS
      await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
      await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Create the image folder in the VFS
      const imageFolderName = `Images`;
      wasmModule.FS.mkdir(imageFolderName, 0x1FF);

      // Create an instance of the Workbook class
      const workbook = wasmModule.Workbook.Create();

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

      // Iterate through each worksheet in the workbook
      for (let i = 0; i < workbook.Worksheets.Count; i++) {
        // Get the current worksheet
        const sheet = workbook.Worksheets.get(i);
        // Iterate through each shape in the worksheet
        for (let j = 0; j < sheet.PrstGeomShapes.Count; j++) {
          // Get the current shape
          const shape = sheet.PrstGeomShapes.get(j);
          // Save the shape to an image
          const image = shape.SaveToImage();
          // Save the image to the VFS
          const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
          image.Save(`${imageFolderName}/${cleanSheetName}_Shape-${j}.png`, 0x1FF)
        }
      }

      // Recursive function to add a directory and its contents to the ZIP
      const addFilesToZip = (folderPath, zipFolder) => {
        const items = wasmModule.FS.readdir(folderPath);
        items.filter(item => item !== "." && item !== "..").forEach((item) => {
          const itemPath = `${folderPath}/${item}`;

          try {
            // Attempt to read file data
            const fileData = wasmModule.FS.readFile(itemPath);
            zipFolder.file(item, fileData);
          } catch (error) {
            if (error.code === 'EISDIR') {
              // If it's a directory, create a new folder in the ZIP and recurse into it
              const zipSubFolder = zipFolder.folder(item);
              addFilesToZip(itemPath, zipSubFolder);
            } else {
              // Handle other errors
              console.error(`Error processing ${itemPath}:`, error);
            }
          }
        });
      };

      // Pack the image folder to a zip file
      const zip = new JSZip();
      addFilesToZip(imageFolderName, zip);

      // Generate a Blob from the result zip file and trigger a download
      zip.generateAsync({type:"blob"})
          .then(function(content) {
            const link = document.createElement('a');
            link.href = URL.createObjectURL(content);
            link.download = 'Shapes.zip';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(link.href);
          }).catch(function(err) {
        console.error("There was an error generating the zip file:", err);
      });
    }
  };

  return (
      <div style="{{">
        <h1>Save Excel Shapes as Images Using JavaScript in React</h1>
        <button onClick={SaveExcelShapeAsImage} disabled={!wasmModule}>
        Export Shapes
        </button>
      </div>
  );
}

export default App;

Excel shape saved as PNG image using JavaScript in React

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.

PowerPoint presentations often contain sensitive or proprietary information, making it essential to secure them from unauthorized access or modifications. Whether you're sharing a presentation with colleagues, clients, or stakeholders, protecting your slides ensures that your content remains intact and confidential. On the other hand, there may be times when you need to unprotect a presentation to make edits or updates. In this guide, we'll explore how to protect and unprotect PowerPoint presentations programmatically in React using Spire.Presentation for JavaScript.

Install Spire.Presentation for JavaScript

To get started with protecting and unprotecting PowerPoint presentations in a React application, you can either download Spire.Presentation for JavaScript from the official website or install it via npm with the following command:

npm i spire.presentation

After that, copy the "Spire.Presentation.Base.js" and "Spire.Presentation.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Protect a PowerPoint Presentation with a Password

Setting a password on a PowerPoint presentation is an effective way to ensure that only authorized users can access its content. By using the Presentation.Encrypt() method of Spire.Presentation for JavaScript, developers can encrypt a PowerPoint presentation with ease. The key steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Encrypt the presentation with a password using the Presentation.Encrypt() method.
  • Save the resulting presentation using the Presentation.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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 protect a PowerPoint file with a password
  const ProtectPowerPointPresentation = async () => {
    if (wasmModule) {

      // Load the font file into the virtual file system (VFS) to ensure proper rendering
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the PowerPoint file into the virtual file system (VFS)
      const inputFileName = "Sample.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a Presentation instance and load the PowerPoint file from the virtual file system
      const ppt = wasmModule.Presentation.Create();
      ppt.LoadFromFile(inputFileName);

      // Define the password
      let password = "e-iceblue";

      // Protect the PowerPoint file with the password
      ppt.Encrypt(password);

      // Define the output file name
      const outputFileName = "Encrypted.pptx";

      // Save the resulting PowerPoint file
      ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });

      // Read the generated PowerPoint file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PowerPoint file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
 
      // Clean up resources
      ppt.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Protect a PowerPoint Presentation with a Password</h1>
      <button onClick={ProtectPowerPointPresentation} disabled={!wasmModule}>
        Protect
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Once it's running, click on the "Protect" button to protect the PowerPoint presentation with a password:

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

Upon opening the output presentation, a dialog box will appear, prompting you to enter a password to gain access to the file:

Protect a PowerPoint Presentation with a Password

Make a PowerPoint Presentation Read-Only

Enabling the read-only setting prevents others from making changes to a PowerPoint presentation while still allowing them to view it. Spire.Presentation for JavaScript offers the Presentation.Protect() method to achieve this purpose. The key steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
  • Make the presentation read-only using the Presentation.Protect() method.
  • Save the resulting presentation using the Presentation.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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 make a PowerPoint file ready only
  const MakePresentationReadOnly = async () => {
    if (wasmModule) {

      // Load the font file into the virtual file system (VFS) to ensure proper rendering
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the PowerPoint file into the virtual file system (VFS)
      const inputFileName = "Sample.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a Presentation instance and load the PowerPoint file from the virtual file system
      const ppt = wasmModule.Presentation.Create();
      ppt.LoadFromFile(inputFileName);

      // Define the password
      let password = "e-iceblue";

      // Make the PowerPoint file read-only by protecting it with the password
      ppt.Protect(password);

      // Define the output file name
      const outputFileName = "ReadOnly.pptx";

      // Save the resulting PowerPoint file
      ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });

      // Read the generated PowerPoint file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PowerPoint file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
 
      // Clean up resources
      ppt.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Make a PowerPoint Presentation Read-Only</h1>
      <button onClick={MakePresentationReadOnly} disabled={!wasmModule}>
        Start
      </button>
    </div>
  );
}

export default App;

Make a PowerPoint Presentation Read-Only

Remove Password Protection from a PowerPoint Presentation

If password protection is no longer needed, it can be easily removed to allow unrestricted access to the presentation using the Presentation.RemoveEncryption() method. The key steps are as follows.

  • Create an object of the Presentation class.
  • Load a password-protected PowerPoint presentation with its password using the Presentation.LoadFromFile() method.
  • Remove password protection from the presentation using the Presentation.RemoveEncryption() method.
  • Save the resulting presentation using the Presentation.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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 remove password encryption from a PowerPoint file
  const RemoveEncryptionFromPresentation = async () => {
    if (wasmModule) {

      // Load the font file into the virtual file system (VFS) to ensure proper rendering
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the PowerPoint file into the virtual file system (VFS)
      const inputFileName = "Encrypted.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a Presentation instance and load the PowerPoint file from the virtual file system
      const ppt = wasmModule.Presentation.Create();
      ppt.LoadFromFile({file: inputFileName, password: "your password"});

      //Remove the password encryption
      ppt.RemoveEncryption();

      // Define the output file name
      const outputFileName = "Decrypted.pptx";

      // Save the resulting PowerPoint file
      ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });

      // Read the generated PowerPoint file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PowerPoint file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
 
      // Clean up resources
      ppt.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove Password Protection from a PowerPoint Presentation</h1>
      <button onClick={RemoveEncryptionFromPresentation} disabled={!wasmModule}>
        Start
      </button>
    </div>
  );
}

export default App;

Remove Password Protection from a PowerPoint Presentation

Remove Read-Only Setting from a PowerPoint Presentation

Disabling the read-only setting allows others to edit the presentation and make necessary changes. By using the Presentation.RemoveProtect() method, developers can remove the read-only setting from a PowerPoint presentation. The key steps are as follows.

  • Create an object of the Presentation class.
  • Load a PowerPoint presentation that has been made as read-only using the Presentation.LoadFromFile() method.
  • Remove the read-only setting from the presentation using the Presentation.RemoveProtect() method.
  • Save the resulting presentation using the Presentation.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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 remove the read-only setting from a PowerPoint file
  const RemoveReadOnlyFromPresentation = async () => {
    if (wasmModule) {

      // Load the font file into the virtual file system (VFS) to ensure proper rendering
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the PowerPoint file into the virtual file system (VFS)
      const inputFileName = "ReadOnly.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a Presentation instance and load the PowerPoint file from the virtual file system
      const ppt = wasmModule.Presentation.Create();
      ppt.LoadFromFile(inputFileName);

      // Remove the read-only setting from the presentation
      ppt.RemoveProtect();

      // Define the output file name
      const outputFileName = "RemoveReadOnly.pptx";

      // Save the resulting PowerPoint file
      ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });

      // Read the generated PowerPoint file
      const modifiedFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blob object from the PowerPoint file
      const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});

      // Create a URL for the Blob
      const url = URL.createObjectURL(modifiedFile);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 
 
      // Clean up resources
      ppt.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Remove Read-Only Setting from a PowerPoint Presentation</h1>
      <button onClick={RemoveReadOnlyFromPresentation} disabled={!wasmModule}>
        Start
      </button>
    </div>
  );
}

export default App;

Remove Read-Only Setting from a PowerPoint Presentation

Get a Free License

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

Transforming PowerPoint presentations into image formats such as JPG or PNG is an effective method for enhancing the way you share visual content. By converting slides into images, you maintain the integrity of the design and layout, making it suitable for a wide range of uses, from online sharing to embedding in documents.

In this article, you will discover how to convert PowerPoint slides to images in React using Spire.Presentation for JavaScript. We will guide you through the process step-by-step, ensuring you can effortlessly create high-quality images from your presentations.

Install Spire.Presentation for JavaScript

To get started with converting PowerPoint to images in a React application, you can either download Spire.Presentation for JavaScript from the official website or install it via npm with the following command:

npm i spire.presentation

After that, copy the "Spire.Presentation.Base.js" and "Spire.Presentation.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.

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

Convert PowerPoint to PNG or JPG with JavaScript

Using Spire.Presentation for JavaScript, you can access a specific slide with the Presentation.Slides.get_Item() method. Once you have the slide, convert it to image data using ISlide.SaveAsImage(). You can then save the image in PNG or JPG format. To convert each slide into a separate image file, simply iterate through the slides and perform the conversion for each one.

The steps to convert PowerPoint to PNG or JPG using JavaScript are as follows:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the wasmModule.Presentation.Create() method
  • Load the PowerPoint document using the Presentation.LoadFromFile() method.
  • Loop through the slides in the document:
    • Get a specific slide using the Presentation.Slides.get_Item() method.
    • Convert the slide into image data using the ISlide.SaveAsImage() method.
    • Save the image data to a PNG or JPG file using the Save() method of the image data object.
    • Create a Blob object from the generated image file.
    • Trigger the download of the image file.
  • 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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 convert PowerPoint to PNG
  const PowerPointToPNG = async () => {
    if (wasmModule) {

      // Load the font files used the PowerPoint file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input PowerPoint file into the virtual file system 
      const inputFileName = "ToImage.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a PowerPoint document
      const presentation = wasmModule.Presentation.Create();

      // Load the PowerPoint file
      presentation.LoadFromFile(inputFileName);

      // Iterate through the slides
      for (let i = 0; i < presentation.Slides.Count; i++) {

        // Convert a specific slide into image data
        let image = presentation.Slides.get_Item(i).SaveAsImage();

        // Specify the output file name
        let outputFileName = `ToImage_img_${i}.png`;

        // Save each image in virtual storage
        image.Save(outputFileName);

        // Read the generated image file from VFS
        const imageFileArray = wasmModule.FS.readFile(outputFileName);

        // Create a Blog object from the image file
        const imageBlob = new Blob([imageFileArray], { type: "image/png" });

        // Create a URL for the Blob
        const url = URL.createObjectURL(imageBlob);

        // Create an anchor element to trigger the download
        const a = document.createElement('a');
        a.href = url;
        a.download = outputFileName;
        document.body.appendChild(a);
        a.click(); 
        document.body.removeChild(a); 
        URL.revokeObjectURL(url); 
      };

      // Clean up resources
      presentation.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PowerPoint to PNG in React</h1>
      <button onClick={PowerPointToPNG} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

React app runs at localhost:3000

Below is a screenshot of the generated PNG image files:

Convert PowerPoint to PNG in React

Convert PowerPoint to SVG with JavaScript

Spire.Presentation for JavaScript provides the ISlide.SaveToSVG() method, allowing you to convert a slide into SVG byte data. This byte data can then be saved as an SVG file using the Save() method.

The following are the steps to convert PowerPoint to SVG using JavaScript:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the wasmModule.Presentation.Create() method
  • Load the PowerPoint document using the Presentation.LoadFromFile() method.
  • Loop through the slides in the document:
    • Get a specific slide using the Presentation.Slides.get_Item() method.
    • Convert the slide into SVG byte data using the ISlide.SaveToSVG() method.
    • Save the byte data to an SVG file using the Save() method.
    • Create a Blob object from the generated image file.
    • Trigger the download of the image file.
  • 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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 convert PowerPoint to SVG
  const PowerPointToSVG = async () => {
    if (wasmModule) {

      // Load the font files used the PowerPoint file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input PowerPoint file into the virtual file system 
      const inputFileName = "ToImage.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a PowerPoint document
      const presentation = wasmModule.Presentation.Create();

      // Load the PowerPoint file
      presentation.LoadFromFile(inputFileName);

      // Iterate through the slides
      for (let i = 0; i < presentation.Slides.Count; i++) {

        // Get a specific slide
        let slide = presentation.Slides.get_Item(i);

        // Convert the slide into SVG bytes
        let image = slide.SaveToSVG()

        // Specify the output file name
        let outputFileName = `ToImage_img_${i}.svg`;

        // Save each image in virtual storage
        image.Save(outputFileName);

        // Read the generated image file from VFS
        const imageFileArray = wasmModule.FS.readFile(outputFileName);

        // Create a Blog object from the image file
        const imageBlob = new Blob([imageFileArray], { type: "image/svg" });

        // Create a URL for the Blob
        const url = URL.createObjectURL(imageBlob);

        // Create an anchor element to trigger the download
        const a = document.createElement('a');
        a.href = url;
        a.download = outputFileName;
        document.body.appendChild(a);
        a.click(); 
        document.body.removeChild(a); 
        URL.revokeObjectURL(url); 
      };

      // Clean up resources
      presentation.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PowerPoint to SVG in React</h1>
      <button onClick={PowerPointToSVG} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Convert PowerPoint to SVG in React

Convert PowerPoint to TIFF with JavaScript

Spire.Presentation for JavaScript includes the Presentation.SaveToFile() method, which allows you to convert an entire PowerPoint document into a multi-frame TIFF image seamlessly.

The following are the steps to convert PowerPoint to TIFF using JavaScript:

  • Load required font files into the virtual file system (VFS).
  • Instantiate a new document using the wasmModule.Presentation.Create() method
  • Load the PowerPoint document using the Presentation.LoadFromFile() method.
  • Convert the document to a TIFF image file using the Presenatation.SaveToFile() method.
  • Create a Blob object from the generated image file.
  • Trigger the download of the image file.
  • 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 Spire.Presentation from the global window object
        const { Module, spirepresentation } = window;

        // Set the wasmModule state when the runtime is initialized
        Module.onRuntimeInitialized = () => {
          setWasmModule(spirepresentation);
        };
      } 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.Presentation.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 convert PowerPoint to TIFF
  const PowerPointToTIFF = async () => {
    if (wasmModule) {

      // Load the font files used the PowerPoint file into the virtual file system (VFS)
      await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);

      // Load the input PowerPoint file into the virtual file system 
      const inputFileName = "ToImage.pptx";
      await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);

      // Create a PowerPoint document
      const presentation = wasmModule.Presentation.Create();

      // Load the PowerPoint file
      presentation.LoadFromFile(inputFileName);

      // Specify the output file name
      const outputFileName = "ToTIFF.tiff" 

      // Save the document to TIFF
      presentation.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Tiff });

      // Read the generated image file from VFS
      const imageFileArray = wasmModule.FS.readFile(outputFileName);

      // Create a Blog object from the image file
      const imageBlob = new Blob([imageFileArray], { type: "image/tiff" });

      // Create a URL for the Blob
      const url = URL.createObjectURL(imageBlob);

      // Create an anchor element to trigger the download
      const a = document.createElement('a');
      a.href = url;
      a.download = outputFileName;
      document.body.appendChild(a);
      a.click(); 
      document.body.removeChild(a); 
      URL.revokeObjectURL(url); 

      // Clean up resources
      presentation.Dispose();
    }
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Convert PowerPoint to TIFF in React</h1>
      <button onClick={PowerPointToTIFF} disabled={!wasmModule}>
        Generate
      </button>
    </div>
  );
}

export default App;

Convert PowerPoint to TIFF in React

Get a Free License

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

page 19