这是我为生成PDF而运行的代码
public string ScreenshotFullLength(string Url) {
UrlScreenshot Shot = new UrlScreenshot(Url, 975, 100);
int maxHeight = 1250;
// If you do skip the crop function you 'll get the
// full lenght of the page. We'll scale it to match
// a 400 pixel width
//int newHeight = (Shot.Bitmap.Width / 400) * Shot.Bitmap.Height;
//Shot.Resize(400, newHeight);
string Filename = LazyAssFilename();
string path = Server.MapPath("~") + "/tmp/" + Filename;
Shot.Bitmap.Save(path, ImageFormat.Png);
string pdfURL = "";
Document document = new Document();
try {
// step 2:
// we create a writer that listens to the document
// and directs a PDF-stream to a file
pdfURL = Server.MapPath("~") + "\\tmp\\Attest_" + EOFName + ".pdf";
PdfWriter.GetInstance(document, new FileStream(pdfURL, FileMode.Create));
// step 3: we open the document
document.Open();
// step 4: we add content
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(path);
if (jpg.Height > maxHeight) {
//we moeten er meer dan 1 maken en croppen
int loops = (int)(jpg.Height / maxHeight);
int rest = (int)(jpg.Height % maxHeight);
int i;
for (i = 0; i < loops; i++) {
Bitmap bmpImage = new Bitmap(path);
Bitmap bmpCrop = bmpImage.Clone(new System.Drawing.Rectangle(0, i * maxHeight, 975, maxHeight),
bmpImage.PixelFormat);
iTextSharp.text.Image crpd = iTextSharp.text.Image.GetInstance(bmpCrop, ImageFormat.Png);
crpd.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
crpd.ScalePercent(60);
document.Add(crpd);
}
//the rest
Bitmap bmpImage2 = new Bitmap(path);
Bitmap bmpCrop2 = bmpImage2.Clone(new System.Drawing.Rectangle(0, i * maxHeight, 975, rest),
bmpImage2.PixelFormat);
iTextSharp.text.Image crpdRest = iTextSharp.text.Image.GetInstance(bmpCrop2, ImageFormat.Png);
crpdRest.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
crpdRest.ScalePercent(60);
document.Add(crpdRest);
} else {
jpg.Alignment = iTextSharp.text.Image.MIDDLE_ALIGN;
jpg.ScalePercent(60);
document.Add(jpg);
}
} catch (DocumentException de) {
Console.Error.WriteLine(de.Message);
} catch (IOException ioe) {
Console.Error.WriteLine(ioe.Message);
}
// step 5: we close the document
document.Close();
try {
//screenshots deleten
File.Delete(path);
} catch { }
return pdfURL;
}
这在网站上运行,以制作网页的PDF。
但是,当多个人从网站访问此代码时,为了生成他们的PDF,我收到错误:Object is currently in use elsewhere.
STACKTRACE:在System.Drawing.Image.Save(String filename,ImageCodecInfo encoder,EncoderParameters encoderParams)at ...
我该如何解决这个问题?该错误在Shot.Bitmap.Save(path, ImageFormat.Png);
答案 0 :(得分:0)
刚发现这个类似的question。其中一个答案表明GDI +不是线程安全的,在这种情况下你需要锁定你的Save()和其他一些方法。
只是为了确认,阅读Image类的信息,尽管这对于单个实例或同一类的不同实例是否含糊不清。
此类型的任何公共静态(在Visual Basic中为Shared)成员都是 线程安全。任何实例成员都不能保证是线程 安全
答案 1 :(得分:0)
我遇到了同样的问题,我有一个工作线程将GUI抽出到其图形界面,但它只在某些时候抛出此异常。 用Invoke包装它修复它。
_parent.Invoke( new Action(() => eg.Graphics.DrawImage( _icon, rc )));