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

发布于:2024-08-19 ⋅ 阅读:(116) ⋅ 点赞:(0)

安装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


网站公告

今日签到

点亮在社区的每一天
去签到