如何将Word文档的所有页面保存为图像?

时间:2014-08-25 01:41:32

标签: c# image ms-word

我尝试使用以下代码将Word文档的所有页面保存为增强型图元文件(.emf)图像:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
using word = Microsoft.Office.Interop.Word;
using System.Drawing.Imaging;
using System.Drawing;

namespace WordToImg
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Doc|*.doc;*.docx";
            ofd.Title = "Select file to convert";
            ofd.InitialDirectory=Application.StartupPath;
            if (ofd.ShowDialog()==DialogResult.OK)
            {
                string file = ofd.FileName;
                word.Application app = new word.Application();
                word.Document doc = app.Documents.Open(file);

                byte[] bytes = (byte[])app.ActiveDocument.Content.EnhMetaFileBits;
                if (bytes != null)
                {
                    MemoryStream ms = new MemoryStream(bytes);
                    Image temp = Image.FromStream(ms);
                    temp.Save(Path.GetDirectoryName(file) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(file) + ".png", ImageFormat.Png);
                }
                doc.Close(false);
                doc = null;
                app.Quit();
                GC.Collect();
            }
        }
    }
}

但是,创建的图元文件仅包含第一页的内容。有没有办法将整个文档内容作为图像?或者,也许,使用Content.EnhMetaFileBits分别获取每个页面的内容?

1 个答案:

答案 0 :(得分:0)

我认为你需要改变:

 byte[] bytes = (byte[])app.ActiveDocument.Content.EnhMetaFileBits;

要:

 byte[] bytes = (byte[])app.ActiveDocument.Range().EnhMetaFileBits;