简体   繁体   English

使用wkhtmltopdf从HTML生成PDF

[英]Using wkhtmltopdf to generate PDF from HTML

I develop an intranet website. 我开发了一个Intranet网站。 And i want to use wkhtmltopdf to generate a pdf from a page of my website. 我想使用wkhtmltopdf从我的网站页面生成pdf。 After some researches, i found wkhtmltopdf. 经过一些研究,我发现了wkhtmltopdf。 The application works great. 该应用程序运行良好。 But i'm new in C# and even i read Calling wkhtmltopdf to generate PDF from HTML i cannot work this code. 但是我是C#的新手,甚至我都读过《 调用wkhtmltopdf从HTML生成PDF》,我无法使用此代码。

EDIT 编辑

Here is the code, it seems i have an error (The directory name is invalid) at p.Start(); 这是代码,看来我在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;
}
}

Thank you for your help. 谢谢您的帮助。

These are just methods. 这些只是方法。 You must put them into a class. 您必须将它们放在班上。 So add something like "class MyClass { // yourcode here } around it 因此,在其周围添加类似“ class MyClass {// yourcode here}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM