com.aspose.words

Class ImageSavingArgs

  • java.lang.Object
    • com.aspose.words.ImageSavingArgs
public class ImageSavingArgs 
extends java.lang.Object

By default, when Aspose.Words saves a document to HTML, it saves each image into a separate file. Aspose.Words uses the document file name and a unique number to generate unique file name for each image found in the document.

ImageSavingArgs allows to redefine how image file names are generated or to completely circumvent saving of images into files by providing your own stream objects.

To apply your own logic for generating image file names use the ImageFileName, CurrentShape and IsImageAvailable properties.

To save images into streams instead of files, use the ImageStream property.

Example:

Shows how split a document into parts and save them.
public void documentParts() throws Exception {
    // Open a document to be converted to html
    Document doc = new Document(getMyDir() + "Rendering.docx");
    String outFileName = "SavingCallback.DocumentParts.Rendering.html";

    // We can use an appropriate SaveOptions subclass to customize the conversion process
    HtmlSaveOptions options = new HtmlSaveOptions();

    // We can use it to split a document into smaller parts, in this instance split by section breaks
    // Each part will be saved into a separate file, creating many files during the conversion process instead of just one
    options.setDocumentSplitCriteria(DocumentSplitCriteria.SECTION_BREAK);

    // We can set a callback to name each document part file ourselves
    options.setDocumentPartSavingCallback(new SavedDocumentPartRename(outFileName, options.getDocumentSplitCriteria()));

    // If we convert a document that contains images into html, we will end up with one html file which links to several images
    // Each image will be in the form of a file in the local file system
    // There is also a callback that can customize the name and file system location of each image
    options.setImageSavingCallback(new SavedImageRename(outFileName));

    // The DocumentPartSaving() and ImageSaving() methods of our callbacks will be run at this time
    doc.save(getArtifactsDir() + outFileName, options);
}

/// <summary>
/// Renames saved document parts that are produced when an HTML document is saved while being split according to a criteria.
/// </summary>
private static class SavedDocumentPartRename implements IDocumentPartSavingCallback {
    public SavedDocumentPartRename(String outFileName, int documentSplitCriteria) {
        mOutFileName = outFileName;
        mDocumentSplitCriteria = documentSplitCriteria;
    }

    public void documentPartSaving(DocumentPartSavingArgs args) throws Exception {
        Assert.assertTrue(args.getDocument().getOriginalFileName().endsWith("Rendering.docx"));

        String partType = "";

        switch (mDocumentSplitCriteria) {
            case DocumentSplitCriteria.PAGE_BREAK:
                partType = "Page";
                break;
            case DocumentSplitCriteria.COLUMN_BREAK:
                partType = "Column";
                break;
            case DocumentSplitCriteria.SECTION_BREAK:
                partType = "Section";
                break;
            case DocumentSplitCriteria.HEADING_PARAGRAPH:
                partType = "Paragraph from heading";
                break;
        }

        String partFileName = MessageFormat.format("{0} part {1}, of type {2}.{3}", mOutFileName, ++mCount, partType, FilenameUtils.getExtension(args.getDocumentPartFileName()));

        // We can designate the filename and location of each output file either by filename
        args.setDocumentPartFileName(partFileName);

        // Or we can make a new stream and choose the location of the file at construction
        try {
            FileOutputStream outputStream = new FileOutputStream(getArtifactsDir() + partFileName);
            args.setDocumentPartStream(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Assert.assertNotNull(args.getDocumentPartStream());
        Assert.assertFalse(args.getKeepDocumentPartStreamOpen());
    }

    private int mCount;
    private String mOutFileName;
    private int mDocumentSplitCriteria;
}

/// <summary>
/// Renames saved images that are produced when an HTML document is saved.
/// </summary>
public static class SavedImageRename implements IImageSavingCallback {
    public SavedImageRename(String outFileName) {
        mOutFileName = outFileName;
    }

    public void imageSaving(ImageSavingArgs args) throws Exception {
        // Same filename and stream functions as above in IDocumentPartSavingCallback apply here
        String imageFileName = MessageFormat.format("{0} shape {1}, of type {2}.{3}", mOutFileName, ++mCount, args.getCurrentShape().getShapeType(), FilenameUtils.getExtension(args.getImageFileName()));

        args.setImageFileName(imageFileName);

        try {
            FileOutputStream outputStream = new FileOutputStream(getArtifactsDir() + imageFileName);
            args.setImageStream(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Assert.assertNotNull(args.getImageStream());
        Assert.assertTrue(args.isImageAvailable());
        Assert.assertFalse(args.getKeepImageStreamOpen());
    }

    private int mCount;
    private String mOutFileName;
}

Property Getters/Setters Summary
ShapeBasegetCurrentShape()
Gets the ShapeBase object corresponding to the shape or group shape that is about to be saved.
DocumentgetDocument()
Gets the document object that is currently being saved.
java.lang.StringgetImageFileName()
void
setImageFileName(java.lang.Stringvalue)
           Gets or sets the file name (without path) where the image will be saved to.
java.io.OutputStreamgetImageStream()
void
setImageStream(java.io.OutputStreamvalue)
           Allows to specify the stream where the image will be saved to.
booleanisImageAvailable()
Returns true if the current image is available for export.
booleangetKeepImageStreamOpen()
void
           Specifies whether Aspose.Words should keep the stream open or close it after saving an image.
 

    • Property Getters/Setters Detail

      • getCurrentShape

        public ShapeBase getCurrentShape()
        
        Gets the ShapeBase object corresponding to the shape or group shape that is about to be saved.

        IImageSavingCallback can be fired while saving either a shape or a group shape. That's why the property has ShapeBase type. You can check whether it's a group shape comparing ShapeBase.ShapeType with ShapeType.GROUP or by casting it to one of derived classes: Shape or GroupShape.

        Aspose.Words uses the document file name and a unique number to generate unique file name for each image found in the document. You can use the CurrentShape property to generate a "better" file name by examining shape properties such as ImageData.Title (Shape only), ImageData.SourceFullName (Shape only) and ShapeBase.Name. Of course you can build file names using any other properties or criteria but note that subsidiary file names must be unique within the export operation.

        Some images in the document can be unavailable. To check image availability use the IsImageAvailable property.

        Example:

        Shows how to involve an image saving callback in an .html conversion process.
        public void imageSavingCallback() throws Exception {
            // Open a document which contains shapes with images
            Document doc = new Document(getMyDir() + "Rendering.docx");
        
            // Create a HtmlSaveOptions object with a custom image saving callback that will print image information
            HtmlSaveOptions options = new HtmlSaveOptions();
            options.setImageSavingCallback(new ImageShapePrinter());
        
            doc.save(getArtifactsDir() + "HtmlSaveOptions.ImageSavingCallback.html", options);
        }
        
        /// <summary>
        /// Prints information of all images that are about to be saved from within a document to image files.
        /// </summary>
        private static class ImageShapePrinter implements IImageSavingCallback {
            public void imageSaving(ImageSavingArgs args) throws Exception {
                args.setKeepImageStreamOpen(false);
                Assert.assertTrue(args.isImageAvailable());
        
                String[] splitOriginalFileName = args.getDocument().getOriginalFileName().split("\\\\");
                System.out.println(MessageFormat.format("{0} Image #{1}", splitOriginalFileName[splitOriginalFileName.length - 1], ++mImageCount));
        
                LayoutCollector layoutCollector = new LayoutCollector(args.getDocument());
        
                System.out.println(MessageFormat.format("\tOn page:\t{0}", layoutCollector.getStartPageIndex(args.getCurrentShape())));
                System.out.println(MessageFormat.format("\tDimensions:\t{0}", args.getCurrentShape().getBounds().toString()));
                System.out.println(MessageFormat.format("\tAlignment:\t{0}", args.getCurrentShape().getVerticalAlignment()));
                System.out.println(MessageFormat.format("\tWrap type:\t{0}", args.getCurrentShape().getWrapType()));
                System.out.println(MessageFormat.format("Output filename:\t{0}\n", args.getImageFileName()));
            }
        
            private int mImageCount;
        }
      • getDocument

        public Document getDocument()
        
        Gets the document object that is currently being saved.

        Example:

        Shows how to involve an image saving callback in an .html conversion process.
        public void imageSavingCallback() throws Exception {
            // Open a document which contains shapes with images
            Document doc = new Document(getMyDir() + "Rendering.docx");
        
            // Create a HtmlSaveOptions object with a custom image saving callback that will print image information
            HtmlSaveOptions options = new HtmlSaveOptions();
            options.setImageSavingCallback(new ImageShapePrinter());
        
            doc.save(getArtifactsDir() + "HtmlSaveOptions.ImageSavingCallback.html", options);
        }
        
        /// <summary>
        /// Prints information of all images that are about to be saved from within a document to image files.
        /// </summary>
        private static class ImageShapePrinter implements IImageSavingCallback {
            public void imageSaving(ImageSavingArgs args) throws Exception {
                args.setKeepImageStreamOpen(false);
                Assert.assertTrue(args.isImageAvailable());
        
                String[] splitOriginalFileName = args.getDocument().getOriginalFileName().split("\\\\");
                System.out.println(MessageFormat.format("{0} Image #{1}", splitOriginalFileName[splitOriginalFileName.length - 1], ++mImageCount));
        
                LayoutCollector layoutCollector = new LayoutCollector(args.getDocument());
        
                System.out.println(MessageFormat.format("\tOn page:\t{0}", layoutCollector.getStartPageIndex(args.getCurrentShape())));
                System.out.println(MessageFormat.format("\tDimensions:\t{0}", args.getCurrentShape().getBounds().toString()));
                System.out.println(MessageFormat.format("\tAlignment:\t{0}", args.getCurrentShape().getVerticalAlignment()));
                System.out.println(MessageFormat.format("\tWrap type:\t{0}", args.getCurrentShape().getWrapType()));
                System.out.println(MessageFormat.format("Output filename:\t{0}\n", args.getImageFileName()));
            }
        
            private int mImageCount;
        }
      • getImageFileName/setImageFileName

        public java.lang.String getImageFileName() / public void setImageFileName(java.lang.String value)
        
        Gets or sets the file name (without path) where the image will be saved to.

        This property allows you to redefine how the image file names are generated during export to HTML.

        When the event is fired, this property contains the file name that was generated by Aspose.Words. You can change the value of this property to save the image into a different file. Note that file names must be unique.

        Aspose.Words automatically generates a unique file name for every embedded image when exporting to HTML format. How the image file name is generated depends on whether you save the document to a file or to a stream.

        When saving a document to a file, the generated image file name looks like <document base file name>.<image number>.<extension>.

        When saving a document to a stream, the generated image file name looks like Aspose.Words.<document guid>.<image number>.<extension>.

        ImageFileName must contain only the file name without the path. Aspose.Words determines the path for saving and the value of the src attribute for writing to HTML using the document file name, the HtmlSaveOptions.ImagesFolder and HtmlSaveOptions.ImagesFolderAlias properties.

        Example:

        Shows how split a document into parts and save them.
        public void documentParts() throws Exception {
            // Open a document to be converted to html
            Document doc = new Document(getMyDir() + "Rendering.docx");
            String outFileName = "SavingCallback.DocumentParts.Rendering.html";
        
            // We can use an appropriate SaveOptions subclass to customize the conversion process
            HtmlSaveOptions options = new HtmlSaveOptions();
        
            // We can use it to split a document into smaller parts, in this instance split by section breaks
            // Each part will be saved into a separate file, creating many files during the conversion process instead of just one
            options.setDocumentSplitCriteria(DocumentSplitCriteria.SECTION_BREAK);
        
            // We can set a callback to name each document part file ourselves
            options.setDocumentPartSavingCallback(new SavedDocumentPartRename(outFileName, options.getDocumentSplitCriteria()));
        
            // If we convert a document that contains images into html, we will end up with one html file which links to several images
            // Each image will be in the form of a file in the local file system
            // There is also a callback that can customize the name and file system location of each image
            options.setImageSavingCallback(new SavedImageRename(outFileName));
        
            // The DocumentPartSaving() and ImageSaving() methods of our callbacks will be run at this time
            doc.save(getArtifactsDir() + outFileName, options);
        }
        
        /// <summary>
        /// Renames saved document parts that are produced when an HTML document is saved while being split according to a criteria.
        /// </summary>
        private static class SavedDocumentPartRename implements IDocumentPartSavingCallback {
            public SavedDocumentPartRename(String outFileName, int documentSplitCriteria) {
                mOutFileName = outFileName;
                mDocumentSplitCriteria = documentSplitCriteria;
            }
        
            public void documentPartSaving(DocumentPartSavingArgs args) throws Exception {
                Assert.assertTrue(args.getDocument().getOriginalFileName().endsWith("Rendering.docx"));
        
                String partType = "";
        
                switch (mDocumentSplitCriteria) {
                    case DocumentSplitCriteria.PAGE_BREAK:
                        partType = "Page";
                        break;
                    case DocumentSplitCriteria.COLUMN_BREAK:
                        partType = "Column";
                        break;
                    case DocumentSplitCriteria.SECTION_BREAK:
                        partType = "Section";
                        break;
                    case DocumentSplitCriteria.HEADING_PARAGRAPH:
                        partType = "Paragraph from heading";
                        break;
                }
        
                String partFileName = MessageFormat.format("{0} part {1}, of type {2}.{3}", mOutFileName, ++mCount, partType, FilenameUtils.getExtension(args.getDocumentPartFileName()));
        
                // We can designate the filename and location of each output file either by filename
                args.setDocumentPartFileName(partFileName);
        
                // Or we can make a new stream and choose the location of the file at construction
                try {
                    FileOutputStream outputStream = new FileOutputStream(getArtifactsDir() + partFileName);
                    args.setDocumentPartStream(outputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
                Assert.assertNotNull(args.getDocumentPartStream());
                Assert.assertFalse(args.getKeepDocumentPartStreamOpen());
            }
        
            private int mCount;
            private String mOutFileName;
            private int mDocumentSplitCriteria;
        }
        
        /// <summary>
        /// Renames saved images that are produced when an HTML document is saved.
        /// </summary>
        public static class SavedImageRename implements IImageSavingCallback {
            public SavedImageRename(String outFileName) {
                mOutFileName = outFileName;
            }
        
            public void imageSaving(ImageSavingArgs args) throws Exception {
                // Same filename and stream functions as above in IDocumentPartSavingCallback apply here
                String imageFileName = MessageFormat.format("{0} shape {1}, of type {2}.{3}", mOutFileName, ++mCount, args.getCurrentShape().getShapeType(), FilenameUtils.getExtension(args.getImageFileName()));
        
                args.setImageFileName(imageFileName);
        
                try {
                    FileOutputStream outputStream = new FileOutputStream(getArtifactsDir() + imageFileName);
                    args.setImageStream(outputStream);
                } catch (IOException e) {
                    e.printStackTrace();
                }
        
                Assert.assertNotNull(args.getImageStream());
                Assert.assertTrue(args.isImageAvailable());
                Assert.assertFalse(args.getKeepImageStreamOpen());
            }
        
            private int mCount;
            private String mOutFileName;
        }
        See Also:
        CurrentShape, IsImageAvailable, ImageStream, HtmlSaveOptions.ImagesFolder, HtmlSaveOptions.ImagesFolderAlias
      • getImageStream/setImageStream

        public java.io.OutputStream getImageStream() / public void setImageStream(java.io.OutputStream value)
        
        Allows to specify the stream where the image will be saved to.

        This property allows you to save images to streams instead of files during HTML.

        The default value is null. When this property is null, the image will be saved to a file specified in the ImageFileName property.

        Using IImageSavingCallback you cannot substitute one image with another. It is intended only for control over location where to save images.

        Example:

        Shows how to involve an image saving callback in an .html conversion process.
        public void imageSavingCallback() throws Exception {
            // Open a document which contains shapes with images
            Document doc = new Document(getMyDir() + "Rendering.docx");
        
            // Create a HtmlSaveOptions object with a custom image saving callback that will print image information
            HtmlSaveOptions options = new HtmlSaveOptions();
            options.setImageSavingCallback(new ImageShapePrinter());
        
            doc.save(getArtifactsDir() + "HtmlSaveOptions.ImageSavingCallback.html", options);
        }
        
        /// <summary>
        /// Prints information of all images that are about to be saved from within a document to image files.
        /// </summary>
        private static class ImageShapePrinter implements IImageSavingCallback {
            public void imageSaving(ImageSavingArgs args) throws Exception {
                args.setKeepImageStreamOpen(false);
                Assert.assertTrue(args.isImageAvailable());
        
                String[] splitOriginalFileName = args.getDocument().getOriginalFileName().split("\\\\");
                System.out.println(MessageFormat.format("{0} Image #{1}", splitOriginalFileName[splitOriginalFileName.length - 1], ++mImageCount));
        
                LayoutCollector layoutCollector = new LayoutCollector(args.getDocument());
        
                System.out.println(MessageFormat.format("\tOn page:\t{0}", layoutCollector.getStartPageIndex(args.getCurrentShape())));
                System.out.println(MessageFormat.format("\tDimensions:\t{0}", args.getCurrentShape().getBounds().toString()));
                System.out.println(MessageFormat.format("\tAlignment:\t{0}", args.getCurrentShape().getVerticalAlignment()));
                System.out.println(MessageFormat.format("\tWrap type:\t{0}", args.getCurrentShape().getWrapType()));
                System.out.println(MessageFormat.format("Output filename:\t{0}\n", args.getImageFileName()));
            }
        
            private int mImageCount;
        }
        See Also:
        ImageFileName, KeepImageStreamOpen
      • isImageAvailable

        public boolean isImageAvailable()
        
        Returns true if the current image is available for export.

        Some images in the document can be unavailable, for example, because the image is linked and the link is inaccessible or does not point to a valid image. In this case Aspose.Words exports an icon with a red cross. This property returns true if the original image is available; returns false if the original image is not available and a "no image" icon will be offered for save.

        When saving a group shape or a shape that doesn't require any image this property is always true.

        Example:

        Shows how to involve an image saving callback in an .html conversion process.
        public void imageSavingCallback() throws Exception {
            // Open a document which contains shapes with images
            Document doc = new Document(getMyDir() + "Rendering.docx");
        
            // Create a HtmlSaveOptions object with a custom image saving callback that will print image information
            HtmlSaveOptions options = new HtmlSaveOptions();
            options.setImageSavingCallback(new ImageShapePrinter());
        
            doc.save(getArtifactsDir() + "HtmlSaveOptions.ImageSavingCallback.html", options);
        }
        
        /// <summary>
        /// Prints information of all images that are about to be saved from within a document to image files.
        /// </summary>
        private static class ImageShapePrinter implements IImageSavingCallback {
            public void imageSaving(ImageSavingArgs args) throws Exception {
                args.setKeepImageStreamOpen(false);
                Assert.assertTrue(args.isImageAvailable());
        
                String[] splitOriginalFileName = args.getDocument().getOriginalFileName().split("\\\\");
                System.out.println(MessageFormat.format("{0} Image #{1}", splitOriginalFileName[splitOriginalFileName.length - 1], ++mImageCount));
        
                LayoutCollector layoutCollector = new LayoutCollector(args.getDocument());
        
                System.out.println(MessageFormat.format("\tOn page:\t{0}", layoutCollector.getStartPageIndex(args.getCurrentShape())));
                System.out.println(MessageFormat.format("\tDimensions:\t{0}", args.getCurrentShape().getBounds().toString()));
                System.out.println(MessageFormat.format("\tAlignment:\t{0}", args.getCurrentShape().getVerticalAlignment()));
                System.out.println(MessageFormat.format("\tWrap type:\t{0}", args.getCurrentShape().getWrapType()));
                System.out.println(MessageFormat.format("Output filename:\t{0}\n", args.getImageFileName()));
            }
        
            private int mImageCount;
        }
        See Also:
        CurrentShape
      • getKeepImageStreamOpen/setKeepImageStreamOpen

        public boolean getKeepImageStreamOpen() / public void setKeepImageStreamOpen(boolean value)
        
        Specifies whether Aspose.Words should keep the stream open or close it after saving an image.

        Default is false and Aspose.Words will close the stream you provided in the ImageStream property after writing an image into it. Specify true to keep the stream open.

        Example:

        Shows how to involve an image saving callback in an .html conversion process.
        public void imageSavingCallback() throws Exception {
            // Open a document which contains shapes with images
            Document doc = new Document(getMyDir() + "Rendering.docx");
        
            // Create a HtmlSaveOptions object with a custom image saving callback that will print image information
            HtmlSaveOptions options = new HtmlSaveOptions();
            options.setImageSavingCallback(new ImageShapePrinter());
        
            doc.save(getArtifactsDir() + "HtmlSaveOptions.ImageSavingCallback.html", options);
        }
        
        /// <summary>
        /// Prints information of all images that are about to be saved from within a document to image files.
        /// </summary>
        private static class ImageShapePrinter implements IImageSavingCallback {
            public void imageSaving(ImageSavingArgs args) throws Exception {
                args.setKeepImageStreamOpen(false);
                Assert.assertTrue(args.isImageAvailable());
        
                String[] splitOriginalFileName = args.getDocument().getOriginalFileName().split("\\\\");
                System.out.println(MessageFormat.format("{0} Image #{1}", splitOriginalFileName[splitOriginalFileName.length - 1], ++mImageCount));
        
                LayoutCollector layoutCollector = new LayoutCollector(args.getDocument());
        
                System.out.println(MessageFormat.format("\tOn page:\t{0}", layoutCollector.getStartPageIndex(args.getCurrentShape())));
                System.out.println(MessageFormat.format("\tDimensions:\t{0}", args.getCurrentShape().getBounds().toString()));
                System.out.println(MessageFormat.format("\tAlignment:\t{0}", args.getCurrentShape().getVerticalAlignment()));
                System.out.println(MessageFormat.format("\tWrap type:\t{0}", args.getCurrentShape().getWrapType()));
                System.out.println(MessageFormat.format("Output filename:\t{0}\n", args.getImageFileName()));
            }
        
            private int mImageCount;
        }
        See Also:
        ImageStream