C#,使用office组件Microsoft.Office.Interop.Word 保存word文档为图片

网上查了很多的攻略教程,汇总如下,亲测

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;
using System.Windows.Forms;
using MSWord = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Threading;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;

namespace StrangeSheep
{
    #region 将word文档转换为图片
    public class Word2Image
    {
        /// <summary>
        /// 将Word文档转换为图片的方法      
        /// </summary>
        /// <param name="wordInputPath">Word文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>
        /// <param name="width">图片的宽度</param>
        /// <param name="imageFormat">图片格式默认png</param>
        /// <returns></returns>
        public List<string> ConvertToImage(string wordInputPath, string imageOutputDirPath, int width, ImageFormat imageFormat)
        {
            //返回值
            List<string> imgpath = new List<string>();
            //捕捉总体报错信息
            try
            {
                if (imageOutputDirPath == "")
                {
                    imageOutputDirPath = Path.Combine(Path.GetDirectoryName(wordInputPath), Path.GetFileNameWithoutExtension(wordInputPath));
                    if (Directory.Exists(imageOutputDirPath))
                    {
                        Directory.Delete(imageOutputDirPath, true);
                    }
                    Directory.CreateDirectory(imageOutputDirPath);
                }
                if (imageFormat == null)
                {
                    imageFormat = ImageFormat.Png;
                }

                MSWord.ApplicationClass wordApplicationClass = new MSWord.ApplicationClass();
                wordApplicationClass.Visible = false;
                object missing = System.Reflection.Missing.Value;

                Random rm = new Random();
                string tmpFilePath = Path.GetFullPath(wordInputPath) +rm.Next().ToString("0000")+ ".tmp";

                MSWord.Document document = new MSWord.Document();
                try
                {
                    //如果文件存在则删除
                    if (File.Exists(tmpFilePath))
                        File.Delete(tmpFilePath);
                    File.Copy(wordInputPath, tmpFilePath);

                    object filePathObject = tmpFilePath;

                    document = wordApplicationClass.Documents.Open(ref filePathObject, ref missing,
                        false, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing, ref missing, ref missing,
                        ref missing, ref missing);

                    bool finished = false;
                    int picnum = 1;
                    while (!finished)
                    {
                        document.Content.CopyAsPicture();
                        System.Windows.Forms.IDataObject data = Clipboard.GetDataObject();
                        if (data.GetDataPresent(DataFormats.MetafilePict))
                        {
                            object obj = data.GetData(DataFormats.MetafilePict);
                            Metafile metafile = ClipboardMetafileHelper.GetEnhMetafileOnClipboard(IntPtr.Zero);
                            //根据宽度等比例缩放
                            int imgHeight = Convert.ToInt32(width * metafile.Height / metafile.Width);
                            Bitmap bm = new Bitmap(width, imgHeight);
                            using (Graphics g = Graphics.FromImage(bm))
                            {
                                g.Clear(Color.White);
                                g.DrawImage(metafile, 0, 0, bm.Width, bm.Height);
                                g.CompositingQuality = CompositingQuality.HighQuality;
                                g.SmoothingMode = SmoothingMode.HighQuality;
                            }
                            //保存文件在文件夹中
                            if (!Directory.Exists(imageOutputDirPath))
                            {
                                Directory.CreateDirectory(imageOutputDirPath); 
                            }
                            bm.Save(Path.Combine(imageOutputDirPath, Path.GetFileNameWithoutExtension(imageOutputDirPath) + "_" + picnum.ToString("000") + "." + imageFormat.ToString()));
                            picnum++;
                            //转成base64图片格式
                            using (MemoryStream ms1 = new MemoryStream())
                            {
                                bm.Save(ms1, System.Drawing.Imaging.ImageFormat.Png);
                                byte[] arr1 = new byte[ms1.Length];
                                ms1.Position = 0;
                                ms1.Read(arr1, 0, (int)ms1.Length);
                                ms1.Close();
                                imgpath.Add(Convert.ToBase64String(arr1));
                            }
                            Clipboard.Clear();
                        }

                        object Next = MSWord.WdGoToItem.wdGoToPage;
                        object First = MSWord.WdGoToDirection.wdGoToFirst;
                        object startIndex = "1";
                        document.ActiveWindow.Selection.GoTo(ref Next, ref First, ref missing, ref startIndex);
                        MSWord.Range start = document.ActiveWindow.Selection.Paragraphs[1].Range;
                        MSWord.Range end = start.GoToNext(MSWord.WdGoToItem.wdGoToPage);
                        finished = (start.Start == end.Start);
                        if (finished)
                        {
                            end.Start = document.Content.End;
                        }

                        object oStart = start.Start;
                        object oEnd = end.Start;
                        document.Range(ref oStart, ref oEnd).Delete(ref missing, ref missing);
                    }
                }
                catch (Exception e)
                {
                    DBUtility.LogMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + e.StackTrace + "    " + e.Source + "\r\n" + e.Message, "doc-error");
                    ((MSWord._Document)document).Close(ref missing, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
                    wordApplicationClass.Quit(ref missing, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplicationClass);
                    File.Delete(tmpFilePath);
                    throw;
                }
                finally
                {
                    ((MSWord._Document)document).Close(ref missing, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
                    wordApplicationClass.Quit(ref missing, ref missing, ref missing);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApplicationClass);
                    File.Delete(tmpFilePath);
                }
            }
            catch (Exception e)
            {
                DBUtility.LogMessage(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + e.StackTrace + "    " + e.Source + "\r\n" + e.Message, "doc-error");
            }
            return imgpath;
        }
    }
    #endregion
    class ClipboardMetafileHelper
    {
        [DllImport("user32.dll")]
        static extern bool OpenClipboard(IntPtr hWndNewOwner);
        [DllImport("user32.dll")]
        static extern bool EmptyClipboard();
        [DllImport("user32.dll")]
        static extern IntPtr SetClipboardData(uint uFormat, IntPtr hMem);
        [DllImport("user32.dll")]
        static extern bool CloseClipboard();
        [DllImport("gdi32.dll")]
        static extern IntPtr CopyEnhMetaFile(IntPtr hemfSrc, IntPtr hNULL);
        [DllImport("gdi32.dll")]
        static extern bool DeleteEnhMetaFile(IntPtr hemf);

        // Metafile mf is set to an invalid state inside this function
        static public bool PutEnhMetafileOnClipboard(IntPtr hWnd, Metafile mf)
        {
            bool bResult = false;
            IntPtr hEMF, hEMF2;
            hEMF = mf.GetHenhmetafile(); // invalidates mf
            if (!hEMF.Equals(new IntPtr(0)))
            {
                hEMF2 = CopyEnhMetaFile(hEMF, new IntPtr(0));
                if (!hEMF2.Equals(new IntPtr(0)))
                {
                    if (OpenClipboard(hWnd))
                    {
                        if (EmptyClipboard())
                        {
                            IntPtr hRes = SetClipboardData(14 /**//*CF_ENHMETAFILE*/, hEMF2);
                            bResult = hRes.Equals(hEMF2);
                            CloseClipboard();
                        }
                    }
                }
                DeleteEnhMetaFile(hEMF);
            }
            return bResult;
        }
        private const int CF_ENHMETAFILE = 14;
        [DllImport("user32.dll")]
        private static extern int IsClipboardFormatAvailable(int wFormat);
        [DllImport("user32.dll")]
        private static extern IntPtr GetClipboardData(int wFormat);

        static public Metafile GetEnhMetafileOnClipboard(IntPtr hWnd)
        {
            Metafile meta = null;
            if (OpenClipboard(hWnd))
            {
                try
                {
                    if (IsClipboardFormatAvailable(CF_ENHMETAFILE) != 0)
                    {
                        IntPtr hEMF = GetClipboardData(CF_ENHMETAFILE);
                        meta = new Metafile(hEMF, true);
                    }
                }
                finally
                {
                    CloseClipboard();
                }
            }
            return meta;
        }
    }
}

如果本地调试正常,但发布IIS时却报错的话,请见我上一篇博客

C#,使用office组件Microsoft.Office.Interop.Word 操作IIS发布报错处理(亲测)

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
microsoft.office.interop.word.dll .dll 本文件能够完美解决系统中缺失microsoft.office.interop.word.dll文件等问题, microsoft.office.interop.word.dll文件官方下载。使用前请详细阅读microsoft.office.interop.word.dll丢失修复方法。 microsoft.office.interop.word.dll使用方法: 方法一 一、如果在运行某软件或编译程序时提示缺少、找不到microsoft.office.interop.word.dll等类似提示 下载来的microsoft.office.interop.word.dll拷贝到指定目录即可(一般是system系统目录或放到软件同级目录里面),或者重新添加文件引用。 二、将软件包下载下来后,先将其解压(一般都是rar压缩包), 然后根据您系统的情况选择X86/X64,X86为32位电脑,X64为64位电脑。 三、直接拷贝系统对应的microsoft.office.interop.word.dll到系统目录里: 1、Windows 95/98/Me系统,将microsoft.office.interop.word.dll复制到C:\Windows\System目录下。 2、Windows NT/2000系统,将microsoft.office.interop.word.dll复制到C:\WINNT\System32目录下。 3、Windows XP/WIN7/win10系统(64位系统对应64位dll文件,32位系统对应32位dll文件),将microsoft.office.interop.word.dll复制到C:\Windows\System32目录下。 4、如果您的系统是64位的请将32位的dll文件复制到C:\Windows\SysWOW64目录。 四、打开"开始-运行-输入regsvr32 microsoft.office.interop.word.dll",回车即可解决。您提供的microsoft.office.interop.word.dll对您有所帮助。 方法二 下载中心下载dll的朋友,可将下面的代码保存为“注册.bat“,放到dll文件同级目录(只要在同一个文件夹里面有这两个文件即可),双击注册.bat,就会自动完成microsoft.office.interop.word.dll注册(win98不支持)。 下面是系统与dll版本对应的注册bat文件(64位的系统对应64位dll文件,32位系统对应32位的dll文件,如果64位的系统安装32位的dll文件,请将下面的system32替换为SysWOW64即可。) 复制代码代码如下: @echo 开始注册 copy microsoft.office.interop.word.dll%windir%\system32\ regsvr32 %windir%\system32\microsoft.office.interop.word.dll /s @echo microsoft.office.interop.word.dll注册成功 @pause

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值