首页 > 编程语言 >asp.net core 调用wps实现word转pdf

asp.net core 调用wps实现word转pdf

时间:2024-08-17 18:27:59浏览次数:10  
标签:core asp word string Classes WriteLine var Console null

安装wps

https://www.wps.cn/
在这里插入图片描述
在这里插入图片描述

创建.net core控制项目

添加com引用,搜索wps
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
准备word,名字叫001.docx
在这里插入图片描述

word转pdf

编写代码

namespace WPSStu01
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("转化开始");
            var inputFile = "001.docx";
            var outputFile = "001.pdf";
            WordExportAsPdf(inputFile, outputFile);
            Console.WriteLine("转化成功");
            Console.ReadKey();
        }

        /// <summary>
        /// 转换为pdf文件,适合(.doc、.docx、.mht、.htm文件类型)
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="outputFileName"></param>
        /// <returns></returns>
        public static string WordExportAsPdf(string fileName, string outputFileName)
        {
            string isSucceed = "OK";
            Word.WdExportFormat fileFormat = Word.WdExportFormat.wdExportFormatPDF;
            Word.Application wordApp = null;
            if (wordApp == null) wordApp = new Word.Application();
            Word._Document wordDoc = null;

            try
            {
                wordDoc = wordApp.Documents.Open(fileName, false, true);
                wordDoc.ExportAsFixedFormat(outputFileName, fileFormat);

            }
            catch (Exception ex)
            {
                isSucceed = ex.Message;
            }

            finally
            {
                if (wordDoc != null)
                {
                    wordDoc.Close(false);
                    wordDoc = null;
                }
                if (wordApp != null)
                {
                    wordApp.Quit(false);
                    wordApp = null;
                }
            }
            return isSucceed;

        }
    }
}

启动项目报错
在这里插入图片描述
选择一下32位程序
在这里插入图片描述
发现还是不行,最后换成.net framework 4.8的控制台项目
添加dll的引用,dll需要去安装的wps里面查找
在这里插入图片描述

Console.WriteLine("转化开始");
var exePath = System.AppDomain.CurrentDomain.BaseDirectory;
var inputFile = Path.Combine(exePath, "001.docx");
var outputFile = Path.Combine(exePath, "001.pdf");
WordExportAsPdf(inputFile, outputFile);
Console.WriteLine("转化成功");
Console.ReadKey();

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

asp.net core也可以问题根本原因是路径的问题,不能些相对路径,必须绝对路径

在这里插入图片描述

excel转pdf

/// <summary>
/// Excel转换为pdf文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="outputFileName"></param>
/// <returns></returns>
public static string ExcelExportAsPdf(string fileName, string outputFileName)
{
    string isSucceed = "OK";
   
    Excel.Application excelApp = null;
    if (excelApp == null)
        excelApp = new Excel.Application();
    Excel.Workbook workBook = null;

    try
    {
        workBook = excelApp.Workbooks.Open(fileName, false, true);
        workBook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF,outputFileName);

    }
    catch (Exception ex)
    {
        isSucceed = ex.Message;
    }

    finally
    {
        if (workBook != null)
        {
            workBook.Close(false);
            workBook = null;
        }
        if (excelApp != null)
        {
            excelApp.Quit();
            excelApp = null;
        }
    }
    return isSucceed;

}

调用

Console.WriteLine("转化开始");
var exePath = System.AppDomain.CurrentDomain.BaseDirectory;
var inputFile = Path.Combine(exePath, "002.xls");
var outputFile = Path.Combine(exePath, "002.pdf");
ExcelExportAsPdf(inputFile, outputFile);
Console.WriteLine("转化成功");
Console.ReadKey();

ppt转pdf

/// <summary>
/// PPT转换为pdf文件
/// </summary>
/// <param name="fileName"></param>
/// <param name="outputFileName"></param>
/// <returns></returns>
public static string PptExportAsPdf(string fileName, string outputFileName)
{
    string isSucceed = "OK";

    PowerPoint.Application pptApp = null;
    if (pptApp == null)
        pptApp = new PowerPoint.Application();
    PowerPoint.Presentation presentation = null;

    try
    {
        presentation = pptApp.Presentations.Open(fileName);
        presentation.ExportAsFixedFormat(outputFileName,PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);

    }
    catch (Exception ex)
    {
        isSucceed = ex.Message;
    }

    finally
    {
        if (pptApp != null)
        {
            presentation.Close();
            pptApp = null;
        }
        if (pptApp != null)
        {
            pptApp.Quit();
            pptApp = null;
        }
    }
    return isSucceed;

}

调用

Console.WriteLine("转化开始");
var exePath = System.AppDomain.CurrentDomain.BaseDirectory;
var inputFile = Path.Combine(exePath, "003.pptx");
var outputFile = Path.Combine(exePath, "003.pdf");
PptExportAsPdf(inputFile, outputFile);
Console.WriteLine("转化成功");
Console.ReadKey();

部署到iis

正常发布网站即可,不过部署到iis中报错了

Connection ID “17654110605327466499”, Request ID “80000004-000f-f500-b63f-84710c7967bb”: An unhandled exception was thrown by the application.
System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 没有注册类 (0x80040154 (REGDB_E_CLASSNOTREG)).

原因:一般软件安装时,会提示选择使用用户:当前登陆用户或者所有用户,如果选择当前登陆用户,会将信息写入注册表CurrentUser下;如果选择所有用户,会将信息写入注册表LocalMachine中。
第一步:导出注册表CurrentUse中Software\Classes\Wow6432Node\CLSID内容,修改节点,并导入LocalMachine中Software\Classes\Wow6432Node\CLSID
第二步:导出注册表CurrentUse中Software\Classes\TypeLib内容,修改节点,并导入LocalMachine中Software\Classes\TypeLib
第三步:导出注册表HKEY_CURRENT_USER\SOFTWARE\Classes\Interface 导入到HKEY_LOCAL_MACHINE中的SOFTWARE\Classes\Interface
就是将来”[HKEY_CURRENT_USER\”全部替换为“[HKEY_LOCAL_MACHINE\”,之后,保存,双击导入注册表
代码实现

using Microsoft.Win32;
using System.Runtime.InteropServices;

namespace WpsRegister
{
    /// <summary>
    ///  System.Runtime.InteropServices.COMException (0x80040154): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 没有注册类 (0x80040154 (REGDB_E_CLASSNOTREG)).
    ///  解决上述问题的报错
    /// </summary>
    internal class Program
    {
        /// <summary>
        /// 程序主入口
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // 导出并导入 Wow6432Node\CLSID
                CopyRegistryKey(
                    Registry.CurrentUser, @"Software\Classes\Wow6432Node\CLSID",
                    Registry.LocalMachine, @"Software\Classes\Wow6432Node\CLSID");

                // 导出并导入 TypeLib
                CopyRegistryKey(
                    Registry.CurrentUser, @"Software\Classes\TypeLib",
                    Registry.LocalMachine, @"Software\Classes\TypeLib");

                // 导出并导入 Interface
                CopyRegistryKey(
                    Registry.CurrentUser, @"SOFTWARE\Classes\Interface",
                    Registry.LocalMachine, @"SOFTWARE\Classes\Interface");
                Console.WriteLine("处理完成");
            }
            else
            {
                Console.WriteLine("仅支持windows系统");
            }
            Console.ReadKey();
        }

        /// <summary>
        /// 批量复制注册表的值
        /// </summary>
        /// <param name="sourceRoot"></param>
        /// <param name="sourceKey"></param>
        /// <param name="destRoot"></param>
        /// <param name="destKey"></param>
        static void CopyRegistryKey(RegistryKey? sourceRoot, string sourceKey, RegistryKey? destRoot, string destKey)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (sourceRoot == null)
                {
                    return;
                }
                using var sourceRegistryKey = sourceRoot.OpenSubKey(sourceKey);
                if (sourceRegistryKey == null)
                {
                    Console.WriteLine($"源路径不存在: {sourceRoot.Name}\\{sourceKey}");
                    return;
                }
                if (destRoot == null)
                {
                    return;
                }
                using var destRegistryKey = destRoot.CreateSubKey(destKey);
                if (destRegistryKey == null)
                {
                    Console.WriteLine($"目标路径无法创建: {destRoot.Name}\\{destKey}");
                    return;
                }

                CopyKey(sourceRegistryKey, destRegistryKey);
            }
        }

        /// <summary>
        /// 单个复制注册表的key
        /// </summary>
        /// <param name="sourceKey"></param>
        /// <param name="destKey"></param>
        static void CopyKey(RegistryKey? sourceKey, RegistryKey? destKey)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                if (sourceKey == null)
                {
                    return;
                }
                if (destKey == null)
                {
                    return;
                }
                // 复制值
                foreach (var valueName in sourceKey.GetValueNames())
                {
                    if (!string.IsNullOrEmpty(valueName))
                    {
                        object value = sourceKey.GetValue(valueName);
                        RegistryValueKind valueKind = sourceKey.GetValueKind(valueName);
                        if(value!=null)
                        { 
                            destKey.SetValue(valueName, value, valueKind); 
                        }
                    }
                }

                // 复制子键
                foreach (string subKeyName in sourceKey.GetSubKeyNames())
                {
                    using var sourceSubKey = sourceKey.OpenSubKey(subKeyName);
                    using var destSubKey = destKey.CreateSubKey(subKeyName);
                    CopyKey(sourceSubKey, destSubKey);
                }
            }

        }
    }
}

打包之后以管理员身份运行,再次启动错误如下展示

Connection ID “18158513746413092902”, Request ID “80000027-000b-fc00-b63f-84710c7967bb”: An unhandled exception was thrown by the application.
System.Runtime.InteropServices.COMException (0x80004023): Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80004023 遇到一个 Microsoft 软件安装程序错误。 (0x80004023).
at System.RuntimeTypeHandle.AllocateComObject(Void* pClassFactory)

找到iis应用程序池,选择自定义账户,输入管理员账号密码
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
设置好之后就可以启动了
在这里插入图片描述
点击提交,成功之后下载即可
在这里插入图片描述
在这里插入图片描述

经过测试发现不设置注册表也可以,只需要在iis中设置管理员账号

参考

https://www.cnblogs.com/stweily/p/17769699.html
https://blog.51cto.com/u_696257/6151371
https://blog.csdn.net/m0_68566281/article/details/134013548
https://blog.csdn.net/m0_68566281/article/details/134013548
https://blog.csdn.net/q646926099/article/details/52421273
https://blog.csdn.net/ningrz/article/details/5016412

标签:core,asp,word,string,Classes,WriteLine,var,Console,null
From: https://blog.csdn.net/qq_36437991/article/details/141220128

相关文章

  • pdf转word免费的软件
    该版本属于免费便携版,可以免费将pdf转成word。软件截图:使用说明:解压后,双击start_Foxit.bat来运行软件下载地址:FoxitPDFEditor-Pro-v13解压密码:helloh下载时可能会有广告,忽略,等下载结束即可。部分杀软会因该版本软件未购买签名证书(如下图)而阻止运行,可通过暂时关闭杀软......
  • EFCore中自引用的实体类设计
    案例:以部门(为主)-----部门下面又分1部、2部、3部等,1部下面又分为1组,2组,3组等这种结构像这样的设计类型应该用自引用来设计下面用用代码来实现://////Departmentclass///publicclassDepartment{//////部门Id///publicintId{get;set;}//////部门名称Nam......
  • 批量Word文档合并助手-V1.4.6.21
    在日常办公与文档处理中,经常需要面对大量分散的Word文档,手动一个个打开、复制、粘贴以合并内容,不仅耗时费力,还极易出错。为此,我们特别推出了“批量Word文档合并助手”软件,旨在为您提供一个高效、便捷的解决方案,让文档合并变得轻松简单。核心功能:一键合并:支持批量选择多个Word......
  • .net core 微服务间通信 消息总线更新 利用GRPC restful 优缺点
     在.NETCore微服务架构中,微服务间的通信是一个核心问题,而消息总线的更新则涉及到微服务间的动态配置和状态同步。关于使用gRPC和RESTfulAPI在微服务间通信的优缺点,以及它们在消息总线更新中的应用,可以从以下几个方面进行详细分析:一、gRPC的优缺点优点:高效性:gRPC使用Prot......
  • easy-es:java: 程序包org.dromara.easyes.core.core不存在
    问题描述:运行easy-es官网的springboot集成demo时报错:java:程序包org.dromara.easyes.core.core不存在问题分析:Ctrl+鼠标左键进入org.dromara.easyes.core下,查找发现BaseEsMapper在org.dromara.easyes.core.kernel目录下,而非org.dromara.easyes.core.core下解决方法......
  • Word文件加密的三种专业方法
    Word文档承载着大量敏感信息,如公司机密、合同内容及个人重要资料等。为了确保这些信息的安全性,对Word文件进行加密处理成为了必要的手段。本文将详细介绍三种Word文件加密方法,帮助大家根据实际需求选择合适的加密方式。首先我们要知道,word文档中主要分为打开密码、限制编辑、......
  • .NET CORE在publish的时候去掉pdb
     默认设置下,publish出来的文件其实是包含很多的pdb文件,即使你过程当中选择的是“输出为单一文件”: 想要设置为publish的时候不输出,有三种方法(推荐第三种):1.直接改项目的配置文件的配置:2.直接改Web项目的publish的文件的配置:在最终的Startup的项目(比如是Web)的publish配......
  • 【Python-办公自动化】1秒提取PPT文本内容形成目录保存至WORD
    欢迎来到"花花ShowPython",一名热爱编程和分享知识的技术博主。在这里,我将与您一同探索Python的奥秘,分享编程技巧、项目实践和学习心得。无论您是编程新手还是资深开发者,都能在这里找到有价值的信息和灵感。自我介绍:我热衷于将复杂的技术概念以简单易懂的方式呈现给大家,......
  • 【Java】Word题库解析
    一、需求场景:一共四种题型,单选、多选、判断、简答题目构成要素:题目、选项、答案、解析一种题型一个Word文档存放,需要把这些题目写入DB维护 二、题库格式:单选案例:多选案例: 判断案例:简答题案例:可以看出,单选,多选和判断都是一样的- 题目有数字和点开头,并设置了标题......
  • coca how word clusters页面
           Collocates     Clusters   Topics   Texts   KWIC       45624how do36622how you28435how it25414how can24930how they24357how did24206how long22277how about21728how ......