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,坑少,比较靠谱. 一. ...
随机推荐
- 基于requests模块的cookie,session和线程池爬取
目录 基于requests模块的cookie,session和线程池爬取 基于requests模块的cookie操作 基于requests模块的代理操作 基于multiprocessing.dummy ...
- PAT 1039. Course List for Student
Zhejiang University has 40000 students and provides 2500 courses. Now given the student name lists o ...
- hdu 4941 stl的map<node,int>用法
#include<iostream> #include<cstdio> #include<cstring> #include<map> using na ...
- class类加载机制
1.类的加载过程 a.加载-链接-初始化-使用-卸载 加载: 查找并加载类的二进制数据 链接: 验证类的正确性,为类的静态变量分配内存,并将其初始化为默认值,把类的符号引用转换为直接引用. 初始化: ...
- posix线程库1
posix线程库重要的程度不言而喻,这些天学习这个,参考 https://www.ibm.com/developerworks/cn/linux/thread/posix_thread1/ 首先先 ...
- [ javascript ] getElementsByClassName与className和getAttribute!
对于javascript中的getElementsByClassName 在IE 6/7/8 不支持问题. 那么须要模拟出getElementsByClassName 须要採用className属性 ...
- CSDN挑战编程——《绝对值最小》
绝对值最小 题目详情: 给你一个数组A[n],请你计算出ans=min(|A[i]+A[j]|)(0<=i,j<n). 比如:A={1, 4, -3}, 则: |A[0] + A[0]| ...
- BPMN使用工具
EA 非常多设计人员都在使用EA.他不仅支持UML,相同也全然支持BPMN2.0.<BPMN规范中的三种视图 >展示的BPMN中三种视图就是使用此工具所绘制. activitidesig ...
- 利用Node.js对某智能家居server重构
原文摘自我的前端博客,欢迎大家来訪问 http://www.hacke2.cn 之前负责过一个智能家居项目的开发,外包重庆一家公司的.我们主要开发server监控和集群版管理. 移动端和机顶盒的远程通 ...
- SQL Server高速导入数据分享
SQL Server高速导入数据,能够尝试的方法例如以下:CTE.OpenRowSet/OpenDataSource.BULK INSERT.bcp.Shell. 以下依次介绍这几种办法. 1.CTE ...