c#实现word中的图文恢复(c#实现word中的图文分离的姊妹篇)

//命名空间:
using Microsoft.Office.Interop.Word;
//包装操作类定义
public class WordCommand : IDisposable
{

public object Missing = System.Type.Missing;
public object True = true;
public object False = false;
public Document wDoc = null;
public Application wApp = null;
private bool FromTemplate;
private string FileName;
private delegate void OutStreamHander();
private event OutStreamHander outStreamHander;
public WordCommand(string sFileFullName, bool bFromTemplate)
{
    FileName = sFileFullName;
    FromTemplate = bFromTemplate;
}
public void Open()
{
    if (!File.Exists(FileName))
    {
 throw new FileNotFoundException("文件不存在!");
    }
    else if (wDoc != null)
    {
 throw new Exception("文档已经打开!");
    }
    else
    {
 wApp = new ApplicationClass();
 wApp.Options.CheckSpellingAsYouType = false;
 wApp.Options.CheckGrammarAsYouType = false;
 object oFileName = FileName;

 if (FromTemplate)
 {
     wDoc = wApp.Documents.Add(ref oFileName, ref Missing, ref Missing, ref Missing);
 }
 else
 {
     wDoc = wApp.Documents.Open(ref oFileName, ref Missing, ref False, ref Missing, ref Missing, ref Missing,
  ref Missing, ref Missing, ref Missing, ref Missing, ref Missing, ref True, ref Missing, ref Missing,
  ref Missing, ref Missing);
 }
 wApp.Selection.Range.Text = string.Empty;
    }
}
public string GetContent()
{
    return wDoc.Content.Text;
}
public string GetContent(string serverPath, string virtualPath)
{
    List<Microsoft.Office.Interop.Word.Range> ranges = new List<Microsoft.Office.Interop.Word.Range>();
    List<string> files = new List<string>();
    foreach (Microsoft.Office.Interop.Word.InlineShape s in wDoc.InlineShapes)
    {
  if (s.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapePicture
  || s.Type == Microsoft.Office.Interop.Word.WdInlineShapeType.wdInlineShapeEmbeddedOLEObject)
  {
      //获取图片数据
      byte[] imgData = (byte[])s.Range.EnhMetaFileBits;
      string file = string.Concat(Guid.NewGuid().ToString(), ".gif");
      files.Add(string.Join(",", new string[] { file, s.Height.ToString(), s.Width.ToString()}));
      //构造图形
      MemoryStream mStream = new MemoryStream(imgData);
      Bitmap bmp = new Bitmap(mStream);
      //保存到磁盘
      bmp.Save(string.Concat(serverPath, "//",file));
      mStream.Dispose();
      bmp.Dispose();

      ranges.Add(s.Range);
      s.Delete();
  }
    }
    for (int i = 0; i < ranges.Count; i++)
    {
  Microsoft.Office.Interop.Word.Range r = ranges[i];
  string[] parameters = files[i].Split(',');
  //替换图片
  r.InsertBefore("<img src=/"" + string.Concat(virtualPath, parameters[0]) + "/" height=/"" + parameters[1] + "/" width =/"" + parameters[2] + "/" onmousewheel=/"var zoom=parseInt(this.style.zoom, 10)||100;zoom+=event.wheelDelta/12;if (zoom>0) this.style.zoom=zoom+'%';return false;/"/>");
    }
    return wDoc.Content.Text;
}
public void SaveToStream(Stream stream)
{
    string sFileName = Path.GetTempFileName();
    if (FromTemplate)
    {
  SaveAs(sFileName);
  string sTmpName = Path.GetTempFileName();
  SaveAs(sTmpName);
  using (FileStream fs = File.OpenRead(sFileName))
  {
      int iLength = (int)fs.Length;
      byte[] bys = new byte[iLength];
      fs.Read(bys, 0, iLength);
      stream.Write(bys, 0, iLength);
  }
  File.Delete(sFileName);

  FileName = sTmpName;
  FromTemplate = true;
  outStreamHander = new OutStreamHander(WordCommand_outStreamHander);
    }
    else
    {
  //保存到临时目录
  SaveAs(sFileName);
  SaveAs(FileName);
  using (FileStream fs = File.OpenRead(sFileName))
  {
      int iLength = (int)fs.Length;
      byte[] bys = new byte[iLength];
      fs.Read(bys, 0, iLength);
      stream.Write(bys, 0, iLength);
  }
  File.Delete(sFileName);
    }
}
private void WordCommand_outStreamHander()
{
    File.Delete(FileName);
}
public void Dispose()
{
    if (wDoc != null)
    {
 System.Runtime.InteropServices.Marshal.ReleaseComObject(wDoc);
 wDoc = null;
    }
    if (wApp != null)
    {
 System.Runtime.InteropServices.Marshal.ReleaseComObject(wApp);
 wApp = null;
    }
}
}
//数据实体定义
private class WordInlineShape
{
private float width;
public float Width
{
  get { return width; }
  set { width = value; }
}
private float height;
public float Height
{
  get { return height; }
  set { height = value; }
}
private string file;
public string File
{
  get { return file; }
  set { file = value; }
}           
private string id;

public string Id
{
  get { return id; }
  set { id = value; }
}
public WordInlineShape(string id, float width, float height, string file)
{
  this.width = width;
  this.height = height;
  this.file = file;
  this.id = id;
}
}
//核心操作代码:
//获取文档路径
string template = ResourceHelper.PaperExportTemplateUrl;
string address = Server.MapPath(template);
WordCommand comm = new WordCommand(address, false);
try
{
    comm.Open();
    comm.wDoc.Content.Text = BizLogic.PrepareExportPaperContents(paperId);
    //逆向处理图片
    Hashtable inlineShapes = Hashtable.Synchronized(new Hashtable());
    string pattern = @"<img.*?//>";
    Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
    Match m = null;
    int idNumber = 1;
    //得到所有的图片匹配
    for (m = r.Match(comm.wDoc.Content.Text); m.Success; m = m.NextMatch())
    {
  if (!string.IsNullOrEmpty(m.Value))
  {
      //得到图片地址
      string srcPattern = @"<img.*?src/s*=/s*/""(.*?)/"".*?>";
      string heightPattern = @"<img.*?height/s*=/s*/""([/d.]+)/"".*?>";
      string widthPattern = @"<img.*?width/s*=/s*/""([/d.]+)/"".*?>";
      Regex xReg = new Regex(srcPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
      string srcUrl = xReg.Match(m.Value).Groups[1].Value;
      xReg = new Regex(heightPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
      string height = xReg.Match(m.Value).Groups[1].Value;
      xReg = new Regex(widthPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
      string width = xReg.Match(m.Value).Groups[1].Value;            
      //转换图片地址
      string file = ResourceHelper.MapFile(srcUrl);
      string id = string.Concat("<img", idNumber.ToString(), "/>");
      comm.wDoc.Content.Text = comm.wDoc.Content.Text.Replace(m.Value, id.ToString());
      float Width = float.Parse(width);
      float Height = float.Parse(height);
      //添加到集合
      WordInlineShape inlineShape = new WordInlineShape(id,Width, Height,file);
      inlineShapes[id] = inlineShape;
      //序号自增
      idNumber += 1;
  }
    }
    for (m = r.Match(comm.wDoc.Content.Text); m.Success; m = m.NextMatch())
    {
  if (!string.IsNullOrEmpty(m.Value))
  {
      WordInlineShape inlineShape = (WordInlineShape)inlineShapes[m.Value];
      //生成ole对象
      string FileName = inlineShape.File;
      object LinkToFile = false;
      object SaveWithDocument = true;
      //运算插入锚点    
      int index = comm.wDoc.Content.Text.IndexOf(m.Value);
      object Start = index;
      object End = index;
      Microsoft.Office.Interop.Word.Range range = comm.wDoc.Range(ref Start, ref End);
      object Anchor = range;
      //插入图片
      comm.wDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref  LinkToFile, ref  SaveWithDocument, ref  Anchor);
      comm.wDoc.Application.ActiveDocument.InlineShapes[1].Width = inlineShape.Width;
      comm.wDoc.Application.ActiveDocument.InlineShapes[1].Height = inlineShape.Height;
  }
    }
    comm.SaveToStream(Response.OutputStream);
    string fileName = @"paper.doc";
    Response.ContentType = "application/vnd.ms-word";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
    Response.Charset ="GB2312";
    Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
    Response.End();
}
catch (Exception expt)
{
    ShowError(expt.Message);
}
finally
{
    comm.Close();
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值