Class LoadOptions

Class LoadOptions

Namespace: Aspose.Words.Loading
Assembly: Aspose.Words.dll (25.12.0)

Allows to specify additional options (such as password or base URI) when loading a document into a Aspose.Words.Document object.

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

public class LoadOptions

Inheritance

object LoadOptions

Derived

ChmLoadOptions , HtmlLoadOptions , MarkdownLoadOptions , PdfLoadOptions , RtfLoadOptions , TxtLoadOptions

Inherited Members

object.GetType() , object.MemberwiseClone() , object.ToString() , object.Equals(object?) , object.Equals(object?, object?) , object.ReferenceEquals(object?, object?) , object.GetHashCode()

Examples

Shows how to load an encrypted Microsoft Word document.

Document doc;

                                                                  // Aspose.Words throw an exception if we try to open an encrypted document without its password.
                                                                  Assert.Throws<IncorrectPasswordException>(() => doc = new Document(MyDir + "Encrypted.docx"));

                                                                  // When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
                                                                  LoadOptions options = new LoadOptions("docPassword");

                                                                  // There are two ways of loading an encrypted document with a LoadOptions object.
                                                                  // 1 -  Load the document from the local file system by filename:
                                                                  doc = new Document(MyDir + "Encrypted.docx", options);
                                                                  // 2 -  Load the document from a stream:
                                                                  using (Stream stream = File.OpenRead(MyDir + "Encrypted.docx"))
                                                                  {
                                                                      doc = new Document(stream, options);
                                                                  }

Constructors

LoadOptions()

Initializes a new instance of this class with default values.

public LoadOptions()

Examples

Shows how to open an HTML document with images from a stream using a base URI.

using (Stream stream = File.OpenRead(MyDir + "Document.html"))
                                                                                         {
                                                                                             // Pass the URI of the base folder while loading it
                                                                                             // so that any images with relative URIs in the HTML document can be found.
                                                                                             LoadOptions loadOptions = new LoadOptions();
                                                                                             loadOptions.BaseUri = ImageDir;

                                                                                             Document doc = new Document(stream, loadOptions);

                                                                                             // Verify that the first shape of the document contains a valid image.
                                                                                             Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

                                                                                             Assert.That(shape.IsImage, Is.True);
                                                                                             Assert.That(shape.ImageData.ImageBytes, Is.Not.Null);
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Width), Is.EqualTo(32.0).Within(0.01));
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Height), Is.EqualTo(32.0).Within(0.01));
                                                                                         }

LoadOptions(string)

A shortcut to initialize a new instance of this class with the specified password to load an encrypted document.

public LoadOptions(string password)

Parameters

password string

The password to open an encrypted document. Can be null or empty string.

Examples

Shows how to load an encrypted Microsoft Word document.

Document doc;

                                                                  // Aspose.Words throw an exception if we try to open an encrypted document without its password.
                                                                  Assert.Throws<IncorrectPasswordException>(() => doc = new Document(MyDir + "Encrypted.docx"));

                                                                  // When loading such a document, the password is passed to the document's constructor using a LoadOptions object.
                                                                  LoadOptions options = new LoadOptions("docPassword");

                                                                  // There are two ways of loading an encrypted document with a LoadOptions object.
                                                                  // 1 -  Load the document from the local file system by filename:
                                                                  doc = new Document(MyDir + "Encrypted.docx", options);
                                                                  // 2 -  Load the document from a stream:
                                                                  using (Stream stream = File.OpenRead(MyDir + "Encrypted.docx"))
                                                                  {
                                                                      doc = new Document(stream, options);
                                                                  }

LoadOptions(LoadFormat, string, string)

A shortcut to initialize a new instance of this class with properties set to the specified values.

public LoadOptions(LoadFormat loadFormat, string password, string baseUri)

Parameters

loadFormat LoadFormat

The format of the document to be loaded.

password string

The password to open an encrypted document. Can be null or empty string.

baseUri string

The string that will be used to resolve relative URIs to absolute. Can be null or empty string.

Examples

Shows how save a web page as a .docx file.

const string url = "https://products.aspose.com/words/";

                                                     using (HttpClient client = new HttpClient())
                                                     {
                                                         byte[] bytes = client.GetByteArrayAsync(url).GetAwaiter().GetResult();

                                                         using (MemoryStream stream = new MemoryStream(bytes))
                                                         {
                                                             // The URL is used again as a baseUri to ensure that any relative image paths are retrieved correctly.
                                                             LoadOptions options = new LoadOptions(LoadFormat.Html, "", url);

                                                             // Load the HTML document from stream and pass the LoadOptions object.
                                                             Document doc = new Document(stream, options);

                                                             // At this stage, we can read and edit the document's contents and then save it to the local file system.
                                                             doc.Save(ArtifactsDir + "Document.InsertHtmlFromWebPage.docx");
                                                         }
                                                     }

Shows how to specify a base URI when opening an html document.

// Suppose we want to load an .html document that contains an image linked by a relative URI
                                                                         // while the image is in a different location. In that case, we will need to resolve the relative URI into an absolute one.
                                                                         // We can provide a base URI using an HtmlLoadOptions object. 
                                                                         HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html, "", ImageDir);

                                                                         Assert.That(loadOptions.LoadFormat, Is.EqualTo(LoadFormat.Html));

                                                                         Document doc = new Document(MyDir + "Missing image.html", loadOptions);

                                                                         // While the image was broken in the input .html, our custom base URI helped us repair the link.
                                                                         Shape imageShape = (Shape)doc.GetChildNodes(NodeType.Shape, true)[0];
                                                                         Assert.That(imageShape.IsImage, Is.True);

                                                                         // This output document will display the image that was missing.
                                                                         doc.Save(ArtifactsDir + "HtmlLoadOptions.BaseUri.docx");

Properties

BaseUri

Gets or sets the string that will be used to resolve relative URIs found in the document into absolute URIs when required. Can be null or empty string. Default is null.

public string BaseUri { get; set; }

Property Value

string

Examples

Shows how to open an HTML document with images from a stream using a base URI.

using (Stream stream = File.OpenRead(MyDir + "Document.html"))
                                                                                         {
                                                                                             // Pass the URI of the base folder while loading it
                                                                                             // so that any images with relative URIs in the HTML document can be found.
                                                                                             LoadOptions loadOptions = new LoadOptions();
                                                                                             loadOptions.BaseUri = ImageDir;

                                                                                             Document doc = new Document(stream, loadOptions);

                                                                                             // Verify that the first shape of the document contains a valid image.
                                                                                             Shape shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

                                                                                             Assert.That(shape.IsImage, Is.True);
                                                                                             Assert.That(shape.ImageData.ImageBytes, Is.Not.Null);
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Width), Is.EqualTo(32.0).Within(0.01));
                                                                                             Assert.That(ConvertUtil.PointToPixel(shape.Height), Is.EqualTo(32.0).Within(0.01));
                                                                                         }

Remarks

This property is used to resolve relative URIs into absolute in the following cases:

  1. When loading an HTML document from a stream and the document contains images with relative URIs and does not have a base URI specified in the BASE HTML element.
  2. When saving a document to PDF and other formats, to retrieve images linked using relative URIs so the images can be saved into the output document.

ConvertMetafilesToPng

Gets or sets whether to convert metafile(Aspose.FileFormat.Wmf or Aspose.FileFormat.Emf) images to Aspose.FileFormat.Png image format.

public bool ConvertMetafilesToPng { get; set; }

Property Value

bool

Examples

Shows how to convert WMF/EMF to PNG during loading document.

Document doc = new Document();

                                                                       Shape shape = new Shape(doc, ShapeType.Image);
                                                                       shape.ImageData.SetImage(ImageDir + "Windows MetaFile.wmf");
                                                                       shape.Width = 100;
                                                                       shape.Height = 100;

                                                                       doc.FirstSection.Body.FirstParagraph.AppendChild(shape);

                                                                       doc.Save(ArtifactsDir + "Image.CreateImageDirectly.docx");

                                                                       shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

                                                                       TestUtil.VerifyImageInShape(1600, 1600, ImageType.Wmf, shape);

                                                                       LoadOptions loadOptions = new LoadOptions();
                                                                       loadOptions.ConvertMetafilesToPng = true;

                                                                       doc = new Document(ArtifactsDir + "Image.CreateImageDirectly.docx", loadOptions);
                                                                       shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);

                                                                       TestUtil.VerifyImageInShape(1666, 1666, ImageType.Png, shape);

Remarks

Metafiles (Aspose.FileFormat.Wmf or Aspose.FileFormat.Emf) is an uncompressed image format and sometimes requires to much RAM to hold and process document. This option allows to convert all metafile images to Aspose.FileFormat.Png on document loading. Please note - conversion vector graphics to raster decreases quality of the images.

ConvertShapeToOfficeMath

Gets or sets whether to convert shapes with EquationXML to Office Math objects.

public bool ConvertShapeToOfficeMath { get; set; }

Property Value

bool

Examples

Shows how to convert EquationXML shapes to Office Math objects.

LoadOptions loadOptions = new LoadOptions();

                                                                          // Use this flag to specify whether to convert the shapes with EquationXML attributes
                                                                          // to Office Math objects and then load the document.
                                                                          loadOptions.ConvertShapeToOfficeMath = isConvertShapeToOfficeMath;

                                                                          Document doc = new Document(MyDir + "Math shapes.docx", loadOptions);

                                                                          if (isConvertShapeToOfficeMath)
                                                                          {
                                                                              Assert.That(doc.GetChildNodes(NodeType.Shape, true).Count, Is.EqualTo(16));
                                                                              Assert.That(doc.GetChildNodes(NodeType.OfficeMath, true).Count, Is.EqualTo(34));
                                                                          }
                                                                          else
                                                                          {
                                                                              Assert.That(doc.GetChildNodes(NodeType.Shape, true).Count, Is.EqualTo(24));
                                                                              Assert.That(doc.GetChildNodes(NodeType.OfficeMath, true).Count, Is.EqualTo(0));
                                                                          }

Encoding

Gets or sets the encoding that will be used to load an HTML, TXT, or CHM document if the encoding is not specified inside the document. Can be null. Default is null.

public Encoding Encoding { get; set; }

Property Value

Encoding

Examples

Shows how to set the encoding with which to open a document.

LoadOptions loadOptions = new LoadOptions
                                                                       {
                                                                           Encoding = Encoding.ASCII
                                                                       };

                                                                       // Load the document while passing the LoadOptions object, then verify the document's contents.
                                                                       Document doc = new Document(MyDir + "English text.txt", loadOptions);

                                                                       Assert.That(doc.ToString(SaveFormat.Text).Contains("This is a sample text in English."), Is.True);

Remarks

This property is used only when loading HTML, TXT, or CHM documents.

If encoding is not specified inside the document and this property is null, then the system will try to automatically detect the encoding.

FontSettings

Allows to specify document font settings.

public FontSettings FontSettings { get; set; }

Property Value

FontSettings

Examples

Shows how to apply font substitution settings while loading a document.

// Create a FontSettings object that will substitute the "Times New Roman" font
                                                                                  // with the font "Arvo" from our "MyFonts" folder.
                                                                                  FontSettings fontSettings = new FontSettings();
                                                                                  fontSettings.SetFontsFolder(FontsDir, false);
                                                                                  fontSettings.SubstitutionSettings.TableSubstitution.AddSubstitutes("Times New Roman", "Arvo");

                                                                                  // Set that FontSettings object as a property of a newly created LoadOptions object.
                                                                                  LoadOptions loadOptions = new LoadOptions();
                                                                                  loadOptions.FontSettings = fontSettings;

                                                                                  // Load the document, then render it as a PDF with the font substitution.
                                                                                  Document doc = new Document(MyDir + "Document.docx", loadOptions);

                                                                                  doc.Save(ArtifactsDir + "LoadOptions.FontSettings.pdf");

Shows how to designate font substitutes during loading.

LoadOptions loadOptions = new LoadOptions();
                                                                  loadOptions.FontSettings = new FontSettings();

                                                                  // Set a font substitution rule for a LoadOptions object.
                                                                  // If the document we are loading uses a font which we do not have,
                                                                  // this rule will substitute the unavailable font with one that does exist.
                                                                  // In this case, all uses of the "MissingFont" will convert to "Comic Sans MS".
                                                                  TableSubstitutionRule substitutionRule = loadOptions.FontSettings.SubstitutionSettings.TableSubstitution;
                                                                  substitutionRule.AddSubstitutes("MissingFont", "Comic Sans MS");

                                                                  Document doc = new Document(MyDir + "Missing font.html", loadOptions);

                                                                  // At this point such text will still be in "MissingFont".
                                                                  // Font substitution will take place when we render the document.
                                                                  Assert.That(doc.FirstSection.Body.FirstParagraph.Runs[0].Font.Name, Is.EqualTo("MissingFont"));

                                                                  doc.Save(ArtifactsDir + "FontSettings.ResolveFontsBeforeLoadingDocument.pdf");

Remarks

When loading some formats, Aspose.Words may require to resolve the fonts. For example, when loading HTML documents Aspose.Words may resolve the fonts to perform font fallback.

If set to null, default static font settings Aspose.Words.Fonts.FontSettings.DefaultInstance will be used.

The default value is null.

IgnoreOleData

Specifies whether to ignore the OLE data.

public bool IgnoreOleData { get; set; }

Property Value

bool

Examples

Shows how to ingore OLE data while loading.

// Ignoring OLE data may reduce memory consumption and increase performance
                                                      // without data lost in a case when destination format does not support OLE objects.
                                                      LoadOptions loadOptions = new LoadOptions() { IgnoreOleData = true };
                                                      Document doc = new Document(MyDir + "OLE objects.docx", loadOptions);

                                                      doc.Save(ArtifactsDir + "LoadOptions.IgnoreOleData.docx");

Remarks

Ignoring OLE data may reduce memory consumption and increase performance without data lost in a case when destination format does not support OLE objects.

The default value is false.

LanguagePreferences

Gets language preferences that will be used when document is loading.

public LanguagePreferences LanguagePreferences { get; }

Property Value

LanguagePreferences

Examples

Shows how to apply language preferences when loading a document.

LoadOptions loadOptions = new LoadOptions();
                                                                           loadOptions.LanguagePreferences.AddEditingLanguage(EditingLanguage.Japanese);

                                                                           Document doc = new Document(MyDir + "No default editing language.docx", loadOptions);

                                                                           int localeIdFarEast = doc.Styles.DefaultFont.LocaleIdFarEast;
                                                                           Console.WriteLine(localeIdFarEast == (int)EditingLanguage.Japanese
                                                                               ? "The document either has no any FarEast language set in defaults or it was set to Japanese originally."
                                                                               : "The document default FarEast language was set to another than Japanese language originally, so it is not overridden.");

LoadFormat

Specifies the format of the document to be loaded. Default is Aspose.Words.LoadFormat.Auto.

public LoadFormat LoadFormat { get; set; }

Property Value

LoadFormat

Examples

Shows how to specify a base URI when opening an html document.

// Suppose we want to load an .html document that contains an image linked by a relative URI
                                                                         // while the image is in a different location. In that case, we will need to resolve the relative URI into an absolute one.
                                                                         // We can provide a base URI using an HtmlLoadOptions object. 
                                                                         HtmlLoadOptions loadOptions = new HtmlLoadOptions(LoadFormat.Html, "", ImageDir);

                                                                         Assert.That(loadOptions.LoadFormat, Is.EqualTo(LoadFormat.Html));

                                                                         Document doc = new Document(MyDir + "Missing image.html", loadOptions);

                                                                         // While the image was broken in the input .html, our custom base URI helped us repair the link.
                                                                         Shape imageShape = (Shape)doc.GetChildNodes(NodeType.Shape, true)[0];
                                                                         Assert.That(imageShape.IsImage, Is.True);

                                                                         // This output document will display the image that was missing.
                                                                         doc.Save(ArtifactsDir + "HtmlLoadOptions.BaseUri.docx");

Remarks

It is recommended that you specify the Aspose.Words.LoadFormat.Auto value and let Aspose.Words detect the file format automatically. If you know the format of the document you are about to load, you can specify the format explicitly and this will slightly reduce the loading time by the overhead associated with auto detecting the format. If you specify an explicit load format and it will turn out to be wrong, the auto detection will be invoked and a second attempt to load the file will be made.

MswVersion

Allows to specify that the document loading process should match a specific MS Word version. Default value is Aspose.Words.Settings.MsWordVersion.Word2019

public MsWordVersion MswVersion { get; set; }

Property Value

MsWordVersion

Examples

Shows how to emulate the loading procedure of a specific Microsoft Word version during document loading.

// By default, Aspose.Words load documents according to Microsoft Word 2019 specification.
                                                                                                                   LoadOptions loadOptions = new LoadOptions();

                                                                                                                   Assert.That(loadOptions.MswVersion, Is.EqualTo(MsWordVersion.Word2019));

                                                                                                                   // This document is missing the default paragraph formatting style.
                                                                                                                   // This default style will be regenerated when we load the document either with Microsoft Word or Aspose.Words.
                                                                                                                   loadOptions.MswVersion = MsWordVersion.Word2007;
                                                                                                                   Document doc = new Document(MyDir + "Document.docx", loadOptions);

                                                                                                                   // The style's line spacing will have this value when loaded by Microsoft Word 2007 specification.
                                                                                                                   Assert.That(doc.Styles.DefaultParagraphFormat.LineSpacing, Is.EqualTo(12.95d).Within(0.01d));

Remarks

Different Word versions may handle certain aspects of document content and formatting slightly differently during the loading process, which may result in minor differences in Document Object Model.

Password

Gets or sets the password for opening an encrypted document. Can be null or empty string. Default is null.

public string Password { get; set; }

Property Value

string

Examples

Shows how to sign encrypted document file.

// Create an X.509 certificate from a PKCS#12 store, which should contain a private key.
                                                     CertificateHolder certificateHolder = CertificateHolder.Create(MyDir + "morzal.pfx", "aw");

                                                     // Create a comment, date, and decryption password which will be applied with our new digital signature.
                                                     SignOptions signOptions = new SignOptions
                                                     {
                                                         Comments = "Comment",
                                                         SignTime = DateTime.Now,
                                                         DecryptionPassword = "docPassword"
                                                     };

                                                     // Set a local system filename for the unsigned input document, and an output filename for its new digitally signed copy.
                                                     string inputFileName = MyDir + "Encrypted.docx";
                                                     string outputFileName = ArtifactsDir + "DigitalSignatureUtil.DecryptionPassword.docx";

                                                     DigitalSignatureUtil.Sign(inputFileName, outputFileName, certificateHolder, signOptions);

Remarks

You need to know the password to open an encrypted document. If the document is not encrypted, set this to null or empty string.

PreserveIncludePictureField

Gets or sets whether to preserve the INCLUDEPICTURE field when reading Microsoft Word formats. The default value is false.

public bool PreserveIncludePictureField { get; set; }

Property Value

bool

Examples

Shows how to preserve or discard INCLUDEPICTURE fields when loading a document.

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

                                                                                          FieldIncludePicture includePicture = (FieldIncludePicture)builder.InsertField(FieldType.FieldIncludePicture, true);
                                                                                          includePicture.SourceFullName = ImageDir + "Transparent background logo.png";
                                                                                          includePicture.Update(true);

                                                                                          using (MemoryStream docStream = new MemoryStream())
                                                                                          {
                                                                                              doc.Save(docStream, new OoxmlSaveOptions(SaveFormat.Docx));

                                                                                              // We can set a flag in a LoadOptions object to decide whether to convert all INCLUDEPICTURE fields
                                                                                              // into image shapes when loading a document that contains them.
                                                                                              LoadOptions loadOptions = new LoadOptions
                                                                                              {
                                                                                                  PreserveIncludePictureField = preserveIncludePictureField
                                                                                              };

                                                                                              doc = new Document(docStream, loadOptions);

                                                                                              if (preserveIncludePictureField)
                                                                                              {
                                                                                                  Assert.That(doc.Range.Fields.Any(f => f.Type == FieldType.FieldIncludePicture), Is.True);

                                                                                                  doc.UpdateFields();
                                                                                                  doc.Save(ArtifactsDir + "Field.PreserveIncludePicture.docx");
                                                                                              }
                                                                                              else
                                                                                              {
                                                                                                  Assert.That(doc.Range.Fields.Any(f => f.Type == FieldType.FieldIncludePicture), Is.False);
                                                                                              }
                                                                                          }

Remarks

By default, the INCLUDEPICTURE field is converted into a shape object. You can override that if you need the field to be preserved, for example, if you wish to update it programmatically. Note however that this approach is not common for Aspose.Words. Use it on your own risk.

One of the possible use cases may be using a MERGEFIELD as a child field to dynamically change the source path of the picture. In this case you need the INCLUDEPICTURE to be preserved in the model.

ProgressCallback

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

public IDocumentLoadingCallback ProgressCallback { get; set; }

Property Value

IDocumentLoadingCallback

Examples

Shows how to notify the user if document loading exceeded expected loading time.

public void ProgressCallback()
                                                                                           {
                                                                                               LoadingProgressCallback progressCallback = new LoadingProgressCallback();

                                                                                               LoadOptions loadOptions = new LoadOptions { ProgressCallback = progressCallback };

                                                                                               try
                                                                                               {
                                                                                                   Document doc = new Document(MyDir + "Big document.docx", loadOptions);
                                                                                               }
                                                                                               catch (OperationCanceledException exception)
                                                                                               {
                                                                                                   Console.WriteLine(exception.Message);

                                                                                                   // Handle loading duration issue.
                                                                                               }
                                                                                           }

                                                                                           /// <summary>
                                                                                           /// Cancel a document loading after the "MaxDuration" seconds.
                                                                                           /// </summary>
                                                                                           public class LoadingProgressCallback : IDocumentLoadingCallback
                                                                                           {
                                                                                               /// <summary>
                                                                                               /// Ctr.
                                                                                               /// </summary>
                                                                                               public LoadingProgressCallback()
                                                                                               {
                                                                                                   mLoadingStartedAt = DateTime.Now;
                                                                                               }

                                                                                               /// <summary>
                                                                                               /// Callback method which called during document loading.
                                                                                               /// </summary>
                                                                                               /// <param name="args">Loading arguments.</param>
                                                                                               public void Notify(DocumentLoadingArgs args)
                                                                                               {
                                                                                                   DateTime canceledAt = DateTime.Now;
                                                                                                   double ellapsedSeconds = (canceledAt - mLoadingStartedAt).TotalSeconds;

                                                                                                   if (ellapsedSeconds > MaxDuration)
                                                                                                       throw new OperationCanceledException($"EstimatedProgress = {args.EstimatedProgress}; CanceledAt = {canceledAt}");
                                                                                               }

                                                                                               /// <summary>
                                                                                               /// Date and time when document loading is started.
                                                                                               /// </summary>
                                                                                               private readonly DateTime mLoadingStartedAt;

                                                                                               /// <summary>
                                                                                               /// Maximum allowed duration in sec.
                                                                                               /// </summary>
                                                                                               private const double MaxDuration = 0.5;
                                                                                           }

Remarks

Aspose.Words.LoadFormat.Docx, Aspose.Words.LoadFormat.FlatOpc, Aspose.Words.LoadFormat.Docm, Aspose.Words.LoadFormat.Dotm, Aspose.Words.LoadFormat.Dotx, Aspose.Words.LoadFormat.Markdown, Aspose.Words.LoadFormat.Rtf, Aspose.Words.LoadFormat.WordML, Aspose.Words.LoadFormat.Doc, Aspose.Words.LoadFormat.Dot, Aspose.Words.LoadFormat.Odt, Aspose.Words.LoadFormat.Ott formats supported.

RecoveryMode

Defines how the document should be handled if errors occur during loading. Use this property to specify whether the system should attempt to recover the document or follow another defined behavior. The default value is Aspose.Words.Loading.DocumentRecoveryMode.TryRecover.

public DocumentRecoveryMode RecoveryMode { get; set; }

Property Value

DocumentRecoveryMode

Examples

Shows how to try to recover a document if errors occurred during loading.

LoadOptions loadOptions = new LoadOptions();
                                                                                    loadOptions.RecoveryMode = DocumentRecoveryMode.TryRecover;

                                                                                    Document doc = new Document(MyDir + "Corrupted footnotes.docx", loadOptions);

ResourceLoadingCallback

Allows to control how external resources (images, style sheets) are loaded when a document is imported from HTML, MHTML.

public IResourceLoadingCallback ResourceLoadingCallback { get; set; }

Property Value

IResourceLoadingCallback

Examples

Shows how to handle external resources when loading Html documents.

public void LoadOptionsCallback()
                                                                              {
                                                                                  LoadOptions loadOptions = new LoadOptions();
                                                                                  loadOptions.ResourceLoadingCallback = new HtmlLinkedResourceLoadingCallback();

                                                                                  // When we load the document, our callback will handle linked resources such as CSS stylesheets and images.
                                                                                  Document doc = new Document(MyDir + "Images.html", loadOptions);
                                                                                  doc.Save(ArtifactsDir + "LoadOptions.LoadOptionsCallback.pdf");
                                                                              }

                                                                              /// <summary>
                                                                              /// Prints the filenames of all external stylesheets and substitutes all images of a loaded html document.
                                                                              /// </summary>
                                                                              private class HtmlLinkedResourceLoadingCallback : IResourceLoadingCallback
                                                                              {
                                                                                  public ResourceLoadingAction ResourceLoading(ResourceLoadingArgs args)
                                                                                  {
                                                                                      switch (args.ResourceType)
                                                                                      {
                                                                                          case ResourceType.CssStyleSheet:
                                                                                              Console.WriteLine($"External CSS Stylesheet found upon loading: {args.OriginalUri}");
                                                                                              return ResourceLoadingAction.Default;
                                                                                          case ResourceType.Image:
                                                                                              Console.WriteLine($"External Image found upon loading: {args.OriginalUri}");

                                                                                              const string newImageFilename = "Logo.jpg";
                                                                                              Console.WriteLine($"\tImage will be substituted with: {newImageFilename}");

                                                                                              Image newImage = Image.FromFile(ImageDir + newImageFilename);

                                                                                              ImageConverter converter = new ImageConverter();
                                                                                              byte[] imageBytes = (byte[])converter.ConvertTo(newImage, typeof(byte[]));
                                                                                              args.SetData(imageBytes);

                                                                                              return ResourceLoadingAction.UserProvided;
                                                                                      }

                                                                                      return ResourceLoadingAction.Default;
                                                                                  }
                                                                              }

TempFolder

Allows to use temporary files when reading document. By default this property is null and no temporary files are used.

public string TempFolder { get; set; }

Property Value

string

Examples

Shows how to load a document using temporary files.

// Note that such an approach can reduce memory usage but degrades speed
                                                              LoadOptions loadOptions = new LoadOptions();
                                                              loadOptions.TempFolder = @"C:\TempFolder\";

                                                              // Ensure that the directory exists and load
                                                              Directory.CreateDirectory(loadOptions.TempFolder);

                                                              Document doc = new Document(MyDir + "Document.docx", loadOptions);

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

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

                                                                                     // The specified temporary folder must exist in the local file system before the load operation.
                                                                                     Directory.CreateDirectory(options.TempFolder);

                                                                                     Document doc = new Document(MyDir + "Document.docx", options);

                                                                                     // The folder will persist with no residual contents from the load operation.
                                                                                     Assert.That(Directory.GetFiles(options.TempFolder).Length, Is.EqualTo(0));

Remarks

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

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

UpdateDirtyFields

Specifies whether to update the fields with the dirty attribute.

public bool UpdateDirtyFields { get; set; }

Property Value

bool

Examples

Shows how to use special property for updating field result.

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

                                                                       // Give the document's built-in "Author" property value, and then display it with a field.
                                                                       doc.BuiltInDocumentProperties.Author = "John Doe";
                                                                       FieldAuthor field = (FieldAuthor)builder.InsertField(FieldType.FieldAuthor, true);

                                                                       Assert.That(field.IsDirty, Is.False);
                                                                       Assert.That(field.Result, Is.EqualTo("John Doe"));

                                                                       // Update the property. The field still displays the old value.
                                                                       doc.BuiltInDocumentProperties.Author = "John & Jane Doe";

                                                                       Assert.That(field.Result, Is.EqualTo("John Doe"));

                                                                       // Since the field's value is out of date, we can mark it as "dirty".
                                                                       // This value will stay out of date until we update the field manually with the Field.Update() method.
                                                                       field.IsDirty = true;

                                                                       using (MemoryStream docStream = new MemoryStream())
                                                                       {
                                                                           // If we save without calling an update method,
                                                                           // the field will keep displaying the out of date value in the output document.
                                                                           doc.Save(docStream, SaveFormat.Docx);

                                                                           // The LoadOptions object has an option to update all fields
                                                                           // marked as "dirty" when loading the document.
                                                                           LoadOptions options = new LoadOptions();
                                                                           options.UpdateDirtyFields = updateDirtyFields;
                                                                           doc = new Document(docStream, options);

                                                                           Assert.That(doc.BuiltInDocumentProperties.Author, Is.EqualTo("John & Jane Doe"));

                                                                           field = (FieldAuthor)doc.Range.Fields[0];

                                                                           // Updating dirty fields like this automatically set their "IsDirty" flag to false.
                                                                           if (updateDirtyFields)
                                                                           {
                                                                               Assert.That(field.Result, Is.EqualTo("John & Jane Doe"));
                                                                               Assert.That(field.IsDirty, Is.False);
                                                                           }
                                                                           else
                                                                           {
                                                                               Assert.That(field.Result, Is.EqualTo("John Doe"));
                                                                               Assert.That(field.IsDirty, Is.True);
                                                                           }
                                                                       }

UseSystemLcid

Gets or sets whether to use LCID value obtained from Windows registry to determine page setup default margins.

public bool UseSystemLcid { get; set; }

Property Value

bool

Remarks

If set to true, then MS Word behavior is emulated which takes LCID value from Windows registry.

The default value is false.

WarningCallback

Called during a load operation, when an issue is detected that might result in data or formatting fidelity loss.

public IWarningCallback WarningCallback { get; set; }

Property Value

IWarningCallback

Examples

Shows how to print and store warnings that occur during document loading.

public void LoadOptionsWarningCallback()
                                                                                    {
                                                                                        // Create a new LoadOptions object and set its WarningCallback attribute
                                                                                        // as an instance of our IWarningCallback implementation.
                                                                                        LoadOptions loadOptions = new LoadOptions();
                                                                                        loadOptions.WarningCallback = new DocumentLoadingWarningCallback();

                                                                                        // Our callback will print all warnings that come up during the load operation.
                                                                                        Document doc = new Document(MyDir + "Document.docx", loadOptions);

                                                                                        List<WarningInfo> warnings = ((DocumentLoadingWarningCallback)loadOptions.WarningCallback).GetWarnings();
                                                                                        Assert.That(warnings.Count, Is.EqualTo(3));
                                                                                    }

                                                                                    /// <summary>
                                                                                    /// IWarningCallback that prints warnings and their details as they arise during document loading.
                                                                                    /// </summary>
                                                                                    private class DocumentLoadingWarningCallback : IWarningCallback
                                                                                    {
                                                                                        public void Warning(WarningInfo info)
                                                                                        {
                                                                                            Console.WriteLine($"Warning: {info.WarningType}");
                                                                                            Console.WriteLine($"\tSource: {info.Source}");
                                                                                            Console.WriteLine($"\tDescription: {info.Description}");
                                                                                            mWarnings.Add(info);
                                                                                        }

                                                                                        public List<WarningInfo> GetWarnings()
                                                                                        {
                                                                                            return mWarnings;
                                                                                        }

                                                                                        private readonly List<WarningInfo> mWarnings = new List<WarningInfo>();
                                                                                    }

Methods

Equals(object)

Determines whether the specified object is equal in value to the current object.

public override bool Equals(object obj)

Parameters

obj object

Returns

bool

 English