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;

1.使用HTMLWorker将html 导出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);
}

b.方法二:

            MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
            byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
            MemoryStream msInput = new MemoryStream(data);
            Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4
            PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
            //指定文件预设开档时的缩放为100%
            PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
            //开启Document文件
            HTMLWorker worker = new HTMLWorker(doc);
            string pathFont = Server.MapPath("~/Fonts/");
            string fontFilePath = Path.Combine(pathFont, "simhei.ttf");
            doc.Open();
            //使用XMLWorkerHelper把Html parse到PDF档里      
            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);
            string[] htmlTextList = htmlText.Split(',');
            foreach (var item in htmlTextList)
            {
                doc.NewPage();
                TextReader fileReader = new StringReader(item);
                worker.Parse(fileReader);
            }
            //将pdfDest设定的资料写到PDF档
            PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
            writer.SetOpenAction(action);
            doc.Close();
            msInput.Close();
            outputStream.Close();
            return File(outputStream.ToArray(), "application/pdf", "范例PDF档.pdf");

2.在本地某个路径下  将html字串  生成PDF文件

string path = Server.MapPath("~/Views/ExportExcel/ExcelHtml.html");
WebClient wc = new WebClient();
string htmlText = wc.DownloadString(path)+ "," + wc.DownloadString(path);

MemoryStream m = new MemoryStream();
Document document = new Document();

string Filepath = Server.MapPath("~/Content/");
FileStream fs = new FileStream(Filepath + HttpUtility.UrlEncode(System.DateTime.Now + ".pdf", Encoding.UTF8), FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
HTMLWorker worker = new HTMLWorker(document);
document.Open();
worker.StartDocument();

//解决 导出的PDF 中文不显示  将C:/Windows/Fonts/simhei.ttf文件考到本地Fonts文件夹中
string pathFont = Server.MapPath("~/Fonts/");
string fontFilePath = Path.Combine(pathFont, "simhei.ttf");
try
{
PdfWriter.GetInstance(document, m);
document.Open();

//解决 导出的PDF 中文不显示  将C:/Windows/Fonts/simhei.ttf文件考到本地Fonts文件夹中
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);

//生成单页PDF
//TextReader fileReader = new StringReader(htmlText);
//worker.Parse(fileReader);

//生成多页PDF
string[] htmlTextList = htmlText.Split(',');
foreach (var item in htmlTextList)
{
document.NewPage();
TextReader fileReader = new StringReader(item);
worker.Parse(fileReader);
}
}
catch (DocumentException ex)
{
Console.Error.WriteLine(ex.StackTrace);
Console.Error.WriteLine(ex.Message);
}
worker.EndDocument();
worker.Close();
document.Close();

 使用iTextSharp、itextsharp.xmlworker导出PDF

 

using System;
using System.Collections;
using System.Collections.Generic;
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.pdf;
using iTextSharp.tool.xml;

//定义一个类,用来规定PDF文件中中文的显示  Model

public class UnicodeFontFactory : FontFactoryImp

{
private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"arialuni.ttf");//arial unicode MS是完整的unicode字型。
private static readonly string 标楷体Path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"KAIU.TTF");//标楷体


public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
bool cached)
{
//可用Arial或标楷体,自己选一个
BaseFont baseFont = BaseFont.CreateFont(标楷体Path, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return new Font(baseFont, size, style, color);
}

}

//Controller

public ActionResult DownloadPdf()

{
//从网址下载Html字串
string path = Server.MapPath("~/Views/ExportExcel/ExcelHtml.html");
WebClient wc = new WebClient();
string htmlText = wc.DownloadString(path);
byte[] pdfFile = this.ConvertHtmlTextToPDF(htmlText);

return File(pdfFile, "application/pdf", "范例PDF档.pdf");
}
/// <summary>
/// 将Html文字 输出到PDF档里
/// </summary>
/// <param name="htmlText"></param>
/// <returns></returns>
public byte[] ConvertHtmlTextToPDF(string htmlText)
{
if (string.IsNullOrEmpty(htmlText))
{
return null;
}
//避免当htmlText无任何html tag标签的纯文字时,转PDF时会挂掉,所以一律加上<p>标签
htmlText = "<p>" + htmlText + "</p>";

MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
MemoryStream msInput = new MemoryStream(data);
Document doc = new Document();//要写PDF的文件,建构子没填的话预设直式A4
PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
//指定文件预设开档时的缩放为100%
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
//开启Document文件
doc.Open();
//使用XMLWorkerHelper把Html parse到PDF档里
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
//将pdfDest设定的资料写到PDF档
PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
writer.SetOpenAction(action);
doc.Close();
msInput.Close();
outputStream.Close();
//回传PDF档案
return outputStream.ToArray();
}

 

posted on 2015-03-26 17:13  水清天藍  阅读(1028)  评论(0)    收藏  举报