Articles in this section
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:

  1. In the ASP.NET applications, add 'AspCompat=true' in the @page directive.
  2. 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
}

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied