TxtSaveOptionsBase

Inheritance: java.lang.Object, com.aspose.words.SaveOptions

public abstract class TxtSaveOptionsBase extends SaveOptions

The base class for specifying additional options when saving a document into a text based formats.

To learn more, visit the Specify Save Options documentation article.

Examples:

Shows how to save a .txt document with a custom paragraph break.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.writeln("Paragraph 1.");
 builder.writeln("Paragraph 2.");
 builder.write("Paragraph 3.");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
 // to modify how we save the document to plaintext.
 TxtSaveOptions txtSaveOptions = new TxtSaveOptions();

 Assert.assertEquals(SaveFormat.TEXT, txtSaveOptions.getSaveFormat());

 // Set the "ParagraphBreak" to a custom value that we wish to put at the end of every paragraph.
 txtSaveOptions.setParagraphBreak(" End of paragraph.\r\r\t");

 doc.save(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt", txtSaveOptions);

 String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt").getText().trim();

 Assert.assertEquals("Paragraph 1. End of paragraph.\r\r\t" +
         "Paragraph 2. End of paragraph.\r\r\t" +
         "Paragraph 3. End of paragraph.", docText);
 

Constructors

ConstructorDescription
TxtSaveOptionsBase()

Methods

MethodDescription
createSaveOptions(int saveFormat)
createSaveOptions(String fileName)Creates a save options object of a class suitable for the file extension specified in the given file name.
getAllowEmbeddingPostScriptFonts()Gets a boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved.
getDefaultTemplate()Gets path to default template (including filename).
getDml3DEffectsRenderingMode()Gets a value determining how 3D effects are rendered.
getDmlEffectsRenderingMode()Gets a value determining how DrawingML effects are rendered.
getDmlRenderingMode()Gets a value determining how DrawingML shapes are rendered.
getEncoding()
getExportGeneratorName()When true , causes the name and version of Aspose.Words to be embedded into produced files.
getExportHeadersFootersMode()Specifies the way headers and footers are exported to the text formats.
getForcePageBreaks()Allows to specify whether the page breaks should be preserved during export.
getImlRenderingMode()Gets a value determining how ink (InkML) objects are rendered.
getMemoryOptimization()Gets value determining if memory optimization should be performed before saving the document.
getParagraphBreak()Specifies the string to use as a paragraph break when exporting in text formats.
getPrettyFormat()When true , pretty formats output where applicable.
getProgressCallback()Called during saving a document and accepts data about saving progress.
getSaveFormat()Specifies the format in which the document will be saved if this save options object is used.
getTempFolder()Specifies the folder for temporary files used when saving to a DOC or DOCX file.
getUpdateCreatedTimeProperty()Gets a value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving.
getUpdateFields()Gets a value determining if fields of certain types should be updated before saving the document to a fixed page format.
getUpdateLastPrintedProperty()Gets a value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.
getUpdateLastSavedTimeProperty()Gets a value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.
getUpdateSdtContent()Gets value determining whether content of StructuredDocumentTag is updated before saving.
getUseAntiAliasing()Gets a value determining whether or not to use anti-aliasing for rendering.
getUseHighQualityRendering()Gets a value determining whether or not to use high quality (i.e.
setAllowEmbeddingPostScriptFonts(boolean value)Sets a boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved.
setDefaultTemplate(String value)Sets path to default template (including filename).
setDml3DEffectsRenderingMode(int value)Sets a value determining how 3D effects are rendered.
setDmlEffectsRenderingMode(int value)Sets a value determining how DrawingML effects are rendered.
setDmlRenderingMode(int value)Sets a value determining how DrawingML shapes are rendered.
setEncoding(Charset value)
setExportGeneratorName(boolean value)When true , causes the name and version of Aspose.Words to be embedded into produced files.
setExportHeadersFootersMode(int value)Specifies the way headers and footers are exported to the text formats.
setForcePageBreaks(boolean value)Allows to specify whether the page breaks should be preserved during export.
setImlRenderingMode(int value)Sets a value determining how ink (InkML) objects are rendered.
setMemoryOptimization(boolean value)Sets value determining if memory optimization should be performed before saving the document.
setParagraphBreak(String value)Specifies the string to use as a paragraph break when exporting in text formats.
setPrettyFormat(boolean value)When true , pretty formats output where applicable.
setProgressCallback(IDocumentSavingCallback value)Called during saving a document and accepts data about saving progress.
setSaveFormat(int value)Specifies the format in which the document will be saved if this save options object is used.
setTempFolder(String value)Specifies the folder for temporary files used when saving to a DOC or DOCX file.
setUpdateCreatedTimeProperty(boolean value)Sets a value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving.
setUpdateFields(boolean value)Sets a value determining if fields of certain types should be updated before saving the document to a fixed page format.
setUpdateLastPrintedProperty(boolean value)Sets a value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.
setUpdateLastSavedTimeProperty(boolean value)Sets a value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.
setUpdateSdtContent(boolean value)Sets value determining whether content of StructuredDocumentTag is updated before saving.
setUseAntiAliasing(boolean value)Sets a value determining whether or not to use anti-aliasing for rendering.
setUseHighQualityRendering(boolean value)Sets a value determining whether or not to use high quality (i.e.

TxtSaveOptionsBase()

public TxtSaveOptionsBase()

createSaveOptions(int saveFormat)

public static SaveOptions createSaveOptions(int saveFormat)

Parameters:

ParameterTypeDescription
saveFormatint

Returns: SaveOptions

createSaveOptions(String fileName)

public static SaveOptions createSaveOptions(String fileName)

Creates a save options object of a class suitable for the file extension specified in the given file name.

Examples:

Shows how to set a default template for documents that do not have attached templates.


 Document doc = new Document();

 // Enable automatic style updating, but do not attach a template document.
 doc.setAutomaticallyUpdateStyles(true);

 Assert.assertEquals("", doc.getAttachedTemplate());

 // Since there is no template document, the document had nowhere to track style changes.
 // Use a SaveOptions object to automatically set a template
 // if a document that we are saving does not have one.
 SaveOptions options = SaveOptions.createSaveOptions("Document.DefaultTemplate.docx");
 options.setDefaultTemplate(getMyDir() + "Business brochure.dotx");

 doc.save(getArtifactsDir() + "Document.DefaultTemplate.docx", options);
 

Parameters:

ParameterTypeDescription
fileNamejava.lang.StringThe extension of this file name determines the class of the save options object to create.

Returns: SaveOptions - An object of a class that derives from SaveOptions.

getAllowEmbeddingPostScriptFonts()

public boolean getAllowEmbeddingPostScriptFonts()

Gets a boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved. The default value is false .

Remarks:

Note, Word does not embed PostScript fonts, but can open documents with embedded fonts of this type.

This option only works when FontInfoCollection.getEmbedTrueTypeFonts() / FontInfoCollection.setEmbedTrueTypeFonts(boolean) of the DocumentBase.getFontInfos() property is set to true .

Examples:

Shows how to save the document with PostScript font.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setName("PostScriptFont");
 builder.writeln("Some text with PostScript font.");

 // Load the font with PostScript to use in the document.
 MemoryFontSource otf = new MemoryFontSource(DocumentHelper.getBytesFromStream(new FileInputStream(getFontsDir() + "AllegroOpen.otf")));
 doc.setFontSettings(new FontSettings());
 doc.getFontSettings().setFontsSources(new FontSourceBase[]{otf});

 // Embed TrueType fonts.
 doc.getFontInfos().setEmbedTrueTypeFonts(true);

 // Allow embedding PostScript fonts while embedding TrueType fonts.
 // Microsoft Word does not embed PostScript fonts, but can open documents with embedded fonts of this type.
 SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.DOCX);
 saveOptions.setAllowEmbeddingPostScriptFonts(true);

 doc.save(getArtifactsDir() + "Document.AllowEmbeddingPostScriptFonts.docx", saveOptions);
 

Returns: boolean - A boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved.

getDefaultTemplate()

public String getDefaultTemplate()

Gets path to default template (including filename). Default value for this property is empty string.

Remarks:

If specified, this path is used to load template when Document.getAutomaticallyUpdateStyles() / Document.setAutomaticallyUpdateStyles(boolean) is true , but Document.getAttachedTemplate() / Document.setAttachedTemplate(java.lang.String) is empty.

Examples:

Shows how to set a default template for documents that do not have attached templates.


 Document doc = new Document();

 // Enable automatic style updating, but do not attach a template document.
 doc.setAutomaticallyUpdateStyles(true);

 Assert.assertEquals("", doc.getAttachedTemplate());

 // Since there is no template document, the document had nowhere to track style changes.
 // Use a SaveOptions object to automatically set a template
 // if a document that we are saving does not have one.
 SaveOptions options = SaveOptions.createSaveOptions("Document.DefaultTemplate.docx");
 options.setDefaultTemplate(getMyDir() + "Business brochure.dotx");

 doc.save(getArtifactsDir() + "Document.DefaultTemplate.docx", options);
 

Returns: java.lang.String - Path to default template (including filename).

getDml3DEffectsRenderingMode()

public int getDml3DEffectsRenderingMode()

Gets a value determining how 3D effects are rendered.

Remarks:

The default value is Dml3DEffectsRenderingMode.BASIC.

Returns: int - A value determining how 3D effects are rendered. The returned value is one of Dml3DEffectsRenderingMode constants.

getDmlEffectsRenderingMode()

public int getDmlEffectsRenderingMode()

Gets a value determining how DrawingML effects are rendered.

Remarks:

The default value is DmlEffectsRenderingMode.SIMPLIFIED.

This property is used when the document is exported to fixed page formats.

Returns: int - A value determining how DrawingML effects are rendered. The returned value is one of DmlEffectsRenderingMode constants.

getDmlRenderingMode()

public int getDmlRenderingMode()

Gets a value determining how DrawingML shapes are rendered.

Remarks:

The default value is DmlRenderingMode.FALLBACK.

This property is used when the document is exported to fixed page formats.

Returns: int - A value determining how DrawingML shapes are rendered. The returned value is one of DmlRenderingMode constants.

getEncoding()

public Charset getEncoding()

Returns: java.nio.charset.Charset

getExportGeneratorName()

public boolean getExportGeneratorName()

When true , causes the name and version of Aspose.Words to be embedded into produced files. Default value is true .

Examples:

Shows how to disable adding name and version of Aspose.Words into produced files.


 Document doc = new Document();

 // Use https://docs.aspose.com/words/net/generator-or-producer-name-included-in-output-documents/ to know how to check the result.
 OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(); { saveOptions.setExportGeneratorName(false); }

 doc.save(getArtifactsDir() + "OoxmlSaveOptions.ExportGeneratorName.docx", saveOptions);
 

Returns: boolean - The corresponding boolean value.

getExportHeadersFootersMode()

public int getExportHeadersFootersMode()

Specifies the way headers and footers are exported to the text formats. Default value is TxtExportHeadersFootersMode.PRIMARY_ONLY.

Examples:

Shows how to specify how to export headers and footers to plain text format.


 Document doc = new Document();

 // Insert even and primary headers/footers into the document.
 // The primary header/footers will override the even headers/footers.
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_EVEN));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_EVEN).appendParagraph("Even header");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_EVEN));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN).appendParagraph("Even footer");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).appendParagraph("Primary header");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).appendParagraph("Primary footer");

 // Insert pages to display these headers and footers.
 DocumentBuilder builder = new DocumentBuilder(doc);
 builder.writeln("Page 1");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 2");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.write("Page 3");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
 // to modify how we save the document to plaintext.
 TxtSaveOptions saveOptions = new TxtSaveOptions();

 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.None"
 // to not export any headers/footers.
 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.PrimaryOnly"
 // to only export primary headers/footers.
 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.AllAtEnd"
 // to place all headers and footers for all section bodies at the end of the document.
 saveOptions.setExportHeadersFootersMode(txtExportHeadersFootersMode);

 doc.save(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt", saveOptions);

 String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt").getText().trim();

 switch (txtExportHeadersFootersMode) {
     case TxtExportHeadersFootersMode.ALL_AT_END:
         Assert.assertEquals("Page 1\r" +
                 "Page 2\r" +
                 "Page 3\r" +
                 "Even header\r\r" +
                 "Primary header\r\r" +
                 "Even footer\r\r" +
                 "Primary footer", docText);

         break;
     case TxtExportHeadersFootersMode.PRIMARY_ONLY:
         Assert.assertEquals("Primary header\r" +
                 "Page 1\r" +
                 "Page 2\r" +
                 "Page 3\r" +
                 "Primary footer", docText);
         break;
     case TxtExportHeadersFootersMode.NONE:
         Assert.assertEquals("Page 1\r" +
                 "Page 2\r" +
                 "Page 3", docText);
         break;
 }
 

Returns: int - The corresponding int value. The returned value is one of TxtExportHeadersFootersMode constants.

getForcePageBreaks()

public boolean getForcePageBreaks()

Allows to specify whether the page breaks should be preserved during export.

The default value is false .

Remarks:

The property affects only page breaks that are inserted explicitly into a document. It is not related to page breaks that MS Word automatically inserts at the end of each page.

Examples:

Shows how to specify whether to preserve page breaks when exporting a document to plaintext.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.writeln("Page 1");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 2");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 3");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save"
 // method to modify how we save the document to plaintext.
 TxtSaveOptions saveOptions = new TxtSaveOptions();

 // The Aspose.Words "Document" objects have page breaks, just like Microsoft Word documents.
 // Save formats such as ".txt" are one continuous body of text without page breaks.
 // Set the "ForcePageBreaks" property to "true" to preserve all page breaks in the form of '\f' characters.
 // Set the "ForcePageBreaks" property to "false" to discard all page breaks.
 saveOptions.setForcePageBreaks(forcePageBreaks);

 doc.save(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt", saveOptions);

 // If we load a plaintext document with page breaks,
 // the "Document" object will use them to split the body into pages.
 doc = new Document(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt");

 Assert.assertEquals(forcePageBreaks ? 3 : 1, doc.getPageCount());
 

Returns: boolean - The corresponding boolean value.

getImlRenderingMode()

public int getImlRenderingMode()

Gets a value determining how ink (InkML) objects are rendered.

Remarks:

The default value is ImlRenderingMode.INK_ML.

This property is used when the document is exported to fixed page formats.

Examples:

Shows how to render Ink object.


 Document doc = new Document(getMyDir() + "Ink object.docx");

 // Set 'ImlRenderingMode.InkML' ignores fall-back shape of ink (InkML) object and renders InkML itself.
 // If the rendering result is unsatisfactory,
 // please use 'ImlRenderingMode.Fallback' to get a result similar to previous versions.
 ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.JPEG);
 {
     saveOptions.setImlRenderingMode(ImlRenderingMode.INK_ML);
 }

 doc.save(getArtifactsDir() + "ImageSaveOptions.RenderInkObject.jpeg", saveOptions);
 

Returns: int - A value determining how ink (InkML) objects are rendered. The returned value is one of ImlRenderingMode constants.

getMemoryOptimization()

public boolean getMemoryOptimization()

Gets value determining if memory optimization should be performed before saving the document. Default value for this property is false .

Remarks:

Setting this option to true can significantly decrease memory consumption while saving large documents at the cost of slower saving time.

Returns: boolean - Value determining if memory optimization should be performed before saving the document.

getParagraphBreak()

public String getParagraphBreak()

Specifies the string to use as a paragraph break when exporting in text formats.

Remarks:

The default value is ControlChar.CR_LF.

Examples:

Shows how to save a .txt document with a custom paragraph break.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.writeln("Paragraph 1.");
 builder.writeln("Paragraph 2.");
 builder.write("Paragraph 3.");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
 // to modify how we save the document to plaintext.
 TxtSaveOptions txtSaveOptions = new TxtSaveOptions();

 Assert.assertEquals(SaveFormat.TEXT, txtSaveOptions.getSaveFormat());

 // Set the "ParagraphBreak" to a custom value that we wish to put at the end of every paragraph.
 txtSaveOptions.setParagraphBreak(" End of paragraph.\r\r\t");

 doc.save(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt", txtSaveOptions);

 String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt").getText().trim();

 Assert.assertEquals("Paragraph 1. End of paragraph.\r\r\t" +
         "Paragraph 2. End of paragraph.\r\r\t" +
         "Paragraph 3. End of paragraph.", docText);
 

Returns: java.lang.String - The corresponding java.lang.String value.

getPrettyFormat()

public boolean getPrettyFormat()

When true , pretty formats output where applicable. Default value is false .

Remarks:

Set to true to make HTML, MHTML, EPUB, WordML, RTF, DOCX and ODT output human readable. Useful for testing or debugging.

Examples:

Shows how to enhance the readability of the raw code of a saved .html document.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);
 builder.writeln("Hello world!");

 HtmlSaveOptions htmlOptions = new HtmlSaveOptions(SaveFormat.HTML);
 {
     htmlOptions.setPrettyFormat(usePrettyFormat);
 }

 doc.save(getArtifactsDir() + "HtmlSaveOptions.PrettyFormat.html", htmlOptions);

 // Enabling pretty format makes the raw html code more readable by adding tab stop and new line characters.
 String html = FileUtils.readFileToString(new File(getArtifactsDir() + "HtmlSaveOptions.PrettyFormat.html"), StandardCharsets.UTF_8);

 if (usePrettyFormat)
     Assert.assertEquals(
             "\r\n" +
                     "\t\r\n" +
                     "\t\t\r\n" +
                     "\t\t\r\n" +
                     MessageFormat.format("\t\t\r\n", BuildVersionInfo.getProduct(), BuildVersionInfo.getVersion()) +
                     "\t\t\r\n" +
                     "\t\t\r\n" +
                     "\t\r\n" +
                     "\t\r\n" +
                     "\t\t \r\n" +
                     "\t\t\t \r\n" +
                     "\t\t\t\tHello world!\r\n" +
                     "\t\t\t\r\n" +
                     "\t\t\t \r\n" +
                     "\t\t\t\t\r\n" +
                     "\t\t\t\r\n" +
                     "\t\t\r\n" +
                     "\t\r\n",
             html);
 else
     Assert.assertEquals(
             "" +
                     "" +
                     MessageFormat.format("", BuildVersionInfo.getProduct(), BuildVersionInfo.getVersion()) +
                     "" +
                     " Hello world!" +
                     " ",
             html);
 

Returns: boolean - The corresponding boolean value.

getProgressCallback()

public IDocumentSavingCallback getProgressCallback()

Called during saving a document and accepts data about saving progress.

Remarks:

Progress is reported when saving to SaveFormat.DOCX, SaveFormat.FLAT_OPC, SaveFormat.DOCM, SaveFormat.DOTM, SaveFormat.DOTX, SaveFormat.DOC, SaveFormat.DOT, SaveFormat.HTML, SaveFormat.MHTML, SaveFormat.EPUB, SaveFormat.XAML_FLOW, or SaveFormat.XAML_FLOW_PACK.

Examples:

Shows how to manage a document while saving to xamlflow.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: XamlFlow, XamlFlowPack.
     XamlFlowSaveOptions saveOptions = new XamlFlowSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("XamlFlowSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }
 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.XAML_FLOW,  "xamlflow"},
                     {SaveFormat.XAML_FLOW_PACK,  "xamlflowpack"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Shows how to manage a document while saving to html.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: Html, Mhtml, Epub.
     HtmlSaveOptions saveOptions = new HtmlSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("HtmlSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }

 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.HTML,  "html"},
                     {SaveFormat.MHTML,  "mhtml"},
                     {SaveFormat.EPUB,  "epub"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Shows how to manage a document while saving to docx.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: Docx, FlatOpc, Docm, Dotm, Dotx.
     OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("OoxmlSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }
 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.DOCX,  "docx"},
                     {SaveFormat.DOCM,  "docm"},
                     {SaveFormat.DOTM,  "dotm"},
                     {SaveFormat.DOTX,  "dotx"},
                     {SaveFormat.FLAT_OPC,  "flatopc"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Returns: IDocumentSavingCallback - The corresponding IDocumentSavingCallback value.

getSaveFormat()

public abstract int getSaveFormat()

Specifies the format in which the document will be saved if this save options object is used.

Examples:

Shows how to use a specific encoding when saving a document to .epub.


 Document doc = new Document(getMyDir() + "Rendering.docx");

 // Use a SaveOptions object to specify the encoding for a document that we will save.
 HtmlSaveOptions saveOptions = new HtmlSaveOptions();
 saveOptions.setSaveFormat(SaveFormat.EPUB);
 saveOptions.setEncoding(StandardCharsets.UTF_8);

 // By default, an output .epub document will have all of its contents in one HTML part.
 // A split criterion allows us to segment the document into several HTML parts.
 // We will set the criteria to split the document into heading paragraphs.
 // This is useful for readers who cannot read HTML files more significant than a specific size.
 saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);

 // Specify that we want to export document properties.
 saveOptions.setExportDocumentProperties(true);

 doc.save(getArtifactsDir() + "HtmlSaveOptions.Doc2EpubSaveOptions.epub", saveOptions);
 

Returns: int - The corresponding int value. The returned value is one of SaveFormat constants.

getTempFolder()

public String getTempFolder()

Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.

Remarks:

When Aspose.Words saves a document, it needs to create temporary internal structures. By default, these internal structures are created in memory and the memory usage spikes for a short period while the document is being saved. When saving is complete, the memory is freed and reclaimed by the garbage collector.

If you are saving a very large document (thousands of pages) and/or processing many documents at the same time, then the memory spike during saving can be significant enough to cause the system to throw java.lang.IndexOutOfBoundsException. Specifying a temporary folder using getTempFolder() / setTempFolder(java.lang.String) will cause Aspose.Words to keep the internal structures in temporary files instead of memory. It reduces the memory usage during saving, but will decrease the save performance.

The folder must exist and be writable, otherwise an exception will be thrown.

Aspose.Words automatically deletes all temporary files when saving is complete.

Examples:

Shows how to use the hard drive instead of memory when saving a document.


 Document doc = new Document(getMyDir() + "Rendering.docx");

 // When we save a document, various elements are temporarily stored in memory as the save operation is taking place.
 // We can use this option to use a temporary folder in the local file system instead,
 // which will reduce our application's memory overhead.
 DocSaveOptions options = new DocSaveOptions();
 options.setTempFolder(getArtifactsDir() + "TempFiles");

 // The specified temporary folder must exist in the local file system before the save operation.
 new File(options.getTempFolder()).mkdir();

 doc.save(getArtifactsDir() + "DocSaveOptions.TempFolder.doc", options);

 // The folder will persist with no residual contents from the load operation.
 Assert.assertEquals(new File(options.getTempFolder()).listFiles().length, 0);
 

Returns: java.lang.String - The corresponding java.lang.String value.

getUpdateCreatedTimeProperty()

public boolean getUpdateCreatedTimeProperty()

Gets a value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving. Default value is false ;

Returns: boolean - A value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving.

getUpdateFields()

public boolean getUpdateFields()

Gets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true .

Remarks:

Allows to specify whether to mimic or not MS Word behavior.

Returns: boolean - A value determining if fields of certain types should be updated before saving the document to a fixed page format.

getUpdateLastPrintedProperty()

public boolean getUpdateLastPrintedProperty()

Gets a value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.

Examples:

Shows how to update a document’s “CreatedTime” property when saving.


 Document doc = new Document();

 Calendar calendar = Calendar.getInstance();
 calendar.set(2019, 11, 20);
 doc.getBuiltInDocumentProperties().setCreatedTime(calendar.getTime());

 // This flag determines whether the created time, which is a built-in property, is updated.
 // If so, then the date of the document's most recent save operation
 // with this SaveOptions object passed as a parameter is used as the created time.
 DocSaveOptions saveOptions = new DocSaveOptions();
 saveOptions.setUpdateCreatedTimeProperty(isUpdateCreatedTimeProperty);

 doc.save(getArtifactsDir() + "DocSaveOptions.UpdateCreatedTimeProperty.docx", saveOptions);
 

Shows how to update a document’s “Last printed” property when saving.


 Document doc = new Document();

 Calendar calendar = Calendar.getInstance();
 calendar.set(2019, 11, 20);
 doc.getBuiltInDocumentProperties().setLastPrinted(calendar.getTime());

 // This flag determines whether the last printed date, which is a built-in property, is updated.
 // If so, then the date of the document's most recent save operation
 // with this SaveOptions object passed as a parameter is used as the print date.
 DocSaveOptions saveOptions = new DocSaveOptions();
 saveOptions.setUpdateLastPrintedProperty(isUpdateLastPrintedProperty);

 // In Microsoft Word 2003, this property can be found via File -> Properties -> Statistics -> Printed.
 // It can also be displayed in the document's body by using a PRINTDATE field.
 doc.save(getArtifactsDir() + "DocSaveOptions.UpdateLastPrintedProperty.doc", saveOptions);
 

Returns: boolean - A value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.

getUpdateLastSavedTimeProperty()

public boolean getUpdateLastSavedTimeProperty()

Gets a value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.

Examples:

Shows how to determine whether to preserve the document’s “Last saved time” property when saving.


 Document doc = new Document(getMyDir() + "Document.docx");

 // When we save the document to an OOXML format, we can create an OoxmlSaveOptions object
 // and then pass it to the document's saving method to modify how we save the document.
 // Set the "UpdateLastSavedTimeProperty" property to "true" to
 // set the output document's "Last saved time" built-in property to the current date/time.
 // Set the "UpdateLastSavedTimeProperty" property to "false" to
 // preserve the original value of the input document's "Last saved time" built-in property.
 OoxmlSaveOptions saveOptions = new OoxmlSaveOptions();
 saveOptions.setUpdateLastSavedTimeProperty(updateLastSavedTimeProperty);

 doc.save(getArtifactsDir() + "OoxmlSaveOptions.LastSavedTime.docx", saveOptions);
 

Returns: boolean - A value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.

getUpdateSdtContent()

public boolean getUpdateSdtContent()

Gets value determining whether content of StructuredDocumentTag is updated before saving.

Remarks:

The default value is false .

Examples:

Shows how to update structured document tags while saving a document to PDF.


 Document doc = new Document();

 // Insert a drop-down list structured document tag.
 StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DROP_DOWN_LIST, MarkupLevel.BLOCK);
 tag.getListItems().add(new SdtListItem("Value 1"));
 tag.getListItems().add(new SdtListItem("Value 2"));
 tag.getListItems().add(new SdtListItem("Value 3"));

 // The drop-down list currently displays "Choose an item" as the default text.
 // Set the "SelectedValue" property to one of the list items to get the tag to
 // display that list item's value instead of the default text.
 tag.getListItems().setSelectedValue(tag.getListItems().get(1));

 doc.getFirstSection().getBody().appendChild(tag);

 doc.save(getArtifactsDir() + "StructuredDocumentTag.UpdateSdtContent.pdf");
 

Returns: boolean - Value determining whether content of StructuredDocumentTag is updated before saving.

getUseAntiAliasing()

public boolean getUseAntiAliasing()

Gets a value determining whether or not to use anti-aliasing for rendering.

Remarks:

The default value is false . When this value is set to true anti-aliasing is used for rendering.

This property is used when the document is exported to the following formats: SaveFormat.TIFF, SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG, SaveFormat.EMF. When the document is exported to the SaveFormat.HTML, SaveFormat.MHTML, SaveFormat.EPUB, SaveFormat.AZW_3 or SaveFormat.MOBI formats this option is used for raster images.

Examples:

Shows how to improve the quality of a rendered document with SaveOptions.


 Document doc = new Document(getMyDir() + "Rendering.docx");
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setSize(60.0);
 builder.writeln("Some text.");

 SaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.Default.jpg", options);

 options.setUseAntiAliasing(true);
 options.setUseHighQualityRendering(true);

 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.HighQuality.jpg", options);
 

Returns: boolean - A value determining whether or not to use anti-aliasing for rendering.

getUseHighQualityRendering()

public boolean getUseHighQualityRendering()

Gets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Remarks:

The default value is false .

This property is used when the document is exported to image formats: SaveFormat.TIFF, SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG, SaveFormat.EMF.

Examples:

Shows how to improve the quality of a rendered document with SaveOptions.


 Document doc = new Document(getMyDir() + "Rendering.docx");
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setSize(60.0);
 builder.writeln("Some text.");

 SaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.Default.jpg", options);

 options.setUseAntiAliasing(true);
 options.setUseHighQualityRendering(true);

 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.HighQuality.jpg", options);
 

Returns: boolean - A value determining whether or not to use high quality (i.e.

setAllowEmbeddingPostScriptFonts(boolean value)

public void setAllowEmbeddingPostScriptFonts(boolean value)

Sets a boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved. The default value is false .

Remarks:

Note, Word does not embed PostScript fonts, but can open documents with embedded fonts of this type.

This option only works when FontInfoCollection.getEmbedTrueTypeFonts() / FontInfoCollection.setEmbedTrueTypeFonts(boolean) of the DocumentBase.getFontInfos() property is set to true .

Examples:

Shows how to save the document with PostScript font.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setName("PostScriptFont");
 builder.writeln("Some text with PostScript font.");

 // Load the font with PostScript to use in the document.
 MemoryFontSource otf = new MemoryFontSource(DocumentHelper.getBytesFromStream(new FileInputStream(getFontsDir() + "AllegroOpen.otf")));
 doc.setFontSettings(new FontSettings());
 doc.getFontSettings().setFontsSources(new FontSourceBase[]{otf});

 // Embed TrueType fonts.
 doc.getFontInfos().setEmbedTrueTypeFonts(true);

 // Allow embedding PostScript fonts while embedding TrueType fonts.
 // Microsoft Word does not embed PostScript fonts, but can open documents with embedded fonts of this type.
 SaveOptions saveOptions = SaveOptions.createSaveOptions(SaveFormat.DOCX);
 saveOptions.setAllowEmbeddingPostScriptFonts(true);

 doc.save(getArtifactsDir() + "Document.AllowEmbeddingPostScriptFonts.docx", saveOptions);
 

Parameters:

ParameterTypeDescription
valuebooleanA boolean value indicating whether to allow embedding fonts with PostScript outlines when embedding TrueType fonts in a document upon it is saved.

setDefaultTemplate(String value)

public void setDefaultTemplate(String value)

Sets path to default template (including filename). Default value for this property is empty string.

Remarks:

If specified, this path is used to load template when Document.getAutomaticallyUpdateStyles() / Document.setAutomaticallyUpdateStyles(boolean) is true , but Document.getAttachedTemplate() / Document.setAttachedTemplate(java.lang.String) is empty.

Examples:

Shows how to set a default template for documents that do not have attached templates.


 Document doc = new Document();

 // Enable automatic style updating, but do not attach a template document.
 doc.setAutomaticallyUpdateStyles(true);

 Assert.assertEquals("", doc.getAttachedTemplate());

 // Since there is no template document, the document had nowhere to track style changes.
 // Use a SaveOptions object to automatically set a template
 // if a document that we are saving does not have one.
 SaveOptions options = SaveOptions.createSaveOptions("Document.DefaultTemplate.docx");
 options.setDefaultTemplate(getMyDir() + "Business brochure.dotx");

 doc.save(getArtifactsDir() + "Document.DefaultTemplate.docx", options);
 

Parameters:

ParameterTypeDescription
valuejava.lang.StringPath to default template (including filename).

setDml3DEffectsRenderingMode(int value)

public void setDml3DEffectsRenderingMode(int value)

Sets a value determining how 3D effects are rendered.

Remarks:

The default value is Dml3DEffectsRenderingMode.BASIC.

Parameters:

ParameterTypeDescription
valueintA value determining how 3D effects are rendered. The value must be one of Dml3DEffectsRenderingMode constants.

setDmlEffectsRenderingMode(int value)

public void setDmlEffectsRenderingMode(int value)

Sets a value determining how DrawingML effects are rendered.

Remarks:

The default value is DmlEffectsRenderingMode.SIMPLIFIED.

This property is used when the document is exported to fixed page formats.

Parameters:

ParameterTypeDescription
valueintA value determining how DrawingML effects are rendered. The value must be one of DmlEffectsRenderingMode constants.

setDmlRenderingMode(int value)

public void setDmlRenderingMode(int value)

Sets a value determining how DrawingML shapes are rendered.

Remarks:

The default value is DmlRenderingMode.FALLBACK.

This property is used when the document is exported to fixed page formats.

Parameters:

ParameterTypeDescription
valueintA value determining how DrawingML shapes are rendered. The value must be one of DmlRenderingMode constants.

setEncoding(Charset value)

public void setEncoding(Charset value)

Parameters:

ParameterTypeDescription
valuejava.nio.charset.Charset

setExportGeneratorName(boolean value)

public void setExportGeneratorName(boolean value)

When true , causes the name and version of Aspose.Words to be embedded into produced files. Default value is true .

Examples:

Shows how to disable adding name and version of Aspose.Words into produced files.


 Document doc = new Document();

 // Use https://docs.aspose.com/words/net/generator-or-producer-name-included-in-output-documents/ to know how to check the result.
 OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(); { saveOptions.setExportGeneratorName(false); }

 doc.save(getArtifactsDir() + "OoxmlSaveOptions.ExportGeneratorName.docx", saveOptions);
 

Parameters:

ParameterTypeDescription
valuebooleanThe corresponding boolean value.

setExportHeadersFootersMode(int value)

public void setExportHeadersFootersMode(int value)

Specifies the way headers and footers are exported to the text formats. Default value is TxtExportHeadersFootersMode.PRIMARY_ONLY.

Examples:

Shows how to specify how to export headers and footers to plain text format.


 Document doc = new Document();

 // Insert even and primary headers/footers into the document.
 // The primary header/footers will override the even headers/footers.
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_EVEN));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_EVEN).appendParagraph("Even header");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_EVEN));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_EVEN).appendParagraph("Even footer");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.HEADER_PRIMARY));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.HEADER_PRIMARY).appendParagraph("Primary header");
 doc.getFirstSection().getHeadersFooters().add(new HeaderFooter(doc, HeaderFooterType.FOOTER_PRIMARY));
 doc.getFirstSection().getHeadersFooters().getByHeaderFooterType(HeaderFooterType.FOOTER_PRIMARY).appendParagraph("Primary footer");

 // Insert pages to display these headers and footers.
 DocumentBuilder builder = new DocumentBuilder(doc);
 builder.writeln("Page 1");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 2");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.write("Page 3");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
 // to modify how we save the document to plaintext.
 TxtSaveOptions saveOptions = new TxtSaveOptions();

 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.None"
 // to not export any headers/footers.
 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.PrimaryOnly"
 // to only export primary headers/footers.
 // Set the "ExportHeadersFootersMode" property to "TxtExportHeadersFootersMode.AllAtEnd"
 // to place all headers and footers for all section bodies at the end of the document.
 saveOptions.setExportHeadersFootersMode(txtExportHeadersFootersMode);

 doc.save(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt", saveOptions);

 String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ExportHeadersFooters.txt").getText().trim();

 switch (txtExportHeadersFootersMode) {
     case TxtExportHeadersFootersMode.ALL_AT_END:
         Assert.assertEquals("Page 1\r" +
                 "Page 2\r" +
                 "Page 3\r" +
                 "Even header\r\r" +
                 "Primary header\r\r" +
                 "Even footer\r\r" +
                 "Primary footer", docText);

         break;
     case TxtExportHeadersFootersMode.PRIMARY_ONLY:
         Assert.assertEquals("Primary header\r" +
                 "Page 1\r" +
                 "Page 2\r" +
                 "Page 3\r" +
                 "Primary footer", docText);
         break;
     case TxtExportHeadersFootersMode.NONE:
         Assert.assertEquals("Page 1\r" +
                 "Page 2\r" +
                 "Page 3", docText);
         break;
 }
 

Parameters:

ParameterTypeDescription
valueintThe corresponding int value. The value must be one of TxtExportHeadersFootersMode constants.

setForcePageBreaks(boolean value)

public void setForcePageBreaks(boolean value)

Allows to specify whether the page breaks should be preserved during export.

The default value is false .

Remarks:

The property affects only page breaks that are inserted explicitly into a document. It is not related to page breaks that MS Word automatically inserts at the end of each page.

Examples:

Shows how to specify whether to preserve page breaks when exporting a document to plaintext.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.writeln("Page 1");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 2");
 builder.insertBreak(BreakType.PAGE_BREAK);
 builder.writeln("Page 3");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save"
 // method to modify how we save the document to plaintext.
 TxtSaveOptions saveOptions = new TxtSaveOptions();

 // The Aspose.Words "Document" objects have page breaks, just like Microsoft Word documents.
 // Save formats such as ".txt" are one continuous body of text without page breaks.
 // Set the "ForcePageBreaks" property to "true" to preserve all page breaks in the form of '\f' characters.
 // Set the "ForcePageBreaks" property to "false" to discard all page breaks.
 saveOptions.setForcePageBreaks(forcePageBreaks);

 doc.save(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt", saveOptions);

 // If we load a plaintext document with page breaks,
 // the "Document" object will use them to split the body into pages.
 doc = new Document(getArtifactsDir() + "TxtSaveOptions.PageBreaks.txt");

 Assert.assertEquals(forcePageBreaks ? 3 : 1, doc.getPageCount());
 

Parameters:

ParameterTypeDescription
valuebooleanThe corresponding boolean value.

setImlRenderingMode(int value)

public void setImlRenderingMode(int value)

Sets a value determining how ink (InkML) objects are rendered.

Remarks:

The default value is ImlRenderingMode.INK_ML.

This property is used when the document is exported to fixed page formats.

Examples:

Shows how to render Ink object.


 Document doc = new Document(getMyDir() + "Ink object.docx");

 // Set 'ImlRenderingMode.InkML' ignores fall-back shape of ink (InkML) object and renders InkML itself.
 // If the rendering result is unsatisfactory,
 // please use 'ImlRenderingMode.Fallback' to get a result similar to previous versions.
 ImageSaveOptions saveOptions = new ImageSaveOptions(SaveFormat.JPEG);
 {
     saveOptions.setImlRenderingMode(ImlRenderingMode.INK_ML);
 }

 doc.save(getArtifactsDir() + "ImageSaveOptions.RenderInkObject.jpeg", saveOptions);
 

Parameters:

ParameterTypeDescription
valueintA value determining how ink (InkML) objects are rendered. The value must be one of ImlRenderingMode constants.

setMemoryOptimization(boolean value)

public void setMemoryOptimization(boolean value)

Sets value determining if memory optimization should be performed before saving the document. Default value for this property is false .

Remarks:

Setting this option to true can significantly decrease memory consumption while saving large documents at the cost of slower saving time.

Parameters:

ParameterTypeDescription
valuebooleanValue determining if memory optimization should be performed before saving the document.

setParagraphBreak(String value)

public void setParagraphBreak(String value)

Specifies the string to use as a paragraph break when exporting in text formats.

Remarks:

The default value is ControlChar.CR_LF.

Examples:

Shows how to save a .txt document with a custom paragraph break.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.writeln("Paragraph 1.");
 builder.writeln("Paragraph 2.");
 builder.write("Paragraph 3.");

 // Create a "TxtSaveOptions" object, which we can pass to the document's "Save" method
 // to modify how we save the document to plaintext.
 TxtSaveOptions txtSaveOptions = new TxtSaveOptions();

 Assert.assertEquals(SaveFormat.TEXT, txtSaveOptions.getSaveFormat());

 // Set the "ParagraphBreak" to a custom value that we wish to put at the end of every paragraph.
 txtSaveOptions.setParagraphBreak(" End of paragraph.\r\r\t");

 doc.save(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt", txtSaveOptions);

 String docText = new Document(getArtifactsDir() + "TxtSaveOptions.ParagraphBreak.txt").getText().trim();

 Assert.assertEquals("Paragraph 1. End of paragraph.\r\r\t" +
         "Paragraph 2. End of paragraph.\r\r\t" +
         "Paragraph 3. End of paragraph.", docText);
 

Parameters:

ParameterTypeDescription
valuejava.lang.StringThe corresponding java.lang.String value.

setPrettyFormat(boolean value)

public void setPrettyFormat(boolean value)

When true , pretty formats output where applicable. Default value is false .

Remarks:

Set to true to make HTML, MHTML, EPUB, WordML, RTF, DOCX and ODT output human readable. Useful for testing or debugging.

Examples:

Shows how to enhance the readability of the raw code of a saved .html document.


 Document doc = new Document();
 DocumentBuilder builder = new DocumentBuilder(doc);
 builder.writeln("Hello world!");

 HtmlSaveOptions htmlOptions = new HtmlSaveOptions(SaveFormat.HTML);
 {
     htmlOptions.setPrettyFormat(usePrettyFormat);
 }

 doc.save(getArtifactsDir() + "HtmlSaveOptions.PrettyFormat.html", htmlOptions);

 // Enabling pretty format makes the raw html code more readable by adding tab stop and new line characters.
 String html = FileUtils.readFileToString(new File(getArtifactsDir() + "HtmlSaveOptions.PrettyFormat.html"), StandardCharsets.UTF_8);

 if (usePrettyFormat)
     Assert.assertEquals(
             "\r\n" +
                     "\t\r\n" +
                     "\t\t\r\n" +
                     "\t\t\r\n" +
                     MessageFormat.format("\t\t\r\n", BuildVersionInfo.getProduct(), BuildVersionInfo.getVersion()) +
                     "\t\t\r\n" +
                     "\t\t\r\n" +
                     "\t\r\n" +
                     "\t\r\n" +
                     "\t\t \r\n" +
                     "\t\t\t \r\n" +
                     "\t\t\t\tHello world!\r\n" +
                     "\t\t\t\r\n" +
                     "\t\t\t \r\n" +
                     "\t\t\t\t\r\n" +
                     "\t\t\t\r\n" +
                     "\t\t\r\n" +
                     "\t\r\n",
             html);
 else
     Assert.assertEquals(
             "" +
                     "" +
                     MessageFormat.format("", BuildVersionInfo.getProduct(), BuildVersionInfo.getVersion()) +
                     "" +
                     " Hello world!" +
                     " ",
             html);
 

Parameters:

ParameterTypeDescription
valuebooleanThe corresponding boolean value.

setProgressCallback(IDocumentSavingCallback value)

public void setProgressCallback(IDocumentSavingCallback value)

Called during saving a document and accepts data about saving progress.

Remarks:

Progress is reported when saving to SaveFormat.DOCX, SaveFormat.FLAT_OPC, SaveFormat.DOCM, SaveFormat.DOTM, SaveFormat.DOTX, SaveFormat.DOC, SaveFormat.DOT, SaveFormat.HTML, SaveFormat.MHTML, SaveFormat.EPUB, SaveFormat.XAML_FLOW, or SaveFormat.XAML_FLOW_PACK.

Examples:

Shows how to manage a document while saving to xamlflow.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: XamlFlow, XamlFlowPack.
     XamlFlowSaveOptions saveOptions = new XamlFlowSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("XamlFlowSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }
 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.XAML_FLOW,  "xamlflow"},
                     {SaveFormat.XAML_FLOW_PACK,  "xamlflowpack"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Shows how to manage a document while saving to html.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: Html, Mhtml, Epub.
     HtmlSaveOptions saveOptions = new HtmlSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("HtmlSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }

 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.HTML,  "html"},
                     {SaveFormat.MHTML,  "mhtml"},
                     {SaveFormat.EPUB,  "epub"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Shows how to manage a document while saving to docx.


 public void progressCallback(int saveFormat, String ext) throws Exception
 {
     Document doc = new Document(getMyDir() + "Big document.docx");

     // Following formats are supported: Docx, FlatOpc, Docm, Dotm, Dotx.
     OoxmlSaveOptions saveOptions = new OoxmlSaveOptions(saveFormat);
     {
         saveOptions.setProgressCallback(new SavingProgressCallback());
     }

     try {
         doc.save(getArtifactsDir() + MessageFormat.format("OoxmlSaveOptions.ProgressCallback.{0}", ext), saveOptions);
     }
     catch (IllegalStateException exception) {
         Assert.assertTrue(exception.getMessage().contains("EstimatedProgress"));
     }
 }

 public static Object[][] progressCallbackDataProvider() throws Exception
 {
     return new Object[][]
             {
                     {SaveFormat.DOCX,  "docx"},
                     {SaveFormat.DOCM,  "docm"},
                     {SaveFormat.DOTM,  "dotm"},
                     {SaveFormat.DOTX,  "dotx"},
                     {SaveFormat.FLAT_OPC,  "flatopc"},
             };
 }

 /// 
 /// Saving progress callback. Cancel a document saving after the "MaxDuration" seconds.
 /// 
 public static class SavingProgressCallback implements IDocumentSavingCallback
 {
     /// 
     /// Ctr.
     /// 
     public SavingProgressCallback()
     {
         mSavingStartedAt = new Date();
     }

     /// 
     /// Callback method which called during document saving.
     /// 
     /// Saving arguments.
     public void notify(DocumentSavingArgs args)
     {
         Date canceledAt = new Date();
         long diff = canceledAt.getTime() - mSavingStartedAt.getTime();
         long ellapsedSeconds = TimeUnit.MILLISECONDS.toSeconds(diff);

         if (ellapsedSeconds > MAX_DURATION)
             throw new IllegalStateException(MessageFormat.format("EstimatedProgress = {0}; CanceledAt = {1}", args.getEstimatedProgress(), canceledAt));
     }

     /// 
     /// Date and time when document saving is started.
     /// 
     private Date mSavingStartedAt;

     /// 
     /// Maximum allowed duration in sec.
     /// 
     private static final double MAX_DURATION = 0.01d;
 }
 

Parameters:

ParameterTypeDescription
valueIDocumentSavingCallbackThe corresponding IDocumentSavingCallback value.

setSaveFormat(int value)

public abstract void setSaveFormat(int value)

Specifies the format in which the document will be saved if this save options object is used.

Examples:

Shows how to use a specific encoding when saving a document to .epub.


 Document doc = new Document(getMyDir() + "Rendering.docx");

 // Use a SaveOptions object to specify the encoding for a document that we will save.
 HtmlSaveOptions saveOptions = new HtmlSaveOptions();
 saveOptions.setSaveFormat(SaveFormat.EPUB);
 saveOptions.setEncoding(StandardCharsets.UTF_8);

 // By default, an output .epub document will have all of its contents in one HTML part.
 // A split criterion allows us to segment the document into several HTML parts.
 // We will set the criteria to split the document into heading paragraphs.
 // This is useful for readers who cannot read HTML files more significant than a specific size.
 saveOptions.setDocumentSplitCriteria(DocumentSplitCriteria.HEADING_PARAGRAPH);

 // Specify that we want to export document properties.
 saveOptions.setExportDocumentProperties(true);

 doc.save(getArtifactsDir() + "HtmlSaveOptions.Doc2EpubSaveOptions.epub", saveOptions);
 

Parameters:

ParameterTypeDescription
valueintThe corresponding int value. The value must be one of SaveFormat constants.

setTempFolder(String value)

public void setTempFolder(String value)

Specifies the folder for temporary files used when saving to a DOC or DOCX file. By default this property is null and no temporary files are used.

Remarks:

When Aspose.Words saves a document, it needs to create temporary internal structures. By default, these internal structures are created in memory and the memory usage spikes for a short period while the document is being saved. When saving is complete, the memory is freed and reclaimed by the garbage collector.

If you are saving a very large document (thousands of pages) and/or processing many documents at the same time, then the memory spike during saving can be significant enough to cause the system to throw java.lang.IndexOutOfBoundsException. Specifying a temporary folder using getTempFolder() / setTempFolder(java.lang.String) will cause Aspose.Words to keep the internal structures in temporary files instead of memory. It reduces the memory usage during saving, but will decrease the save performance.

The folder must exist and be writable, otherwise an exception will be thrown.

Aspose.Words automatically deletes all temporary files when saving is complete.

Examples:

Shows how to use the hard drive instead of memory when saving a document.


 Document doc = new Document(getMyDir() + "Rendering.docx");

 // When we save a document, various elements are temporarily stored in memory as the save operation is taking place.
 // We can use this option to use a temporary folder in the local file system instead,
 // which will reduce our application's memory overhead.
 DocSaveOptions options = new DocSaveOptions();
 options.setTempFolder(getArtifactsDir() + "TempFiles");

 // The specified temporary folder must exist in the local file system before the save operation.
 new File(options.getTempFolder()).mkdir();

 doc.save(getArtifactsDir() + "DocSaveOptions.TempFolder.doc", options);

 // The folder will persist with no residual contents from the load operation.
 Assert.assertEquals(new File(options.getTempFolder()).listFiles().length, 0);
 

Parameters:

ParameterTypeDescription
valuejava.lang.StringThe corresponding java.lang.String value.

setUpdateCreatedTimeProperty(boolean value)

public void setUpdateCreatedTimeProperty(boolean value)

Sets a value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving. Default value is false ;

Parameters:

ParameterTypeDescription
valuebooleanA value determining whether the BuiltInDocumentProperties.getCreatedTime() / BuiltInDocumentProperties.setCreatedTime(java.util.Date) property is updated before saving.

setUpdateFields(boolean value)

public void setUpdateFields(boolean value)

Sets a value determining if fields of certain types should be updated before saving the document to a fixed page format. Default value for this property is true .

Remarks:

Allows to specify whether to mimic or not MS Word behavior.

Parameters:

ParameterTypeDescription
valuebooleanA value determining if fields of certain types should be updated before saving the document to a fixed page format.

setUpdateLastPrintedProperty(boolean value)

public void setUpdateLastPrintedProperty(boolean value)

Sets a value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.

Examples:

Shows how to update a document’s “CreatedTime” property when saving.


 Document doc = new Document();

 Calendar calendar = Calendar.getInstance();
 calendar.set(2019, 11, 20);
 doc.getBuiltInDocumentProperties().setCreatedTime(calendar.getTime());

 // This flag determines whether the created time, which is a built-in property, is updated.
 // If so, then the date of the document's most recent save operation
 // with this SaveOptions object passed as a parameter is used as the created time.
 DocSaveOptions saveOptions = new DocSaveOptions();
 saveOptions.setUpdateCreatedTimeProperty(isUpdateCreatedTimeProperty);

 doc.save(getArtifactsDir() + "DocSaveOptions.UpdateCreatedTimeProperty.docx", saveOptions);
 

Shows how to update a document’s “Last printed” property when saving.


 Document doc = new Document();

 Calendar calendar = Calendar.getInstance();
 calendar.set(2019, 11, 20);
 doc.getBuiltInDocumentProperties().setLastPrinted(calendar.getTime());

 // This flag determines whether the last printed date, which is a built-in property, is updated.
 // If so, then the date of the document's most recent save operation
 // with this SaveOptions object passed as a parameter is used as the print date.
 DocSaveOptions saveOptions = new DocSaveOptions();
 saveOptions.setUpdateLastPrintedProperty(isUpdateLastPrintedProperty);

 // In Microsoft Word 2003, this property can be found via File -> Properties -> Statistics -> Printed.
 // It can also be displayed in the document's body by using a PRINTDATE field.
 doc.save(getArtifactsDir() + "DocSaveOptions.UpdateLastPrintedProperty.doc", saveOptions);
 

Parameters:

ParameterTypeDescription
valuebooleanA value determining whether the BuiltInDocumentProperties.getLastPrinted() / BuiltInDocumentProperties.setLastPrinted(java.util.Date) property is updated before saving.

setUpdateLastSavedTimeProperty(boolean value)

public void setUpdateLastSavedTimeProperty(boolean value)

Sets a value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.

Examples:

Shows how to determine whether to preserve the document’s “Last saved time” property when saving.


 Document doc = new Document(getMyDir() + "Document.docx");

 // When we save the document to an OOXML format, we can create an OoxmlSaveOptions object
 // and then pass it to the document's saving method to modify how we save the document.
 // Set the "UpdateLastSavedTimeProperty" property to "true" to
 // set the output document's "Last saved time" built-in property to the current date/time.
 // Set the "UpdateLastSavedTimeProperty" property to "false" to
 // preserve the original value of the input document's "Last saved time" built-in property.
 OoxmlSaveOptions saveOptions = new OoxmlSaveOptions();
 saveOptions.setUpdateLastSavedTimeProperty(updateLastSavedTimeProperty);

 doc.save(getArtifactsDir() + "OoxmlSaveOptions.LastSavedTime.docx", saveOptions);
 

Parameters:

ParameterTypeDescription
valuebooleanA value determining whether the BuiltInDocumentProperties.getLastSavedTime() / BuiltInDocumentProperties.setLastSavedTime(java.util.Date) property is updated before saving.

setUpdateSdtContent(boolean value)

public void setUpdateSdtContent(boolean value)

Sets value determining whether content of StructuredDocumentTag is updated before saving.

Remarks:

The default value is false .

Examples:

Shows how to update structured document tags while saving a document to PDF.


 Document doc = new Document();

 // Insert a drop-down list structured document tag.
 StructuredDocumentTag tag = new StructuredDocumentTag(doc, SdtType.DROP_DOWN_LIST, MarkupLevel.BLOCK);
 tag.getListItems().add(new SdtListItem("Value 1"));
 tag.getListItems().add(new SdtListItem("Value 2"));
 tag.getListItems().add(new SdtListItem("Value 3"));

 // The drop-down list currently displays "Choose an item" as the default text.
 // Set the "SelectedValue" property to one of the list items to get the tag to
 // display that list item's value instead of the default text.
 tag.getListItems().setSelectedValue(tag.getListItems().get(1));

 doc.getFirstSection().getBody().appendChild(tag);

 doc.save(getArtifactsDir() + "StructuredDocumentTag.UpdateSdtContent.pdf");
 

Parameters:

ParameterTypeDescription
valuebooleanValue determining whether content of StructuredDocumentTag is updated before saving.

setUseAntiAliasing(boolean value)

public void setUseAntiAliasing(boolean value)

Sets a value determining whether or not to use anti-aliasing for rendering.

Remarks:

The default value is false . When this value is set to true anti-aliasing is used for rendering.

This property is used when the document is exported to the following formats: SaveFormat.TIFF, SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG, SaveFormat.EMF. When the document is exported to the SaveFormat.HTML, SaveFormat.MHTML, SaveFormat.EPUB, SaveFormat.AZW_3 or SaveFormat.MOBI formats this option is used for raster images.

Examples:

Shows how to improve the quality of a rendered document with SaveOptions.


 Document doc = new Document(getMyDir() + "Rendering.docx");
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setSize(60.0);
 builder.writeln("Some text.");

 SaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.Default.jpg", options);

 options.setUseAntiAliasing(true);
 options.setUseHighQualityRendering(true);

 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.HighQuality.jpg", options);
 

Parameters:

ParameterTypeDescription
valuebooleanA value determining whether or not to use anti-aliasing for rendering.

setUseHighQualityRendering(boolean value)

public void setUseHighQualityRendering(boolean value)

Sets a value determining whether or not to use high quality (i.e. slow) rendering algorithms.

Remarks:

The default value is false .

This property is used when the document is exported to image formats: SaveFormat.TIFF, SaveFormat.PNG, SaveFormat.BMP, SaveFormat.JPEG, SaveFormat.EMF.

Examples:

Shows how to improve the quality of a rendered document with SaveOptions.


 Document doc = new Document(getMyDir() + "Rendering.docx");
 DocumentBuilder builder = new DocumentBuilder(doc);

 builder.getFont().setSize(60.0);
 builder.writeln("Some text.");

 SaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);
 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.Default.jpg", options);

 options.setUseAntiAliasing(true);
 options.setUseHighQualityRendering(true);

 doc.save(getArtifactsDir() + "Document.ImageSaveOptions.HighQuality.jpg", options);
 

Parameters:

ParameterTypeDescription
valuebooleanA value determining whether or not to use high quality (i.e.