Using Clipboard Class in ASP.NET 拷贝Excel的图表到PowerPoint粘帖时出错

Using the clipboard class in C# or VB.NET is pretty simple for windows applications. However, it gets a little trickier for ASP.Net projects.

Background:
The first question you may ask is "Why would you ever want to use the server's clipboard to do anything?" Good question :). I came accross this problem when I was trying to write a pdf parser that would rasterize the front page and save it into a Bitmap object. From here, you can save it to a file, database, etc. To do this, I was using the Adobe Acrobat com library that comes with Adobe Acrobat 7.0. Unfortunatly, they do not have a function that allows you to simply save to a file. They do, however, let you copy the image to the clipboard and then recover it in whatever format you want.

Problem:
I found some great code here: http://www.codeproject.com/dotnet/pdfthumbnail.asp. This code was written for a C#/VB.Net Windows App and works great if used that way. However, when I tried to use this text in the OnClick event of an ASP Button control, i found that nothing was happening. Turns out, the CopyToClipboard command was working fine, b/c if I traced through, I could press ctrl+v and see the image perfectly. However, when the Clipboard.GetObject method was called, it was always returning Null.

Solution:
After much digging and 2 days of work, I stumbled on the reason: The thread started for the ASP.Net application did not have the right ApartmentState to read the Clipboard class. So, here is what I did to work around this:

protected void Button_Click(object sender, EventArgs e)
{
 Thread cbThread = new Thread(new ThreadStart(CopyToClipboard));
 cbThread.ApartmentState = ApartmentState.STA;
 cbThread.Start();
 cbThread.Join();
}

[STAThread]
protected void CopyToClipboard()
{
/*
In here, put the code that copies AND retrieves from the clipboard.
If you use global variables, the Bitmap you populate here can be used elsewhere in your code.
*/
}

Final Notes:
I do not recommend doing this in a multi-user environment as there is no guarentee that the user that copied to the clipboard will be the one who retrieves from it. Also, images/pdfs can be very large and the clipboard is slow.

I hope this is of some use to someone. It solved my problem and saved me $900 by not having to buy a PDF Rasterizer control. Feel free to respond and let me know if it helped you out or if you have any questions.

http://msdn.microsoft.com/en-us/library/bb676881(v=office.12).aspx

http://www.telerik.com/community/forums/community-forums/interesting-resources/using-clipboard-class-in-asp-net.aspx

http://stackoverflow.com/questions/798761/in-net-how-do-i-set-stathread-when-im-running-a-form-in-an-additional-thread

原文地址:https://www.cnblogs.com/blackbean/p/2288343.html