使用wkhtmltopdf从HTML生成PDF

本文关键字:生成 PDF HTML wkhtmltopdf 使用 | 更新日期: 2023-09-27 18:16:58

我开发了一个内部网网站。我想使用wkhtmltopdf从我的网站的页面生成pdf。经过一番研究,我找到了wkhtmltopdf。该应用程序运行良好。但我是c#的新手,甚至我读到调用wkhtmltopdf从HTML生成PDF,我不能工作这个代码。

编辑

这是代码,似乎我有一个错误(目录名无效)在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;
}
}

谢谢你的帮助。

使用wkhtmltopdf从HTML生成PDF

这些只是方法。你必须把他们分成一个班。所以在它周围加上"class MyClass {//yourcode here} "