码迷,mamicode.com
首页 > Web开发 > 详细

通过html文件生成PDF文件

时间:2018-08-27 14:20:08      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:cache   head   bsp   www.   完整   二进制流   readonly   ++   cli   

/// <summary>
/// 获取html内容,转成PDF(注册)

/// </summary>
public void DownloadPDFByHTML(string html,string FileName)
{


WebClient wc = new WebClient();
//
wc.Encoding = System.Text.Encoding.UTF8;
//string htmlText = getWebContent();
string htmlText = html;//getWebContent();

string DataName = FileName;//下载文件名

byte[] pdfFile =ConvertHtmlTextToPDF(htmlText);

//如果需要保存到服务器
//string fileId = "/file_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
//System.IO.File.WriteAllBytes(path + fileId, pdfFile);
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(DataName + ".pdf", System.Text.Encoding.UTF8));
Response.BinaryWrite(pdfFile);//文件下载二进制流
Response.Flush();
Response.End();
////删除服务器文件,通知下载成功之后,删除
//FileInfo fi = new FileInfo(path + fileId);
//if (fi.Exists)
//{
// fi.Delete();
//}
}

/// <summary>
/// 获取网站内容,包含了 HTML+CSS+JS
/// </summary>
/// <returns>String返回网页信息</returns>
public string getWebContent()
{
try
{
string INPATH = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplet/sa.html");
WebClient MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials;
//获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = MyWebClient.DownloadData(INPATH);
//从指定网站下载数据
string pageHtml = Encoding.UTF8.GetString(pageData);
//如果获取网站页面采用的是GB2312,则使用这句
bool isBool =isMessyCode(pageHtml);//判断使用哪种编码 读取网页信息
if (!isBool)
{
string pageHtml1 = Encoding.UTF8.GetString(pageData);
pageHtml = pageHtml1;
}
else
{
string pageHtml2 = Encoding.Default.GetString(pageData);
pageHtml = pageHtml2;
}
return pageHtml;
}

catch (WebException webEx)
{
Console.WriteLine(webEx.Message.ToString());
return webEx.Message;
}
}


/// <summary>
/// 判断是否有乱码
/// </summary>
/// <param name="txt"></param>
/// <returns></returns>
public static bool isMessyCode(string txt)
{
var bytes = Encoding.UTF8.GetBytes(txt);
for (var i = 0; i < bytes.Length; i++)
{
if (i < bytes.Length - 3)
if (bytes[i] == 239 && bytes[i + 1] == 191 && bytes[i + 2] == 189)
{
return true;
}
}
return false;
}

 


/// <summary>
/// 将Html文字 输出到PDF档里
/// </summary>
/// <param name="htmlText"></param>
/// <returns></returns>
public static 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(PageSize.A4.Rotate(), 1, 1, 1, 1);//要写PDF的文件,建构子没填的话预设直式A4(括号内不填写值默认是A4纵向,否则是横向)

PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
//指定文件预设开档时的缩放为100%

PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
//开启Document文件
doc.Open();
doc.Add(iTextSharp.text.PageSize.A5.Rotate());
//使用XMLWorkerHelper把Html parse到PDF档里
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory());
//XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);

//将pdfDest设定的资料写到PDF档
PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer);
writer.SetOpenAction(action);
doc.Close();
msInput.Close();
outputStream.Close();
//回传PDF档案
return outputStream.ToArray();

}

//设置字体类 (如果字体设置有问题,只能显示英文)
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 FontTypePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"STKAITI.TTF");


public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached)
{
BaseFont bfChiness = BaseFont.CreateFont(@"C:\\WINDOWS\\FONTS\\STKAITI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//可用Arial或标楷体,自己选一个
BaseFont baseFont = BaseFont.CreateFont(FontTypePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return new Font(bfChiness, size, style, color);
}
}

转载至:https://www.cnblogs.com/zhurunlai/p/7193201.html

 

通过html文件生成PDF文件

标签:cache   head   bsp   www.   完整   二进制流   readonly   ++   cli   

原文地址:https://www.cnblogs.com/lijianli/p/9541411.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!