主要步骤:
1、传递需要打印的html内容
2、后台将html内容转换成PDF内容
3、转换后生成文件流下载
使用解析组件:iTextSharp
程序包管理控制器执行安装命令,也可以直接Nuget包管理器安装。
Install-Package iTextSharp
Install-Package itextsharp.xmlworker
页面:
通过form表单提交吧当前页面的html提交到后台,进入页面,获取指定区域内容,当然你也可以使用其他方式,这里我做个示例:
后台接收:
public FileResult BaishiMianDan(string pdfData = "")
{
pdfData = pdfData.Replace("<", "<").Replace(">", ">").Replace("\r\n", "");
#region 针对IE浏览器js获取的html内容会丢失"的问题,添加转义字符\"
//if (pdfData.IndexOf("color=red") > 0)
//{
// pdfData = pdfData.Replace("color=red", "color=\"red\"");
//}
//if (pdfData.IndexOf("color=#000") > 0)
//{
// pdfData = pdfData.Replace("color=#000", "color=\"#000\"");
//}
#endregion
byte[] pdf = this.ConvertHtmlTextToPDF(pdfData);
return File(pdf, "application/pdf", "test.pdf");
}
///
/// 将Html文字 输出到PDF档里
///
///
///
public byte[] ConvertHtmlTextToPDF(string htmlText)
{
if (string.IsNullOrEmpty(htmlText))
{
return null;
}
MemoryStream outputStream = new MemoryStream();//要把PDF写到哪个串流
byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串转成byte[]
MemoryStream msInput = new MemoryStream(data);
Document doc = new Document();
doc.SetMargins(0, 0, 0, 0); //设置内容边距
PdfWriter writer = PdfWriter.GetInstance(doc, outputStream);
//指定文件预设开档时的缩放为100%
PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f);
//开启Document文件
doc.Open();
#region pdf文件添加LOGO
string logoPath = Server.MapPath("/Assets/images/tuanzi.jpg");
Image logo = Image.GetInstance(logoPath);
float scalePercent = 10f; //图片缩放比例
float percentX = 60f;
float percentY = 250f;
logo.ScalePercent(scalePercent);
logo.SetAbsolutePosition(percentX, doc.PageSize.Height - percentY);
doc.Add(logo);
#endregion
//使用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();
}
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 kaiuPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"KAIU.TTF");//标楷体
private static readonly string simsunPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"simsun.ttc,1");//新宋体
private static readonly string msyhPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts),
"msyh.ttf");//微软雅黑
public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color,
bool cached)
{
//采用微软雅黑
BaseFont baseFont = BaseFont.CreateFont(msyhPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
return new Font(baseFont, size, style, color);
}
}
导出效果: