Html导出Pdf
最近领导给了一个新的需求:给了我一个html页面,让我导出Pdf页面
由于以前没有搞过这方面的需求,所以查百度找资料,找了一大堆的好东西,像ItextSharp和wkhtmltopdf
废话不说,进入正题
ItextSharp对Html5的canvas和css,js等支持不是很好,只适用于简单的页面导出。故放弃
导出方法一:使用wkhtmltopdf
这个需要安装wkhtmltopdf: https://wkhtmltopdf.org/downloads.html 下面的变量就是wkhtmltopdf的安装目录
public ActionResult ExportSocialPDF(int testerid)
{
try
{
var tester = _testerBll.Details(testerid);
string folder = string.Format("~/Temp/{0}", DateTime.Now.ToString("yyyyMMdd"));
if (!System.IO.Directory.Exists(Server.MapPath(folder)))
{
System.IO.Directory.CreateDirectory(Server.MapPath(folder));
}
string fileName = string.Format("{0}-社会综合素质测试{1}", tester.name, DateTime.Now.ToString("yyyyMMddHHmmss"));
string pdfpath = fileName + ".pdf";
ExportSocialPDFCore(tester, folder, pdfpath);
string filePath = Server.MapPath(folder) + "/" + pdfpath;
new System.Threading.Thread(DeleteOldFileFolder).Start();
return File(filePath, "application/octet-stream", System.IO.Path.GetFileName(filePath));
}
catch (Exception ex)
{
log.Error(ex);
return View(ex);
}
}
public void ExportSocialPDFCore(HqftTestPaper.Entity.t_testerEntity tester, string folder, string pdfpath)
{
string pdf = @"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe";
//string url = "http://localhost/TestManage/WordTemplate/index.html";
string url = Url.Action("ExportPreview", "ExportPDF", new { testerid = tester.id }); url = string.Format("http://{0}:{1}{2}",Request.Url.Host, Request.Url.Port, url); string add = url + " \"" + Server.MapPath(folder + "/" + pdfpath) + "\"";
Process p = System.Diagnostics.Process.Start(pdf, add);
p.WaitForExit();
}
public void DeleteOldFileFolder()
{
string strPath = Server.MapPath("~/Temp/");
string[] fileNames = System.IO.Directory.GetDirectories(strPath);
foreach (string fileName in fileNames)
{
string name = fileName.Substring(strPath.Length);
if (string.Compare(DateTime.Now.ToString("yyyyMMdd"), name) > )
{
System.IO.Directory.Delete(fileName, true);
}
}
}
注释:
1、t_testerEntity是个需要导出的测试者的类,大家可以自行脑补,只要一个id获取数据就可以了
2、此方法是现在本地生成一个Pdf,然后把路径传到View让浏览器下载,所以需要一个删除旧文件的方法
3、根据cshtml下载的页面,必须能够无限制的访问,就是直接把路径贴在浏览器中可以直接访问。
如果为了系统安全性,加了访问限制的,需要新建一个不受限制的Controller
导出方法二:页面先截图,然后生成Pdf
这个用的是Winform的WebBrowser控件,有限制:你的IE和你的WebBrowser内核可能不是一个版本的。Css支持率极低。个人认为不好用
using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms; namespace ExportPDF.Common
{
public class HtmlToPdf
{
WebBrowser webBrowser; public void ConvertToImage(object url)
{
//string strUrl = "http://echarts.baidu.com/demo.html#pie-legend";
webBrowser = new WebBrowser();
//改变webBrowser内核版本
WebBrowserOper.BrowserEmulationSet();
webBrowser.AllowNavigation = true;
webBrowser.Url = new Uri(url.ToString());
webBrowser.ScrollBarsEnabled = true;
DateTime dtime = DateTime.Now;
double timespan = ;
while (timespan < || webBrowser.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
DateTime time2 = DateTime.Now;
timespan = (time2 - dtime).TotalSeconds;
} if (webBrowser.ReadyState == WebBrowserReadyState.Complete)
{
//htmlstr = webBrowser.DocumentText;
webBrowser_DocumentCompleted();
}
//string html = ""; //webBrowser.DocumentText = html;
} /// <summary>
/// 在单线程中启用浏览器
/// </summary>
public void RunWithSingleThread()
{
string url = "http://localhost/Export/template/index.html";
ParameterizedThreadStart ps = new ParameterizedThreadStart(ConvertToImage);
Thread t = new Thread(ps);
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start(url);
} private void webBrowser_DocumentCompleted()
{
//获取解析后HTML的大小
System.Drawing.Rectangle rectangle = webBrowser.Document.Body.ScrollRectangle;
int width = rectangle.Width;
int height = rectangle.Height; //设置解析后HTML的可视区域
webBrowser.Width = width;
webBrowser.Height = height; Bitmap bitmap = new System.Drawing.Bitmap(width, height);
webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(, , width, height)); //设置图片文件保存路径和图片格式,格式可以自定义
string filePath = AppDomain.CurrentDomain.BaseDirectory + "/SaveFile/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";
bitmap.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); //创建PDF
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "/SaveFile/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".pdf", FileMode.Create); byte[] result = CreatePDF(bitmap, width, height); fileStream.Write(result, , result.Length); fileStream.Close();
fileStream.Dispose();
} private byte[] CreatePDF(Bitmap bitmap, int width, int height)
{
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(new iTextSharp.text.Rectangle(, , width, height), , , , ); // 左右上下 PdfWriter writer = PdfWriter.GetInstance(doc, ms); writer.CloseStream = false; doc.Open(); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Png); img.ScalePercent(); // 放缩比例 doc.Add(img); // 添加图片对像
doc.Close(); return ms.ToArray();
}
}
}
}
using Microsoft.Win32;
using System;
using System.Diagnostics; namespace ExportPDF.Common
{
public static class WebBrowserOper
{
public static void WebBrowserVersionEmulation()
{
const string BROWSER_EMULATION_KEY = @"SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION";
//const string BROWSER_EMULATION_KEY = @"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION"; // app.exe and app.vshost.exe
RegistryKey browserEmulationKey = Registry.LocalMachine.OpenSubKey(BROWSER_EMULATION_KEY,RegistryKeyPermissionCheck.ReadWriteSubTree) ?? Registry.LocalMachine.CreateSubKey(BROWSER_EMULATION_KEY);
//RegistryKey browserEmulationKey = Registry.CurrentUser.OpenSubKey(BROWSER_EMULATION_KEY,RegistryKeyPermissionCheck.ReadWriteSubTree) ?? Registry.LocalMachine.CreateSubKey(BROWSER_EMULATION_KEY);
if (browserEmulationKey != null)
{
String appname = Process.GetCurrentProcess().ProcessName + ".exe";
//Webpages are displayed in IE10 Standards mode, regardless of the !DOCTYPE directive.
const int browserEmulationMode = ; if ((int)browserEmulationKey.GetValue(appname) != )
{
browserEmulationKey.SetValue(appname, browserEmulationMode, RegistryValueKind.DWord);
}
browserEmulationKey.Close();
}
} /// <summary>
/// IE WebBrowser内核设置
/// </summary>
public static void BrowserEmulationSet()
{
//当前程序名称
var exeName = Process.GetCurrentProcess().ProcessName + ".exe";
//系统注册表信息
var mreg = Registry.LocalMachine;
//IE注册表信息
var ie = mreg.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION", RegistryKeyPermissionCheck.ReadWriteSubTree);
if (ie != null)
{
try
{
var val = ieVersionEmulation(ieVersion());
if (val != )
{
ie.SetValue(exeName, val);
}
mreg.Close();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
} /// <summary>
/// IE版本号
/// </summary>
/// <returns></returns>
static int ieVersion()
{
//IE版本号
RegistryKey mreg = Registry.LocalMachine;
mreg = mreg.CreateSubKey("SOFTWARE\\Microsoft\\Internet Explorer"); //更新版本
var svcVersion = mreg.GetValue("svcVersion");
if (svcVersion != null)
{
mreg.Close();
var v = svcVersion.ToString().Split('.')[];
return int.Parse(v);
}
else
{
//默认版本
var ieVersion = mreg.GetValue("Version");
mreg.Close();
if (ieVersion != null)
{
var v = ieVersion.ToString().Split('.')[];
return int.Parse(v);
}
}
return ;
} /// <summary>
/// 根据IE版本号 返回Emulation值
/// </summary>
/// <param name="ieVersion"></param>
/// <returns></returns>
static int ieVersionEmulation(int ieVersion)
{
//IE7 7000 (0x1B58)
if (ieVersion < )
{
return ;
}
if (ieVersion == )
{
return 0x1F40;//8000 (0x1F40)、8888 (0x22B8)
}
if (ieVersion == )
{
return 0x2328;//9000 (0x2328)、9999 (0x270F)
}
else if (ieVersion == )
{
return 0x02710;//10000 (0x02710)、10001 (0x2711)
}
else if (ieVersion == )
{
return 0x2AF8;//11000 (0x2AF8)、11001 (0x2AF9
}
return ;
}
}
}
另外还有一个导出Html的
using System.IO;
using System.Text;
using System.Web; namespace ExportPDF.Common
{
public class ExportHtml
{
public void TemplateExport()
{
string templatePath = HttpContext.Current.Server.MapPath("~/Template/") + "index.html";
string template = "";
using (StreamReader sr = new StreamReader(templatePath))
{
template=sr.ReadToEnd();
}
//新的内容
StringBuilder context = new StringBuilder();
/*
foreach (Student stu in stulist)
{
context.Append("<tr>");
context.Append("<td>" + stu.XueHao + "</td><td>" + stu.XingMing + "</td>");
context.Append("</tr>");
}
string newContext = template.Replace("$student$", context.ToString());
*/
//把newContext写入报表中
string path = HttpContext.Current.Server.MapPath("~/SaveFile/") + "report.html";
using (StreamWriter sw = new StreamWriter(path, false))
{
sw.WriteLine(template);
}
}
}
}
言尽于此
Html导出Pdf的更多相关文章
- .Net导出pdf文件,C#实现pdf导出
最近碰见个需求需要实现导出pdf文件,上网查了下代码资料总结了以下代码.可以成功的实现导出pdf文件. 在编码前需要在网上下载个itextsharp.dll,此程序集是必备的.楼主下载的是5.0版本, ...
- JS导出PDF插件(支持中文、图片使用路径)
在WEB上想做一个导出PDF的功能,发现jsPDF比较多人推荐,遗憾的是不支持中文,最后找到pdfmake,很好地解决了此问题.它的效果可以先到http://pdfmake.org/playgroun ...
- ITextSharp导出PDF表格和图片(C#)
文章主要介绍使用ITextSharp导出PDF表格和图片的简单操作说明,以下为ITextSharp.dll下载链接 分享链接:http://pan.baidu.com/s/1nuc6glj 密码:3g ...
- JAVA导出pdf实例
一.直接导出成PDF Java代码 1. import java.io.FileNotFoundException; 2. import java.io.FileOutputStream; 3. ...
- 利用ITextSharp导出PDF文件
最近项目中需要到处PDF文件,最后上网搜索了一下,发现ITextSharp比较好用,所以做了一个例子: public string ExportPDF() { //ITextSharp Usage / ...
- iText导出pdf、word、图片
一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生成PDF报表,客户端采用超级连接显示或 ...
- Itext导出PDF,word,图片案例
iText导出pdf.word.图片 一.前言 在企业的信息系统中,报表处理一直占比较重要的作用,本文将介绍一种生成PDF报表的Java组件--iText.通过在服务器端使用Jsp或JavaBean生 ...
- Ireport 报表导出 Poi + ireport 导出pdf, word ,excel ,htm
Ireport 报表导出 Poi + ireport 导出pdf, doc ,excel ,html 格式 下面是报表导出工具类reportExportUtils 需要导出以上格式的报表 只需要调用本 ...
- Spring Boot 系列教程18-itext导出pdf下载
Java操作pdf框架 iText是一个能够快速产生PDF文件的java类库.iText的java类对于那些要产生包含文本,表格,图形的只读文档是很有用的.它的类库尤其与java Servlet有很好 ...
- 纯前端导出pdf文件
纯前端js导出pdf,已经用于生产环境. 工具: 1.html2canvas,一种让html转换为图片的工具. 2.pdfmake或者jspdf ,一种生成.编辑pdf,并且导出pdf的工具. pdf ...
随机推荐
- 主成分分析(PCA)及其在R里的实现
主成分分析(principal component analysis,PCA)是一种降维技术,把多个变量化为能够反映原始变量大部分信息的少数几个主成分.设X有p个变量,为n*p阶矩阵,即n个样本的p维 ...
- Android控件——AutoCompleteTextView与MultiAutoCompleteTextView(实现自动匹配输入的内容)
------------------------------------AutoCompleteTextView----------------------
- Java中通过方法创建一个http连接并请求(服务器间进行通信)
服务器间进行通信只能通过流(Stream)的方式进行,不能用方法的返回值. 1.Java代码创建一个连接并请求该连接返回的数据 doGet()方法,execute()方法中调用 package dem ...
- CTF两个经典的文件包含案例
案例一URL:http://120.24.86.145:8003/代码 <?php include "waf.php"; include "flag.php&quo ...
- source insight 保存时删除多余空格,去除多余空格 space tab键【转】
转自:http://blog.csdn.net/lanmanck/article/details/8638391 上传源码时最好把空格行去掉,以前介绍了使用notepad++,现在发现,习惯用sour ...
- perl多线程tcp端口扫描器(原创)
perl多线程tcp端口扫描器(原创) http://bbs.chinaunix.net/thread-1457744-1-1.html perl socket 客户端发送消息 http://blog ...
- binlog_server备份binlogs
在主库上建一个复制用的账号: root@localhost [(none)]>grant replication slave on *.* to 'wyz'@'%' identified by ...
- 2015多校第6场 HDU 5358 First One 枚举,双指针
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5358 题意:如题. 解法:观察式子发现,由于log函数的存在,使得这个函数的值域<=34,然后我 ...
- Scrapy爬虫:抓取大量斗图网站最新表情图片
一:目标 第一次使用Scrapy框架遇到很多坑,坚持去搜索,修改代码就可以解决问题.这次爬取的是一个斗图网站的最新表情图片www.doutula.com/photo/list,练习使用Scrapy ...
- [Deep dig] ViewController初始化过程调查
代码:https://github.com/xufeng79x/ViewControllerLife 1.简介: 介绍xib方式.storyborad方式以及code方式下ViewController ...