2014-08-27 140 views
0

我想要使用wkhtmltopdf將鏈接(例如www.google.com)轉換爲PDF格式(請參閱Calling wkhtmltopdf to generate PDF from HTML),但在這裏我得到的錯誤是沒有生成pdf,但代碼工作正常,返回0作爲回覆。無法使用wkhtmltopdf從HTML生成PDF

代碼:

public static bool HtmlToPdf(string Url, string outputFilename) 
{ 
    // assemble destination PDF file name 
    string filename = @"C:\Users\Documents\visual studio 2012\Projects\PenchKin\PenchKin\Setup\test.pdf"; 

    // get proj no for header 
    //Project project = new Project(int.Parse(outputFilename)); 

    var p = new System.Diagnostics.Process(); 
    p.StartInfo.FileName = @"C:\Users\documents\visual studio 2012\Projects\PenchKin\PenchKin\Setup\wkhtmltopdf-0.9.9-installer.exe"; 

    string switches = "--print-media-type "; 
    switches += "--margin-top 4mm --margin-bottom 4mm --margin-right 0mm --margin-left 0mm "; 
    switches += "--page-size A4 "; 
    switches += "--no-background "; 
    switches += "--redirect-delay 100"; 

    p.StartInfo.Arguments = switches + " " + Url + " " + filename; 
    p.StartInfo.UseShellExecute = false; // needs to be false in order to redirect output 
    p.StartInfo.RedirectStandardOutput = true; 
    p.StartInfo.RedirectStandardError = true; 
    p.StartInfo.RedirectStandardInput = true; // redirect all 3, as it should be all 3 or none 
    p.StartInfo.WorkingDirectory = p.StartInfo.FileName; 

    p.Start(); 

    // read the output here... 
    string output = p.StandardOutput.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 (not sure about other values, I want a better way to confirm this) 
    return (returnCode == 0 || returnCode == 2); 
} 

請給我幫助解決這個問題。

回答

1

您應該指向實際的exe,而不是安裝程序。您的回覆感謝:更換

p.StartInfo.FileName = @"C:\Users\documents\visual studio 2012\Projects\PenchKin\PenchKin\Setup\wkhtmltopdf-0.9.9-installer.exe"; 

通過

p.StartInfo.FileName = @"C:\path\to\binary\wkhtmltopdf.exe"; 
+0

亞歷克西斯。我想確認一個工作目錄(p.StartInfo.WorkingDirectory)與文件名相同的東西嗎?因爲我不確定工作目錄是什麼?也請讓我知道,我將如何能夠用上面的代碼編寫pdf文件。請幫助我。 – 2014-08-27 12:49:24

相關問題