首页 > 解决方案 > 从 c# 调用时,wkhtmltopdf 未将 html 字符串转换为 pdf

问题描述

我正在尝试将html字符串转换为在我的控制台应用程序中pdf使用。这是命令。wkhtmltopdf.net 5

echo | set /p="<h3>test</h3>" | "C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe" -s A4 - "C:\Users\xxxx\Desktop\test.pdf"

当我在命令提示符下运行并获得 pdf 文件时,上述命令有效。但是当我在控制台应用程序中以编程方式运行相同的命令时,这没有任何作用。

这是我尝试过的代码,

string arguments = $@"echo | set /p=""<h3>test</h3>"" | ""C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"" -s A4 - ""C:\Users\xxxx\Desktop\test.pdf""";

var p = new System.Diagnostics.Process()
{
    StartInfo =
    {
        FileName = "cmd.exe",
        Arguments = arguments,
        UseShellExecute = false, // needs to be false in order to redirect output
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        RedirectStandardInput = true, // redirect all 3, as it should be all 3 or none
        WorkingDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)),
        //WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden
    }
};

p.Start();

// read the output here...
var output = p.StandardOutput.ReadToEnd();
var errorOutput = p.StandardError.ReadToEnd();

// ...then wait n milliseconds for exit (as after exit, it can't read the output)
p.WaitForExit(60000);

// read the exit code, close process
int returnCode = p.ExitCode;
p.Close();

// if 0 or 2, it worked so return path of pdf
if ((returnCode == 0) || (returnCode == 2))
    return outputFolder + outputFilename;
else
    throw new Exception(errorOutput);

请协助我缺少什么。

标签: c#cmdcommand-linecommand-promptwkhtmltopdf

解决方案


我弄清楚了问题所在。

/C当我们以编程方式运行命令时,看起来我们需要添加到命令的开头。

string arguments = $@"/C echo | set /p=""<h3>test</h3>"" | ""C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe"" -s A4 - ""C:\Users\xxxx\Desktop\test.pdf""";

原因:

/C执行字符串指定的命令,然后终止。


推荐阅读