您的位置:首页 > 编程语言 > ASP

Aspose Words 把内容读到stream中时容易出现的问题,以及memorystream to string

2015-04-10 13:54 597 查看
Aspose Words 转换doc为其他格式时,如果你想直接将转换出的内容保存到数据库中,或者其他方式进行传输,而不需要保存到文件时,通常使用流的方式,如果下面这样:

  Aspose.Words.Document doc = new Aspose.Words.Document(new MemoryStream(aDocument));

doc.PageColor = Color.White; // doc files are saved with red background on the server, changing to white anyway
MemoryStream firstStream = new MemoryStream();
doc.Save(firstStream, saveFormat);
return firstStream.GetBuffer();
这时,会发生一个异常:
Image file cannot be written to disk. When saving the document to a stream either ImagesFolder should be specified or custom streams should be provided via ImageSavingCallback.
Please see documentation for details.

解决这个异常的代码是这样的:

也可参考这个页面:
http://www.aspose.com/community/forums/thread/405071/exception-when-converting-doc-to-html-when-saving-the-document-to-a-stream-either-imagesfolder-sho.aspx
internal byte[] ConvertRightNowAspose(byte[] aDocument, SaveFormat saveFormat)
{
Aspose.Words.Document doc = new Aspose.Words.Document(new MemoryStream(aDocument));
doc.PageColor = Color.White; // doc files are saved with red background on the server, changing to white anyway
using (MemoryStream firstStream = new MemoryStream())
{
if (saveFormat == SaveFormat.Html)
{
HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html);
options.ImageSavingCallback = new HandleImageSaving();
doc.Save(firstStream, options);
}
else
{
doc.Save(firstStream, saveFormat);
}

return firstStream.GetBuffer();
}
}

public class HandleImageSaving : IImageSavingCallback
{
void IImageSavingCallback.ImageSaving(ImageSavingArgs e)
{
e.ImageStream = new MemoryStream();
e.KeepImageStreamOpen = false;
}
}

如果你要获取文本:
MemoryStream streamContent = new MemoryStream();
docContent.Save(streamContent, saveOption);
string a = System.Text.Encoding.UTF8.GetString(streamContent.ToArray());
streamContent.Close();

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息