32450新蒲京网站HTML生成PDF(c#)

2019-10-30 17:52 来源:未知

Calling wkhtmltopdf to generate PDF from HTML 老外最多人加分的那篇做法,使用wkhtmtopdf(GPL协议)可以省很多程序代码, 首先到官网
找installer.exe下载

对页面生成PDF

wkhtmltopdf,一个集成好了的exe文件(C++编写),基本的调用方法是, wkhtmltopdf.exe
count/register e:yupskyreg.pdf

public bool HtmlToPdf(string url, string path)
    {
        try
        {                  
            string filename = PdfFolder + "\" + path + ".pdf";

            Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = @"C:PDFFolderwkhtmltopdf.exe";
            //p.StartInfo.UserName = "administrator"; //用户名
            //p.StartInfo.Password = StringToSecureString("password01!");//用户密码


            // p.StartInfo.Arguments = " " + """ + url + """ + " " + """ + filename + """;
            p.StartInfo.Arguments = string.Format("  "{0}" "{1}" --password "{2}" --username "{3}"", url, filename, "domainpassword", "password");
            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 = "c:\PDFFolder";

            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);

        }
        catch (Exception ex)
        {

        }
        return false;
    }
     public static SecureString StringToSecureString(String str)
        {
            SecureString secureStr = new SecureString();
            char[] chars = str.ToCharArray();
            for (int i = 0; i < chars.Length; i++)
            {
                secureStr.AppendChar(chars[i]);
            }
            return secureStr;
        }

,可以先在命令行测试一下,有其他的需要可以在命令行通过wkhtmltopdf --help查询,如果是超长页的花,可以用命令

 

wkhtmltopdf.exe
count/register e:yupskyreg.pdf  -H --outline (-H是添加默认标题,--outline是添加pdf的左侧概要哦!)而且可以批量生成哦,中间用空格隔开32450新蒲京网站 1

用法:HtmlToPdf("", "xxxxx")

 

wkhtmltopdf.exe文件地址: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
/*要引用以下命名空间*/
using System.Diagnostics;
using System.IO;

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

//Button的Click事件(把Url的网页内容转成PDF)
    protected void btn_execute_Click(object sender, EventArgs e)
    {

        //因为Web 是多线程环境,避免甲产生的文件被乙下载去,所以档名都用唯一
        string fileNameWithOutExtention = Guid.NewGuid().ToString();

        //执行wkhtmltopdf.exe
        Process p = System.Diagnostics.Process.Start(@"D:wkhtmltopdfwkhtmltopdf.exe", @" D:" + fileNameWithOutExtention + ".pdf");

        //若不加这一行,程序就会马上执行下一句而抓不到文件发生意外:System.IO.FileNotFoundException: 找不到文件 ''。
        p.WaitForExit();

        //把文件读进文件流
        FileStream fs = new FileStream(@"D:" + fileNameWithOutExtention + ".pdf", FileMode.Open);
        byte[] file = new byte[fs.Length];
        fs.Read(file, 0, file.Length);
        fs.Close();

        //Response给客户端下载
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=" + fileNameWithOutExtention + ".pdf");//强制下载
        Response.ContentType = "application/octet-stream";
        Response.BinaryWrite(file);

    }
}

在GitHub上发现2个相关的项目,其中Pechkin这个项目不需要单独安装wkhtmltopdf ,就是.NET的库了。

C# wrapper around excellent wkhtmltopdf console utility 

.NET Wrapper for WkHtmlToPdf static DLL. Allows you to utilize full power of the libra:

TAG标签:
版权声明:本文由32450新蒲京网站发布于葡萄游戏厅_卡牌游戏,转载请注明出处:32450新蒲京网站HTML生成PDF(c#)