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

来源:互联网 发布:淘宝店铺层级在哪里看 编辑:程序博客网 时间:2024/05/01 09:51

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();




0 0