tnblog
首页
登录

基于open office 把各种类型转为pdf在线预览

60人阅读 2019/7/3 9:27 评论:1 手机 收藏 关注
分类: .net

                 

//需要在服务器安装open office,引用cli_basetypes,cli_cppuhelper,cli_oootypes,cli_ure,cli_uretypes
public bool ConvertToPdf(string inputFile, string outputFile)
        {
            if (ConvertExtensionToFilterType(Path.GetExtension(inputFile)) == null) {
                throw new InvalidProgramException("Unknown file  = " + inputFile);
            }

            StartOpenOffice();

            //Get a ComponentContext
            var xLocalContext = Bootstrap.bootstrap();
           
            //Get MultiServiceFactory
            var xRemoteFactory = (XMultiServiceFactory) xLocalContext.getServiceManager();
            //Get a CompontLoader
            var aLoader = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");
            //var aa = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.style.CharacterProperties");

            //Load the sourcefile 
           

            XComponent xComponent = null;

            try
            {
                xComponent = InitDocument(aLoader, PathConverter(inputFile), "_blank");
                
                //Wait for loading
                while (xComponent == null)
                {
                    Thread.Sleep(1000);
                }

                // save/export the document
               
               return SaveDocument(xComponent, inputFile, PathConverter(outputFile));
            }
            finally
            {
                if (xComponent != null) xComponent.dispose();
            }
        }

        private static void StartOpenOffice()
        {
            var ps = Process.GetProcessesByName("soffice.exe");
            if (ps.Length != 0)
                throw new InvalidProgramException("soffice not installed!");
            if (ps.Length > 0)
                return;
            var p = new Process
            {
                StartInfo =
                {
                    Arguments = "-headless -nofirststartwizard",
                    FileName = "soffice.exe",
                    CreateNoWindow = true
                }
            };
            var result = p.Start();

            if (result == false)
                throw new InvalidProgramException("soffice failed to start.");
        }


        private static XComponent InitDocument(XComponentLoader aLoader, string file, string target)
        {
            var openProps = new PropertyValue[1];
            openProps[0] = new PropertyValue { Name = "Hidden", Value = new Any(true) };

            var xComponent = aLoader.loadComponentFromURL( file, target, 0, openProps);
            

            return xComponent;
        }

        private static bool SaveDocument(XComponent xComponent, string sourceFile, string destinationFile)
        {
            try {
                var propertyValues = new PropertyValue[2];
                
                // Setting the flag for overwriting
                propertyValues[1] = new PropertyValue { Name = "Overwrite", Value = new Any(true) };
                //// Setting the filter name
                propertyValues[0] = new PropertyValue
                {
                    Name = "FilterName",
                    Value = new Any(ConvertExtensionToFilterType(Path.GetExtension(sourceFile)))
                };

               
                //propertyValues[2] = new PropertyValue
                //{ 
                //    Name = "CharFontStyleName",
                //    Value = new Any("华文琥珀")
                //};

                ((XStorable)xComponent).storeToURL(destinationFile, propertyValues);
                return true;
            } catch {
                return false;
            }

           
        }

        private static string PathConverter(string file)
        {
            if (string.IsNullOrEmpty(file))
                throw new NullReferenceException("Null or empty path passed to OpenOffice");

            return String.Format("file:///{0}", file.Replace(@"\", "/"));
        }

        public static string ConvertExtensionToFilterType(string extension)
        {
            switch (extension)
            {
                case ".doc":
                case ".docx":
               case ".txt":
                case ".rtf":
                case ".html":
                case ".htm":
                case ".xml":
                case ".odt":
                case ".wps":
                case ".wpd":
                    return "writer_pdf_Export";
                case ".xls":
                case ".xlsb":
                case ".xlsx":
                case ".ods":
                    return "calc_pdf_Export";
                case ".ppt":
                case ".pptx":
                case ".odp":
                    return "impress_pdf_Export";

                default:
                    return null;
            }
        }

 

评价
关注
没有个性,不需要签名
文章
6
评论
8
分类
16
关注
16
{{item.ArticleTitle}}
{{item.BlogName}} : {{item.Content}}