使用wkhtmltopdf从HTML生成PDF

时间:2014-08-07 09:31:19

标签: c# pdf wkhtmltopdf

我开发了一个内部网网站。 我想使用wkhtmltopdf从我的网站页面生成pdf。经过一些研究,我找到了wkhtmltopdf。该应用程序运行良好。但我是C#的新手,甚至我读Calling wkhtmltopdf to generate PDF from HTML我无法使用此代码。

修改

这是代码,似乎我在p.Start()时有错误(目录名无效); :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Web;
using System.Web.Hosting;
using System.Diagnostics;
using System.IO;

public partial class _zipdownload : System.Web.UI.Page  {

protected void DoDownload(object sender, EventArgs e)
{
    var url = "http://dlp-wdi/TR/view_I.asp?ID=11080";
    var file = WKHtmlToPdf(url);
    if (file != null)
    {
        Response.ContentType = "Application/pdf";
        Response.BinaryWrite(file);
        Response.End();
    }
}

public byte[] WKHtmlToPdf(string url)
{
    var fileName = " - ";
    var wkhtmlDir = "bin\\wkhtmltopdf\\";
    var wkhtml = "bin\\wkhtmltopdf\\wkhtmltopdf.exe";
    var p = new Process();

    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.RedirectStandardError = true;
    p.StartInfo.RedirectStandardInput = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.FileName = wkhtml;
    p.StartInfo.WorkingDirectory = wkhtmlDir;

    string switches = "";
    switches += "--print-media-type ";
    switches += "--margin-top 10mm --margin-bottom 10mm --margin-right 10mm --margin-left 10mm ";
    switches += "--page-size Letter ";
    p.StartInfo.Arguments = switches + " " + url + " " + fileName;
    p.Start();

    //read output
    byte[] buffer = new byte[32768];
    byte[] file;
    using(var ms = new MemoryStream())
    {
        while(true)
        {
            int read =  p.StandardOutput.BaseStream.Read(buffer, 0,buffer.Length);

            if(read <=0)
            {
                break;
            }
            ms.Write(buffer, 0, read);
        }
        file = ms.ToArray();
    }

    // wait or exit
    p.WaitForExit(60000);

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

    return returnCode == 0 ? file : null;
}
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这些只是方法。你必须把它们放进一堂课。所以在它周围添加类似&#34;类MyClass {// yourcode here}