C# 生成并执行批处理命令文件实现批量转换pdf

public class ExecBatHelper
{
    //创建并执行bat文件
    public static bool ExecBat(string folderPath, string saveFolderPath)
    {
        bool flag;
        try
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("@echo off");
            sb.AppendLine("cd /d %~dp0");
            sb.AppendLine("title html batch to pdf");
            sb.AppendLine($@"for %%i in ({folderPath}\*.html) do wkhtmltopdf.exe --page-size A4 --orientation landscape --dpi 96 --encoding utf8 --margin-left 10 --margin-right 10 --margin-bottom 10 --margin-top 10 %%i {saveFolderPath}\%%~ni.pdf");

            string batPath = CreateBatFile(sb.ToString());

            flag = ExecBatFile(batPath);

            File.Delete(batPath);
        }
        catch
        {
            flag = false;
        }
        return flag;
    }

    // 创建bat文件
    public static string CreateBatFile(string strBat)
    {
        if (string.IsNullOrEmpty(strBat))
        {
            throw new Exception("Bat text content cannot be empty.");
        }

        try
        {
            string path = AppDomain.CurrentDomain.BaseDirectory.ToString() + @"wkhtmltopdf\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string fileName = path + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 10000) + ".bat";
            FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            //Encoding.GetEncoding("GB2312")使用GB2312 以代表ANSI编码 不然中文会报错
            StreamWriter streamWriter = new StreamWriter(fileStream, Encoding.GetEncoding("GB2312"));
            streamWriter.Write(strBat);
            streamWriter.Flush();

            streamWriter.Close();
            streamWriter.Dispose();
            fileStream.Close();
            fileStream.Dispose();
            return fileName;
        }
        catch
        {
            throw new Exception("Bat text content error.");
        }
    }

    // 执行bat文件
    public static bool ExecBatFile(string filename)
    {
        try
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo();
            processStartInfo.FileName = filename;
            //processStartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
            processStartInfo.UseShellExecute = false;
            processStartInfo.CreateNoWindow = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.StandardOutputEncoding = Encoding.UTF8;
            //processStartInfo.Arguments = GetArguments(htmlPath, savePath);

            Process proc = new Process();
            proc.StartInfo = processStartInfo;
            proc.Start();
            proc.WaitForExit();

            proc.Close();
            proc.Dispose();

            return true;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception Occurred :{0},{1}", ex.Message, ex.StackTrace.ToString());
            return false;
        }
    }
}

posted on 2023-09-04 15:55  糯米白白  阅读(21)  评论(0编辑  收藏  举报

导航