Search code examples
c#cmdcommand-linecommand-promptwkhtmltopdf

wkhtmltopdf not converting html string to pdf when invoked from c#


I'm trying to convert html string to pdf using wkhtmltopdf in my .net 5 console app. Here is the command.

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

The above command works when I run in command prompt and I get the pdf file. But this does nothing when I run the same command programmatically in my console app.

Here is the code I tried,

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);

Please assist on what I'm missing.


Solution

  • I figured out what was the issue.

    Looks like we need to add /C to the beginning of command when we run command programmatically.

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

    Reason:

    /C Carries out the command specified by the string and then terminates.