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

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





  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值