Category / Section
How to fix the ThreadStateException (ActiveX control cannot be instantiated) exception when converting HTML to PDF?
1 min read
In the HTML to PDF conversion process, the HTMLConverter throws an exception with the message "ActiveX control '8856f961-340a-11d0-a96b-00c04fd705a2' cannot be instantiated because the current thread is not in a single-threaded apartment."
The HTMLConverter internally makes use of the MSHTML.dll that can run only in the STA mode. Running the application in the MTA mode leads to this exception.
This can be fixed by any of the following ways:
- In the ASP.NET applications, add 'AspCompat=true' in the @page directive.
- In ASP.NET MVC, windows or web services and console applications make use of the following code snippet:
[C#] Thread t = new Thread(ConvertToPDF); t.SetApartmentState(ApartmentState.STA); t.Start(); t.Join(); private void ConvertToPDF() { //Convert PDF here }
[C#] private void ConvertToPDF() { //Convert PDF here using IE based converter }