在服务器端使用wkhtmltopdf.exe将URL转换为pdf

时间:2016-08-23 11:29:00

标签: c# asp.net asp.net-mvc-4 pdf-generation wkhtmltopdf

前几天我试图创建一个将url转换为pdf的Web应用程序。最后我在wkhtmltopdf.exe的帮助下做到了这一点 我的课程代码如下:

public class PDFGenerator
{
    public static string HtmlToPdf(string pdfOutputLocation, string outputFilenamePrefix, string[] urls,
        string[] options = null,
        string pdfHtmlToPdfExePath = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
    {
        string urlsSeparatedBySpaces = string.Empty;
        try
        {
            //Determine inputs
            if ((urls == null) || (urls.Length == 0))
                throw new Exception("No input URLs provided for HtmlToPdf");
            else
                urlsSeparatedBySpaces = String.Join(" ", urls); //Concatenate URLs

            string outputFolder = pdfOutputLocation;
            string outputFilename = outputFilenamePrefix + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss-fff") + ".PDF"; // assemble destination PDF file name

            var p = new System.Diagnostics.Process()
            {
                StartInfo =
                {
                    FileName = pdfHtmlToPdfExePath,
                    Arguments = ((options == null) ? "" : String.Join(" ", options)) + " " + urlsSeparatedBySpaces + " " + outputFilename,
                    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 = HttpContext.Current.Server.MapPath(outputFolder)
                }
            };

            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);
        }
        catch (Exception exc)
        {
            throw new Exception("Problem generating PDF from HTML, URLs: " + urlsSeparatedBySpaces + ", outputFilename: " + outputFilenamePrefix, exc);
        }
    }
}

我的按钮点击事件代码在下面给出

//Create PDF from a single URL
    var pdfUrl = PdfGenerator.PDFGenerator.HtmlToPdf(pdfOutputLocation: "~/PDFs/",
        outputFilenamePrefix: "GeneratedPDF",
        urls: new string[] { "http://news.bbc.co.uk" });

    //Create PDF from multiple URLs
    pdfUrl = PdfGenerator.PDFGenerator.HtmlToPdf(pdfOutputLocation: "~/PDFs/",
        outputFilenamePrefix: "GeneratedPDF",
        urls: new string[] { "http://www.google.co.uk", "http://news.bbc.co.uk" });

所有代码都正常运行并在我的PDF代码中保存pdf。但我有两个问题:

  1. 当我托管我的网站时,由于C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe执行错误,此代码无效。是否有任何dll库可用于wkhtmltopdf?
  2. 当我运行此代码时,pdf以静默模式保存。我想知道这可以通过保存对话框保存pdf或者询问用户要保存pdf的文件夹位置吗? 抱歉我的英文不好。

0 个答案:

没有答案