I am trying to generate a Pdf from Html string using DynamicPdf.HmtlConverter library. For generating Html string I am using HtmlTextWriter class from System.Web.UI. I am trying to add the external style sheet as follows :
StringBuilder sb = new StringBuilder();
sb.Append(@"<!DOCTYPE html>" + Environment.NewLine);
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{ //adding head and link tag
writer.RenderBeginTag(HtmlTextWriterTag.Html);
writer.RenderBeginTag(HtmlTextWriterTag.Head);
writer.Write("<meta charset=" + "\"UTF-8\">");
//Add Link tag attributes
writer.AddAttribute(HtmlTextWriterAttribute.Rel, "stylesheet");
writer.AddAttribute(HtmlTextWriterAttribute.Href,@"~\Stylesheet1.css"); //style sheet reference
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/css");
writer.RenderBeginTag(HtmlTextWriterTag.Link);
writer.RenderEndTag(); // end of Link tag
writer.RenderEndTag(); // end of head tag
// Body tag
writer.RenderBeginTag(HtmlTextWriterTag.Body)
writer.RenderEndTag(); // end of Body tag
writer.RenderEndTag(); // end of Html tag
}
sb.Append(stringWriter);
So "sb" will have the Html string which will be passed to DynamicPdf library method to generate Pdf as below :
ceTe.DynamicPDF.HtmlConverter.Converter.Convert(sb.ToString(),@"~\output3.pdf", null, options);
External style sheet does not show any effect on Html controls.
any suggestions how to use external style sheet with HtmlTextWriter and DynamicPdf library to generate a Pdf ..!!!
The issue is with path used for stylesheet. HTML does not recognizes any special meaning for '~' character. See RFC3986 Section:2.3
In Linux, '~' has a special meaning and translates to the home directory but for HTML it is just another character. I would suggest you to use
Path.GetFullPath("~")to get full path to home directory and then use that instead.Update:
I was mostly concentrated on the HTML part but I noticed that the third parameter of
ceTe.DynamicPDF.HtmlConverter.Converter.Convert()is set tonull. It must be the base-path for all the file paths used in html string. See DynamicPDF ReferenceSo the code should look something like this:
Then you may not need to use any path in HTML string. This can be just stylesheet name:
Hopefully this will fix the issue.