.net将html转换PDF

需要使用iTextSharp库文件

using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
 
string path = Server.MapPath("~/Views/ExportExcel/ExcelHtml.html");
WebClient wc = new WebClient();
string htmlText = wc.DownloadString(path);


// string imgpath = Server.MapPath("~/Content/logo.png");
//string htmlText = @"<html>
//<body>
//<div>
//添加圖片
//<img src='" + imgpath + @"' />
//<table style='width:100%' class='tdCollapse'>
//<tr>
//<td class='td1'>safs</td>
//<td class='td2' class='tdBorder'>DSA</td>
//<td class='td3'>dfsaf</td>
//<td class='td4' class='tdBorder'>sdfsfsf</td>
//<td class='td5'>dfsaf</td>
//<td class='td5'>dfsafsfsf</td>
//<td class='td5'>gfdgdg</td>
//</tr></table></div></body></html>";
a.方法一:
MemoryStream m = new MemoryStream();
Document document = new Document();
HTMLWorker worker = new HTMLWorker(document);
try
{
//解决 导出的PDF 中文不显示  将C:/Windows/Fonts/simhei.ttf文件考到本地Fonts文件夹中
string Fontpath = Server.MapPath("~/Fonts/");
string fontFilePath = Path.Combine(Fontpath, "simhei.ttf");//C:/Windows/Fonts/simhei.ttf
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/pdf";
Response.AddHeader("Content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(System.DateTime.Now + ".pdf", Encoding.UTF8));

PdfWriter.GetInstance(document, m);
document.Open();
StyleSheet styles = new StyleSheet();
FontFactory.Register(fontFilePath);
styles.LoadTagStyle("td", "face", "SIMHEI");
styles.LoadTagStyle("td", "encoding", "Identity-H");
styles.LoadTagStyle("td", "leading", "18,0");
styles.LoadTagStyle("body", "face", "SIMHEI");
styles.LoadTagStyle("body", "encoding", "Identity-H");
styles.LoadTagStyle("body", "leading", "10,0");
worker.SetStyleSheet(styles);
TextReader fileReader = new StringReader(htmlText);
worker.Parse(fileReader);
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.StackTrace);
Console.Error.WriteLine(ex.Message);
}
document.Close();
Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
Response.OutputStream.Flush();
Response.OutputStream.Close();
上述方法导出的是单页PDF,若是超出会自动连到下一页。
若要将PDF分页导出,可将上面蓝字部分修改成下面代码:
string htmlText = wc.DownloadString(path) + "," + wc.DownloadString(path);
string[] htmlTextList= htmlText.Split(',');
foreach (var item in htmlTextList)
{
document.NewPage();
TextReader fileReader = new StringReader(item);
worker.Parse(fileReader);
}

 

posted @ 2016-01-29 14:13  可可味  阅读(426)  评论(0编辑  收藏  举报