C#使用wkhtmltopdf,把HTML生成PDF(包含分页)
最近花了2天多的时间终于把HTML生成PDF弄好了。步骤如下:
1、首先是技术选型。看了好多都是收费的就不考虑了。
免费的有:
- jsPDF(前端生成,清晰度不高,生成比较慢)
- iText(严格要求html标签。这个好像也是收费的)
- wkhtmltopdf(简单、配置选项多、生成快、支持跨平台、也支持HTML生成图片)
因此选择wkhtmltopdf。
2、前期准备,首先需要下载wkhtmltopdf.exe(下载地址:https://wkhtmltopdf.org/downloads.html)阅读配置参数(https://wkhtmltopdf.org/usage/wkhtmltopdf.txt)
常用参数:
- -T 0 :设置上下左右margin-top=0(-B 0 -L 0 -R 0 -T 0,上下左右都设置一下)
- -s A4:设置A4纸大小,默认A4
- --disable-smart-shrinking:禁止缩放(不设置这个,生成的pdf会缩放)
- --zoom 1:设置缩放系数,默认为1。如果--disable-smart-shrinking设置了,--zoom就不用设置了。
- --cookie name value:设置cookie,如果下载的url需要登录(用cookie),那么这个参数很重要。
3、设置需要打印的页面(核心是分页)
A4纸大小:210mm×297mm,因此页面的每个div大小也是A4纸大小。
这里的页面设置很重要。另外,设置了分页的页码,示例如下:
<style>
#view {
height: %;
margin: auto;
padding: ;
width: 210mm;
} /*设置A4打印页面*/
/*备注:由于@是否特殊符号,样式放在css文件中没问题,放在cshtml文件就不行了,需要@@。*/
@preview-item {
size: A4;
margin: ;
} @media print {
.preview-item {
margin: ;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}
.preview-item {
width: %;
height: 297mm;
position: relative;
} .page-view {
position: absolute;
width: %;
text-align: center;
height: 60px;
line-height: 60px;
bottom: ;
}
</style> <div id="view">
<div class="preview-item">
<div class="preview-item-body">这是第一页</div>
<div class="page-view">/</div>
</div>
<div class="preview-item">
<div class="preview-item-body">这是第二页</div>
<div class="page-view">/</div>
</div>
<div class="preview-item">
<div class="preview-item-body">这是第三页</div>
<div class="page-view">/</div>
</div>
</div>
4、C#代码实现(核心是Arguments的设置)
/// <summary>
/// HTML生成PDF
/// </summary>
/// <param name="url">url地址(需要包含HTTP://)</param>
/// <param name="path">PDF存放路径(可以是aaa.pdf,也可以用路径,只能是绝对地址,如:D://aaa.pdf)</param>
public static bool HtmlToPdf(string url, string path)
{
path = HttpContext.Current.Server.MapPath(path);string cookie = "cookieKey cookieValue";//改为为你自己的
string Arguments = "-q -B 0 -L 0 -R 0 -T 0 -s A4 --no-background --disable-smart-shrinking --cookie " + cookie + " " + url + " " + path; //参数可以根据自己的需要进行修改 try
{
if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
return false;
var p = new Process();
string str = HttpContext.Current.Server.MapPath("/htmlToPDF/wkhtmltopdf.exe");
if (!File.Exists(str))
return false;
p.StartInfo.FileName = str;
p.StartInfo.Arguments = Arguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = false;
p.Start();
p.WaitForExit();
System.Threading.Thread.Sleep(); return true;
}
catch (Exception ex)
{
LogHelper.WriteError(ex);
}
return false;
}
方法的调用:
string url = Request.Url.AbsoluteUri.Replace("DownloadPDF", "Detail");//DownloadPDF是下载页面,Detail是上面的HTML页面
string pdfDirectory = "/Data/PDF/";
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(pdfDirectory)))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(pdfDirectory));
}
string path = pdfDirectory + Guid.NewGuid() + ".pdf";
HtmlToPdf(url, path); if (!System.IO.File.Exists(Utils.GetMapPath(path)))//如果生成失败,重试一次
{
HtmlToPdfHelper.HtmlToPdf(url, path);
} if (!System.IO.File.Exists(Utils.GetMapPath(path)))//如果生成失败,重试一次
{
HtmlToPdfHelper.HtmlToPdf(url, path);
}
5、ok,采坑结束~
C#使用wkhtmltopdf,把HTML生成PDF(包含分页)的更多相关文章
- wkhtmltopdf 将网页生成pdf文件
先安装依赖 yum install fontconfig libXrender libXext xorg-x11-fonts-Type1 xorg-x11-fonts-75dpi freetype l ...
- C# html生成PDF遇到的问题,从iTextSharp到wkhtmltopdf
我们的网站业务会生成一个报告,用网页展示出来,要有生成pdf并下载的功能,关键是生成pdf. 用内容一段段去拼pdf,想想就很崩溃,所以就去网上找直接把html生成pdf的方法. 网上资料大部分都是用 ...
- wkhtmltopdf 生成pdf
public class PdfHelper { static string RootPath { get { string AppPath = ""; HttpContext H ...
- 页面导出生成pdf,使用wkhtmltopdf第三方工具
把页面导出生成pdf,这里用到第三方的工具,使用方法中文文档没有找到,网上也没找到网友详细的神作.没有深入研究,所以也不赘述了,当然最基本的使用大多数也够用了,详细参数的官网也没介绍,大家使用的时候, ...
- java调用wkhtmltopdf生成pdf文件,美观,省事
最近项目需要导出企业风险报告,文件格式为pdf,于是搜了一大批文章都是什么Jasper Report,iText ,flying sauser ,都尝试了一遍,感觉不是我想要的效果, 需要自己调整好多 ...
- wkhtmltopdf+itext实现html生成pdf文件的打印下载(适用于linux及windows)
目中遇到个根据html转Java的功能,在java中我们itext可以快速的实现pdf打印下载的功能,在itext中我们一般有以下三中方式实现 配置pdf模板,通过Adobe Acrobat 来设置域 ...
- 使用wkhtmltopdf工具生成pdf
背景:将前台页面转换成pdf文档保存到服务器 最开始计划使用canvas2pdf在前端进行生成.但是canva2pdf转换的pdf有严重的失真问题,然后决定使用wkhtmltopdf工具进行生成. 思 ...
- Python之将Python字符串生成PDF
笔者在今天的工作中,遇到了一个需求,那就是如何将Python字符串生成PDF.比如,需要把Python字符串'这是测试文件'生成为PDF, 该PDF中含有文字'这是测试文件'. 经过一番检索, ...
- 使用puppeteer生成pdf与截图
之前写过一篇 vue cli2 使用 wkhtmltopdf 踩坑指南,由于wkhtmltopdf对vue的支持并不友好,而且不支持css3,经过调研最终选择puppeteer,坑少,比较靠谱. 一. ...
随机推荐
- Linux判断
#字符串比较if [ "$1" == "判断条件" ] then echo "$1" elif [ "$1" == &q ...
- 66.零停机下reindex
主要知识点: 理解reindex的使用场景和必要性 学会reindex 一.理解reindex的使用场景和必要性 假设:在某一个index中依靠dynamic mapping插入数据, ...
- 用Twebbrowser做可控编辑器与MSHTML(插入表格)
在插入表格问题上出现与结果想象不一样的问题.看代码 <table border="1" cellpadding="0" width="100%& ...
- 1、ceph-deploy之部署ceph集群
环境说明 server:3台虚拟机,挂载卷/dev/vdb 10G 系统:centos7.2 ceph版本:luminous repo: 公网-http://download.ceph.com,htt ...
- CODEVS1187 Xor最大路径 (Trie树)
由于权值是在边上,所以很容易发现一个性质:d(x,y)=d(x,root) xor d(y,root). 因为有了这个性质,那么就很好做了.对于每一个点统计到root的距离,记为f 数组. 将f数组里 ...
- LSB、MSB是什么单位
最低有效位 (LSB: Least Significant Bit) 最低有效位(LSB)是给这些单元值的一个二进制整数位位置,就是,决定是否这个数字是偶数或奇数.LSB有时候是指最右边的位,因为 ...
- Human Gene Functions POJ 1080 最长公共子序列变形
Description It is well known that a human gene can be considered as a sequence, consisting of four n ...
- pg 学习资料
文/谭峰 DBA,PostgreSQL专家 开源数据库 PostgreSQL 中文资料非常缺乏,很多社区朋友苦于上手的中文资料少,因此汇总收集以下 PostgreSQL 中文资料,包括 Postgre ...
- [RxJS] AsyncSubject and ReplaySubject - Learn the Differences
We can use Subject as Observable and Observer: // Subject should be only used to emit value for priv ...
- Think in ISP(image sensor pipe )之How to implement an effecitive AE
How to implement a effecitive AE. AE(自己主动曝光) 1)try Minual exposure //time,line 2)try Max exposure // ...