How can I use css for the HTML string input in PDF

I have a set of HTML string which I need to add in pages and set the look and feel of it with the css.

I also want to add Heading text to the same page before adding Html string.

Can anybody help me out

Regards,
Nithin Eate

@NithinEate,

You can use the following code to insert heading as well as HTML into Word document:

Document doc = new Document("D:\\Temp\\input.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToDocumentEnd();
builder.ParagraphFormat.StyleIdentifier = StyleIdentifier.Heading1;

builder.Writeln("Heading text");

builder.ParagraphFormat.ClearFormatting();
builder.InsertHtml("<span style='color:red;'>html text with style</span>");

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

Thanks for the reply but, I am looking for PDF file, which will generate as per HTML with css

@NithinEate,

Sure, you just need to change

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

with

doc.Save("D:\\temp\\18.8.pdf");

In case you still face any problems, please ZIP and attach the following resources here for testing:

  • Your simplified input Word document (if any)
  • HTML string (if any)
  • Aspose.Words 18.8 generated output PDF file showing the undesired behavior
  • Your expected DOCX/PDF document showing the correct output. You may create expected document by using Microsoft Word.
  • Please also create a standalone simple console application (source code without compilation errors) that helps us to reproduce your problem on our end and attach it here for testing. Please do not include Aspose.Words.dll files in it to reduce the file size.

As soon as you get these pieces of information ready, we will start further investigation into your issue/scenario and provide you code to achieve the same by using Aspose.Words. Thanks for your cooperation.

I can create PDF with inline html string. but if I want to use CSS from a .css file or .scss file, is it possible

@NithinEate,

If you have an external CSS file, then you can use the code like this to meet this requirement:

string css = File.ReadAllText("D:\\temp\\StyleSheet1.css");
string html = "<h1>Heading 1 goes here</h1>";

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.8.pdf");

Thanks for your reply