This is our example code :
using Aspose.Words;
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace AsposeWordsPartialHtmlBug
{
class Program
{
static void Main(string[] args)
{
var license = new License();
license.SetLicense("Aspose.Words.NET.lic");
var richTextField = Convert("<bold>this is bold HTML</bold>");
try
{
Assert(richTextField.Text);
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.Read();
Environment.Exit(1);
}
Environment.Exit(0);
}
private static void Assert(string text)
{
if (text.Contains("Evaluation Only"))
{
throw new Exception("License is invalid or not setup correctly.");
}
if (text.Contains("<bold>"))
{
throw new Exception($"HTML string was not converted correctly.{Environment.NewLine}Text was: {text}");
}
}
private static RichTextField Convert(string value)
{
//value = WorkAround(value);
var htmlStringAsBytes = ConvertHtmlStringToBytes(value);
return new RichTextField(GetText(htmlStringAsBytes), htmlStringAsBytes);
}
private static string WorkAround(string value)
{
return ContainsIgnoreCase(value, "<html>") ? value : $"<html><head></head><body>{value}</body></html>";
}
private static bool ContainsIgnoreCase(string value, string searchString)
{
return CultureInfo.InvariantCulture.CompareInfo.IndexOf(value, searchString, System.Globalization.CompareOptions.IgnoreCase) >= 0;
}
private static byte[] ConvertHtmlStringToBytes(string html)
{
byte[] result;
if (string.IsNullOrEmpty(html))
{
result = Array.Empty<byte>();
}
else
{
var htmlBytes = Encoding.UTF32.GetBytes(html);
using (var htmlStream = new MemoryStream(htmlBytes))
{
var doc = new Document(htmlStream, new LoadOptions(LoadFormat.Html, "", ""));
using (var outStream = new MemoryStream())
{
doc.Save(outStream, SaveFormat.Docx);
result = outStream.ToArray();
}
}
}
return result;
}
private static string GetText(byte[] data)
{
Document doc;
using (var memStream = new MemoryStream(data))
{
doc = new Document(memStream);
}
return CreateUnformattedText(doc);
}
private static string CreateUnformattedText(Document doc)
{
return CreateText(doc, new Aspose.Words.Saving.TxtSaveOptions { PreserveTableLayout = true, SimplifyListLabels = true });
}
private static string CreateText(Document doc, Aspose.Words.Saving.SaveOptions options)
{
using (var ms = new MemoryStream())
{
doc.Save(ms, options);
ms.Position = 0;
return CreateText(ms);
}
}
private static string CreateText(MemoryStream stream)
{
using (var sr = new StreamReader(stream))
{
var text = sr.ReadToEnd();
return text.TrimEnd();
}
}
}
}