Cannot convert Html string to docx

Hi,

I am trying to generate docx from a html string. Here’s my code.

       Aspose.Words.Document doc = new Aspose.Words.Document();

        DocumentBuilder builder = new DocumentBuilder();

        string csshtml = ".MyStyle{color: red;} </ body > ";

        builder.InsertHtml(csshtml);

        string divhtml = "Div Text";

        builder.InsertHtml(divhtml, true);

        doc.Save(@"C:\Test\" + "Out.docx");

However, my Out.docx is blank. Not sure what I am missing here, could someone please guide me, Thanks!

@shireesha,

Please try running the following code.

string css = ".MyStyle{color: red;}";
string html = "<div class='MyStyle'>Div Text</div>";

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

builder.MoveToDocumentEnd();

StringBuilder finalHtml = new StringBuilder();
finalHtml.Append("<html><head><style>");
finalHtml.Append(css);
finalHtml.Append("</style><title></title></head><body>");
finalHtml.Append(html);
finalHtml.Append("</body></html>");

builder.InsertHtml(finalHtml.ToString());

doc.Save("D:\\temp\\18.9.docx");

Hope, this helps.

Thank you Awais Hafeez. That worked!
I was wondering if there’s a way to include css as an external script instead of appending it as a string?

Thanks in advance!

@shireesha,

If you have external CSS file then you can read it like this:

string css = File.ReadAllText("D:\\temp\\StyleSheet1.css");

The rest of the code will remain be the same.

great! thanks Awais, will try that out. Thanks again!

Hi awais,

Thanks for your help with the previous questions. I am able to convert html to docx and then from docx to pdf without any issues. The only problem that I am seeing is there is a lot of white space in the header area of every page (both in docx and pdf). I am sure this is not coming from my html. Is there any way to get rid of this huge white space.

@shireesha,

Please ZIP and upload your input HTML file and Aspose.Words generated DOCX and PDF files here for testing. We will then investigate the issue on our end and provide you more information.