菩提树的Framework架构

.net 架构,数据库设计,编码规范

导航

MOSS的 EventHandle Word 转化XPS

转载请标明去处: www.cnblogs.com/putishu  菩提树qq:43094723

 

主要思路:

在ItemAdded添加处理事件,步骤如下:

 

1、获取当前文档、存储到服务器的硬盘路径;

2、转化当前硬盘路径上的word为xps;

3、通过二进制流上传到moss文档库。

 

不多说了,直接贴代码!

 

 

 

 

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using System.Web;
using System.Configuration;

namespace sinopec.LeaderPortal
{
    class Convert2XPS : SPItemEventReceiver
    {
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            using (SPSite site = new SPSite(properties.ListItem.Web.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(properties.ListItem.Web.ID))
                {
                    SPFile sf = properties.ListItem.File;
                    string path = string.Empty;
                    String FileName=String.Empty;
                    string testpath = string.Empty;
                  
                    if (sf != null)
                    {

                        string appPath = GetPath();
                        testpath = sf.ParentFolder.ServerRelativeUrl;
                        FileName = sf.Name;
                        string savePath= ByteConvertWord(sf.OpenBinary(), FileName);
                        string flName = savePath.Substring(0, savePath.LastIndexOf("."));
                        string targetFileName = flName + ".xps";
                        string targetFileName2 = FileName.Substring(0, FileName.LastIndexOf(".")) + ".xps";
                        //此处写转化为doc/docx转化成xps
                        Convert(appPath + savePath, appPath  + targetFileName, Word.WdExportFormat.wdExportFormatXPS);
                        System.IO.FileInfo myfile = new System.IO.FileInfo(appPath+savePath);              
                        byte[] fileContents = new byte[int.Parse(myfile.Length.ToString())];
                        FileStream fs = File.OpenRead(appPath + targetFileName);
                        int n = fs.Read(fileContents, 0, int.Parse(myfile.Length.ToString()));
                        UploadDocument(targetFileName2, fileContents, @"http://win2003_blank/sites/zhenggongbu/wordxps/"); 


                    }
                    //SPListItem listItem = properties.ListItem;

                    //louji

                    //listItem["Title"] = "dafaffsskj;afffds";

                    //listItem.Update();

                }
            }
        }

        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
        }

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
        }

        public override void ItemUpdating(SPItemEventProperties properties)
        {
            base.ItemUpdating(properties);
        }

        public override void ItemAttachmentAdded(SPItemEventProperties properties)
        {
            base.ItemAttachmentAdded(properties);


            using (SPSite site = new SPSite(properties.ListItem.Web.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(properties.ListItem.Web.ID))
                {
                    SPListItem listItem = properties.ListItem;

                    //louji

                    listItem["Title"] = "dafaffsskj;afffds";
                    listItem.Update();
                }
            }
        }


        private bool Convert(string sourcePath, string targetPath, Microsoft.Office.Interop.Word.WdExportFormat exportFormat)
        {
            bool result;
            object paramMissing = Type.Missing;
            Word.ApplicationClass wordApplication = new Word.ApplicationClass();
            Word.Document wordDocument = null;
            try
            {
                object paramSourceDocPath = sourcePath;
                string paramExportFilePath = targetPath;

                Word.WdExportFormat paramExportFormat = exportFormat;
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor =
                    Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks =
                    Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                wordDocument = wordApplication.Documents.Open(
                    ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);

                if (wordDocument != null)
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                        paramExportFormat, paramOpenAfterExport,
                        paramExportOptimizeFor, paramExportRange, paramStartPage,
                        paramEndPage, paramExportItem, paramIncludeDocProps,
                        paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                        paramBitmapMissingFonts, paramUseISO19005_1,
                        ref paramMissing);
                result = true;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            return result;
        }

        /// <summary>
        /// 二进制数据转换为word文件
        /// </summary>
        /// <param name="data">二进制数据</param>
        /// <param name="fileName">word文件名</param>
        /// <returns>word保存的相对路径</returns>
        public string ByteConvertWord(byte[] data, string fileName)
        {
            string savePath = @"\SystemWord\" + FormatNowTime(2) + @"\";
            string appPath = GetPath();
            if (!System.IO.Directory.Exists(appPath + savePath))
            {
                Directory.CreateDirectory(appPath + savePath);
            }
            savePath += fileName;
            string filePath = appPath + savePath;

            FileStream fs;
            if (System.IO.File.Exists(filePath))
            {
                fs = new FileStream(filePath, FileMode.Truncate);
            }
            else
            {
                fs = new FileStream(filePath, FileMode.CreateNew);
            }
            BinaryWriter br = new BinaryWriter(fs);
            br.Write(data, 0, data.Length);
            br.Close();
            fs.Close();
            return savePath;
        }

        /// <summary>
        /// word文件转换二进制数据
        /// </summary>
        /// <param name="wordPath">word文件路径</param>
        /// <returns>二进制</returns>
        private byte[] wordConvertByte(string wordPath)
        {
            byte[] bytContent = null;
            System.IO.FileStream fs = null;
            System.IO.BinaryReader br = null;
            try
            {
                fs = new FileStream(wordPath, System.IO.FileMode.Open);
            }
            catch
            {
            }
            br = new BinaryReader((Stream)fs);
            bytContent = br.ReadBytes((Int32)fs.Length);

            return bytContent;
        }

        /// <summary>
        /// 项目所在目录
        /// </summary>
        /// <returns></returns>
        public string GetPath()
        {
            //return Application.StartupPath;

            string path = @System.Configuration.ConfigurationManager.AppSettings["xpspath"];
            return path;
        }

        public string GetWebAddress()
        {
            return System.Configuration.ConfigurationManager.AppSettings["webaddr"];
        }
        /// <summary>
        /// 格式化当前时间:
        /// 1:yyMMddHHmmss; 2:yyyy-MM\dd\
        /// </summary>
        /// <returns></returns>
        public string FormatNowTime(int num)
        {
            if (num == 1)
            {
                return DateTime.Now.ToString("yyMMddHHmmss");
            }
            else if (num == 2)
            {
                return DateTime.Now.ToString("yyyy-MM") + @"\" + DateTime.Now.Day;
            }
            return "";
        }

        public static string UploadDocument(string fileName, byte[] fileContents, string pathFolder)
        {
            if (fileContents == null)
            {
                return "Null Attachment";
            }
            try
            {
               
                int iStartIndex = pathFolder.LastIndexOf("/");              
                string sitePath = pathFolder.Remove(iStartIndex);
                string folderName = string.Empty;

                if (sitePath.LastIndexOf("/") > 6)
                {
                    int sec_iStartIndex = sitePath.LastIndexOf("/");
                  
                    sitePath = pathFolder.Remove(sitePath.LastIndexOf("/"));
                    folderName = pathFolder.Substring(sec_iStartIndex + 1);
                
                }
             
                else
                {
                    folderName = pathFolder.Substring(iStartIndex + 1);
                
                }
                SPSite site = new SPSite(sitePath);
                SPWeb web = site.OpenWeb();
               
              
                SPFolder folder = web.GetFolder(folderName);

                string fileURL = fileName;
               
                SPFile exFile=folder.Files.Add(fileURL, fileContents);

                if (exFile!=null )
                {
                    exFile.CheckIn("File Checked In");
                }
              
                return "File added successfully!";
               
              
            }
            catch (System.Exception ex)
            {
                return ex.Source + ":" + ex.Message;
            }
        }

    }
}

 

posted on 2010-09-02 10:07  菩提树下  阅读(795)  评论(0编辑  收藏  举报