• ASP.NET C#根据HTML页面导出PDF


    启明星采购系统里,新增了导出PDF功能。整个功能使用了第三方软件 wkhtmltopdf(下载) 官网 https://wkhtmltopdf.org/ 提供有更多版本下载

    他可以把HTML页面转换为PDF,该软件简直是incredible-不可思议了,功能太强大了。

    因为,我有一个HTML,引用了很多CSS,而页面基本上都是JS动态生成的,一直担心wkhtmltopdf生成的PDF会是一个空白

    没相当,转换后,那些CSS和JS没有“失真”。

    下面是利用C#将HTML生成PDF的代码:

    复制代码
               string url = "http://www.dotnetcms.org/About.aspx";  
      string pdf = "c:pdfinwkhtmltopdf.exe"
    string filename = Guid.NewGuid().ToString(); string pdfpath = filename + ".pdf"; Process p = System.Diagnostics.Process.Start(pdf, url + " "" + Server.MapPath(pdfpath)+"""); p.WaitForExit(); //方法1,使用下面代码,在线打开 // Response.Redirect(pdfpath); //方法2,使用下面代码,让客户下载 FileStream fs = new FileStream(Server.MapPath(pdfpath), FileMode.Open); byte[] file = new byte[fs.Length]; fs.Read(file, 0, file.Length); fs.Close(); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");//以二进制流模式,强制下载 Response.ContentType = "application/octet-stream"; Response.BinaryWrite(file);
    复制代码

    在上面代码里,url为需要传递的页面,pdf参数为wkhtmltopdf.exe为你实际安装的路径。

    当然,在实际环境里,如果你使用IIS,并且希望通过ASP.NET生成PDF,需要注意权限,首先,找到应用程序所使用的应用程序池,点击“应用程序池”上的高级,有一个“标识”,将默认的ApplicationPoolIdentity修改为LocalSystem。否则,可能因为权限不足而调用exe失败。

  • 相关阅读:
    TCP/IP Checksum 吐槽
    RHEL安装时加载第三方raid驱动
    RHEL Channel Bonding
    关于case语句中声明变量并初始化的注意事项
    Allocators与Criterion的相同点及区别
    BitSet构造函数的两种特例
    Bitset<>用于unordered container时的默认hash函数
    C++ Stream
    C++Exception知识整理
    C++String知识整理
  • 原文地址:https://www.cnblogs.com/ztf20/p/10414832.html
Copyright © 2020-2023  润新知