文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>Word转Tif

Word转Tif

时间:2010-09-13  来源:YangLei's

先把word分页存储为tif,然后把把所有的tif合成一张tif,界面如下:

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using oWord = Microsoft.Office.Interop.Word;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Interop;
using System.Windows.Forms;
using System.Threading;

namespace WpfWordToTif
{
    /// <summary>
    /// 杨磊原创http://www.cnblogs.com/yangleiWPF

    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            setProcessDel = (i) =>
            {
                progressBar1.Value = i;
            };
            setListDel = (str) =>
            {
                listBox1.Items.Insert(0,str);
            };
            setGridDel = (ifor) =>
            {
                grid1.IsEnabled = ifor;
            };
        }
        static string FileName;
        delegate void setProcess(int i);
        setProcess setProcessDel;
        delegate void setList(string str);
        setList setListDel;
        delegate void setGrid(bool ifor);
        setGrid setGridDel;
        public void PrintWortWithClipBoard(string wordPath, string outputFilePath, IntPtr handle)
        {
            ArrayList imageList = new ArrayList();
            oWord.ApplicationClass word = new oWord.ApplicationClass();
            Type wordType = word.GetType();
            oWord.Documents docs = word.Documents;
            object missing = Type.Missing;
            try
            {
                grid1.IsEnabled = false;
                wordType = docs.GetType();
                object objDocName = wordPath;
                oWord.Document doc = (oWord.Document)wordType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { objDocName, true, true });
                wordType = doc.GetType();
                oWord.WdStatistic Statistic = oWord.WdStatistic.wdStatisticPages;
                int countPage = doc.ComputeStatistics(Statistic, ref missing);
                listBox1.Items.Add("文件 " + FileName + " 共" + countPage + "页");
                object What = oWord.WdGoToItem.wdGoToPage;
                object Which = oWord.WdGoToDirection.wdGoToNext;
                if (countPage < 1)
                {
                    //MessageBox.Show("页面不足一页!");
                }
                else
                {
                    Thread tr = new Thread(new ThreadStart(() =>
                    {
                        int smallCount = 100 / countPage;
                        int count = 0;
                        for (int i = 1; i <= countPage; i++)
                        {
                            object startPage = i;
                            object endPage = i + 1;
                            object start = doc.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref startPage).Start; // 第二个参数可以用Nothing
                            object end;
                            if (i == countPage)
                            {
                                end = doc.Content.End;
                            }
                            else
                            {
                                end = doc.ActiveWindow.Selection.GoTo(ref What, ref Which, ref missing, ref endPage).Start; // 第二个参数可以用Nothing
                            }
                            oWord.Range mg = doc.ActiveWindow.Document.Range(ref start, ref end);
                            mg.Select();
                            mg.CopyAsPicture();
                            System.Windows.Forms.IDataObject data = System.Windows.Forms.Clipboard.GetDataObject();
                            Object obj = null;
                            if (data.GetDataPresent(System.Windows.Forms.DataFormats.MetafilePict))
                            {
                                obj = data.GetData(System.Windows.Forms.DataFormats.MetafilePict);
                                Metafile mf = ClipboardMetafileHelper.GetEnhMetafileOnClipboard(handle);
                                System.Drawing.Image image = mf;
                                image.Save(@outputFilePath + FileName + i + ".jpg", ImageFormat.Tiff);
                                imageList.Add(@outputFilePath + FileName + i + ".jpg");
                                image.Dispose();
                            }
                            this.Dispatcher.Invoke(setListDel, "第" + i.ToString() + "页转换完成");
                            count += smallCount;
                            this.Dispatcher.Invoke(setProcessDel, count);
                        }
                        this.Dispatcher.Invoke(setListDel, "正在处理结果...");
                        if (imageList.Count > 1)
                        {
                            JoinTiffImages(imageList, outputFilePath + "\\" + FileName + ".tif", EncoderValue.CompressionLZW);
                        }
                        this.Dispatcher.Invoke(setListDel, "转换完成。");
                        this.Dispatcher.Invoke(setProcessDel, 100);
                        try
                        {
                            wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, word, null);
                        }
                        catch (Exception)
                        {
                        }
                        finally {
                            this.Dispatcher.Invoke(setGridDel, true);
                        }
                    }));
                    tr.ApartmentState = ApartmentState.STA;
                    tr.IsBackground = true;
                    tr.Start();
                }
            }
            catch (Exception)
            {
                this.Dispatcher.Invoke(setGridDel, true);
            }
        }
        public void JoinTiffImages(ArrayList imageFiles, string outFile, EncoderValue compressEncoder)
        {
            try
            {
                if (imageFiles.Count == 1)
                {
                    File.Copy((string)imageFiles[0], outFile, true);
                    return;
                }
                Encoder enc = Encoder.SaveFlag;
                EncoderParameters ep = new EncoderParameters(2);
                ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
                ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
                Bitmap pages = null;
                int frame = 0;
                ImageCodecInfo info = GetEncoderInfo("image/tiff");
                foreach (string strImageFile in imageFiles)
                {
                    if (frame == 0)
                    {
                        pages = (Bitmap)System.Drawing.Image.FromFile(strImageFile);
                        pages.Save(outFile, info, ep);
                    }
                    else
                    {
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
                        Bitmap bm = (Bitmap)System.Drawing.Image.FromFile(strImageFile);
                        pages.SaveAdd(bm, ep);
                        bm.Dispose();
                    }
                    if (frame == imageFiles.Count - 1)
                    {
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                        pages.SaveAdd(ep);
                    }
                    frame++;
                }
                pages.Dispose();
            }
            catch (Exception ex)
            {
#if DEBUG
                Console.WriteLine(ex.Message);
#endif
                throw;
            }
            finally
            {
                foreach (var item in imageFiles)
                {
                    File.Delete(item.ToString());
                }
            }
            return;
        }
        private ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int j = 0; j < encoders.Length; j++)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }

            throw new Exception(mimeType + "找不到该mini类型");
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openF = new OpenFileDialog();
            if (openF.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                listBox1.Items.Clear();
                progressBar1.Value = 0;
                textBox1.Text = openF.FileName;
                FileName = openF.SafeFileName.Substring(0, openF.SafeFileName.IndexOf('.'));
            }

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            IntPtr hwnd = ((HwndSource)PresentationSource.FromVisual(button2)).Handle;
            if (textBox1.Text.Trim() != "" && textBox2.Text.Trim() != "")
            {
                if (File.Exists(textBox1.Text) && Directory.Exists(textBox2.Text))
                {
                    PrintWortWithClipBoard(textBox1.Text, textBox2.Text, hwnd);
                }
            }
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog sf = new System.Windows.Forms.FolderBrowserDialog();
            if (sf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                textBox2.Text = sf.SelectedPath;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
    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;
        }
    }
}

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载