走进一步,发掘一处。勇于,敢于。
jtans

导航

 
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.table;
//引用openoffice安装路径下的C:\Program Files\OpenOffice.org 3\Basis\sdk\cli 的5个dll
namespace OpenOfficeService
{
    public class ConversionToPDF
    {
        // For thread safety
        private static Mutex _openOfficeLock = new Mutex(false, "OpenOfficeMutexLock-MiloradCavic");

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="wordMl">WordML document in binary form</param>
        /// <returns>PDF in binary form</returns>
        public static byte[] Generate(byte[] wordMl)
        {
            string tempDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Temp\";

            if (!Directory.Exists(tempDirectory))
                Directory.CreateDirectory(tempDirectory);

            Random r = new Random();
            string sourcePath = string.Format("{0}\\doc-source-{1}-{2}.xml",
                tempDirectory, r.Next(), DateTime.Now.Ticks);
            string destinationPath = string.Format("{0}\\doc-destination-{1}-{2}.pdf",
                tempDirectory, r.Next(), DateTime.Now.Ticks);

            File.WriteAllBytes(sourcePath, wordMl);

            Generate(sourcePath, destinationPath);

            byte[] resulting = File.ReadAllBytes(destinationPath);

            //if (System.IO.File.Exists(destinationPath))
            //    File.Delete(destinationPath);

            return resulting;
        }

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="sourcePath">Path to document to convert(e.g: C:\test.doc)</param>
        /// <returns>PDF in binary form</returns>
        public static byte[] Generate(string sourcePath)
        {
            //string tempDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).TrimEnd('\\');
            string tempDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Temp\";

            if (!Directory.Exists(tempDirectory))
                Directory.CreateDirectory(tempDirectory);

            Random r = new Random();
            string destinationPath = string.Format("{0}\\doc-destination-{1}-{2}.pdf",
                tempDirectory, r.Next(), DateTime.Now.Ticks);

            Generate(sourcePath, destinationPath);

            byte[] resulting = File.ReadAllBytes(destinationPath);

            //if (System.IO.File.Exists(destinationPath))
            //    File.Delete(destinationPath);

            return resulting;
        }

        /// <summary>
        /// Converts document to PDF
        /// </summary>
        /// <param name="sourcePath">Path to document to convert(e.g: C:\test.doc)</param>
        /// <param name="destinationPath">Path on which to save PDF (e.g: C:\test.pdf)</param>
        /// <returns>Path to destination file if operation is successful, or Exception text if it is not</returns>
        public static string Generate(string sourcePath, string destinationPath)
        {
            bool obtained = _openOfficeLock.WaitOne(60 * 1000, false);
            XComponent xComponent = null;

            try
            {
                if (!obtained)
                {
                    throw new System.Exception(string.Format("Request for using OpenOffice wasn't served after {0} seconds. Aborting...", 30));
                }

                sourcePath = PathConverter(sourcePath);
                destinationPath = PathConverter(destinationPath);

                // 載入文件前屬性設定,設定文件開啟時隱藏  
                PropertyValue[] loadDesc = new PropertyValue[1];
                loadDesc[0] = new PropertyValue();
                loadDesc[0].Name = "Hidden";
                loadDesc[0].Value = new uno.Any(true);

                //Get a ComponentContext
                unoidl.com.sun.star.uno.XComponentContext xLocalContext = uno.util.Bootstrap.bootstrap();

                //Get MultiServiceFactory
                unoidl.com.sun.star.lang.XMultiServiceFactory xRemoteFactory = (unoidl.com.sun.star.lang.XMultiServiceFactory)xLocalContext.getServiceManager();

                //Get a CompontLoader
                XComponentLoader aLoader = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");

                //Load the sourcefile
                xComponent = aLoader.loadComponentFromURL(sourcePath, "_blank", 0, new unoidl.com.sun.star.beans.PropertyValue[0]);

                //Wait for loading
                while (xComponent == null)
                {
                    System.Threading.Thread.Sleep(3000);
                }

                saveDocument(xComponent, destinationPath);

                xComponent.dispose();

                return destinationPath;
            }
            catch (System.Exception ex)
            {
                return ex.ToString();
            }
            finally
            {
                Process[] pt = Process.GetProcessesByName("soffice.bin");
                if (pt != null && pt.Length > 0)
                    pt[0].Kill();

                Process[] ps = Process.GetProcessesByName(@"C:\Program Files\OpenOffice.org 3\program\soffice.exe");
                if (ps != null && ps.Length > 0)
                    ps[0].Kill();

                if (System.IO.File.Exists(sourcePath))
                    File.Delete(sourcePath);

                if (obtained)
                    _openOfficeLock.ReleaseMutex();
            }
        }


        /// <summary>
        /// Saves the document.
        /// </summary>
        /// <param name="xComponent">The x component.</param>
        /// <param name="fileName">Name of the file.</param>
        private static void saveDocument(XComponent xComponent, string fileName)
        {
            unoidl.com.sun.star.beans.PropertyValue[] propertyValue = new unoidl.com.sun.star.beans.PropertyValue[1];

            propertyValue[0] = new unoidl.com.sun.star.beans.PropertyValue();
            propertyValue[0].Name = "FilterName";
            propertyValue[0].Value = new uno.Any("writer_pdf_Export");

            ((XStorable)xComponent).storeToURL(fileName, propertyValue);
        }

        /// <summary>
        /// Convert into OO file format
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>The converted file</returns>
        private static string PathConverter(string file)
        {
            try
            {
                file = file.Replace(@"\", "/");

                return "file:///" + file;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
    }
}
//之前我试着OpenOffice官方的java代码用C#写了一篇,觉得乱了点,附上上面是摘自一位网友的代码。稍微修改、优化、或者作出windows 服务运行等。。。。
using System;
using System.Collections.Generic;
using System.Web;
using System.IO;
using System.Diagnostics;

namespace OpenOfficeConvert.Converter
{


    public abstract class PDF2Swf
    {
    //下载安装swftools安装包,下面是安装根路径 protected static string SWFTools_PATH = @"D:\Program Files\SWFTools\"; static PDF2Swf() { } public static string ConvertPDFToSWF(string inFilePath,string outFilePath) { string cmdStr = string.Empty; string msg = string.Empty; cmdStr = string.Format("d:\r\ncd {0}\r\npdf2swf {1} -B {2}swfs\\rfxview.swf -o {3}", SWFTools_PATH, inFilePath, SWFTools_PATH, outFilePath); RunShell(cmdStr,ref msg); if (File.Exists(outFilePath)) { return outFilePath; } return msg; } ///<summary> /// 获取文件全路径 ///</summary> ///<param name="path"></param> ///<returns></returns> public static string GetPath(string path) { //HttpContext.Current.Server.MapPath(path); return String.Format("{0}{1}", "", path); } ///<summary> /// 运行命令 ///</summary> ///<param name="strShellCommand">命令字符串</param> ///<returns>命令运行时间</returns> private static double RunShell(string strShellCommand,ref string msg) { double spanMilliseconds = 0; DateTime beginTime = DateTime.Now; Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.Arguments = String.Format(@"/c {0}", strShellCommand); cmd.Start(); msg = "MSG:" + cmd.StandardOutput.ReadToEnd(); cmd.WaitForExit(); cmd.Close(); DateTime endTime = DateTime.Now; TimeSpan timeSpan = endTime - beginTime; spanMilliseconds = timeSpan.TotalMilliseconds; return spanMilliseconds; } ///<summary> /// 保证当前的文件名唯一 ///</summary> ///<returns></returns> private static string GetPDFName() { return DateTime.Now.ToLongTimeString().Replace(':', '_') + DateTime.Now.Millisecond; } } }
//转换记得用物理路径

  

  

posted on 2012-09-03 21:58  jtans  阅读(443)  评论(0)    收藏  举报