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发布报错处理(亲测)

 

    原文作者:羊奇乐乐
    原文地址: https://blog.csdn.net/yq772700/article/details/105626423
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞