基于Layui +net. mvcPDF导出
html
<button class="layui-btn layui-btn-lg layui-btn-radius layui-btn-normal" onclick="PDF导出()">PDF导出</button>
js
function PDF导出() { $.post("/PDFHelper/PDF导出", { }, function (pdfName) { var fname = "/upload/" + pdfName; window.open(fname); }); }
PDFHelperController
using iTextSharp.text; using iTextSharp.text.pdf; using SFMVC.Model.DAL; using SFMVC.Model.Model; using System; using System.IO; using System.Web.Mvc; namespace SFMVC3._0.Controllers { public class PDFHelperController : Controller { // GET: PDF public ActionResult Index() { return View(); } #region public string PDF导出(string userId) { userId = "admin"; string guid = Guid.NewGuid().ToString();//PDF随机名称 SUSERS dal = new SUSERS(); SUser user = dal.getUserByUid(userId);//通过参数查找数据 //开始PDF生产; string fileName = guid + ".pdf"; string basePath = AppDomain.CurrentDomain.BaseDirectory; try { BaseFont bfSon = BaseFont.CreateFont(basePath + "/fonts/simsunb.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);//字体文件 BaseFont bfHei = BaseFont.CreateFont(basePath + "/fonts/STXIHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(bfHei, 14, 1); Font fontInfo = new Font(bfHei, 10, 0); Font fontTable = new Font(bfHei, 10, 1); Font fontFoot = new Font(bfHei, 10); Font font注 = new Font(bfHei, 9); Font fontTitle = new Font(bfHei, 28, 1);//定义文字大小和格式 Document document = new Document(new Rectangle(595F, 842F));//创建一个Document对象并设置纸张 System.IO.File.Delete(basePath + "/upload/tem_" + fileName); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(basePath + "/upload/tem_" + fileName, FileMode.Create));//创建PDF实例 document.Open();//打开文档; PdfPTable tablePage = new PdfPTable(new float[] { 100 });//设置列宽为100的一列 tablePage.WidthPercentage = 100;//设置表的宽度 PdfPCell 编号 = new PdfPCell(new Paragraph("【编号: 】", fontTable)); 编号.HorizontalAlignment = Element.ALIGN_RIGHT; 编号.VerticalAlignment = Element.ALIGN_RIGHT; 编号.PaddingRight = 40;//边距 编号.PaddingBottom = 20; 编号.PaddingTop = 80; 编号.BorderWidth = 0;//边线 tablePage.AddCell(编号);//将编号放入到tablePage PdfPCell cellTitle01 = new PdfPCell(new Paragraph("PDF导出", fontTitle)); cellTitle01.HorizontalAlignment = Element.ALIGN_CENTER; cellTitle01.VerticalAlignment = Element.ALIGN_MIDDLE; cellTitle01.Padding = 5; cellTitle01.PaddingBottom = 250; cellTitle01.BorderWidth = 0; tablePage.AddCell(cellTitle01);//将cellTitle01放入到tablePage document.Add(tablePage);//将tablePage添加到document document.NewPage();//新的一页 PdfPTable table00 = new PdfPTable(new float[] { 100 }); table00.WidthPercentage = 100; PdfPCell cellTitle = new PdfPCell(new Paragraph("第一页", font)); cellTitle.HorizontalAlignment = Element.ALIGN_CENTER; cellTitle.VerticalAlignment = Element.ALIGN_MIDDLE; cellTitle.Padding = 5; cellTitle.BorderWidth = 0; cellTitle.PaddingBottom = 20; table00.AddCell(cellTitle); /*画表头*/ PdfPTable table1 = new PdfPTable(new float[] { 15, 20, 15, 30, 20 }); table1.WidthPercentage = 100; AddPdfCell(table1, fontTable, "姓名", Element.ALIGN_CENTER, 5, 1, 40, 1, 1); AddPdfCell(table1, fontInfo, user.Name, 0, 5, 1, 50, 1, 1); AddPdfCell(table1, fontTable, "时间", Element.ALIGN_CENTER, 5, 1, 40, 1, 1); AddPdfCell(table1, fontInfo, user.Created.ToString("yyyy-MM-dd") == "1900-01-01" ? "" : user.Created.ToString("yyyy年MM月dd日"), 0, 5, 1, 40, 1, 1); //照片格 try { Image img = Image.GetInstance(basePath + "/upload/" + user.Photo); img.ScaleAbsolute(100, 150); PdfPCell cellimg = new PdfPCell(img); cellimg.Rowspan = 3; table1.AddCell(cellimg); } catch (Exception e) { PdfPCell cellimg = new PdfPCell(new Paragraph("无照片", fontInfo)); cellimg.HorizontalAlignment = Element.ALIGN_CENTER; cellimg.VerticalAlignment = Element.ALIGN_MIDDLE; cellimg.Padding = 5; cellimg.BorderWidth = 1; cellimg.Rowspan = 3; table1.AddCell(cellimg); }; document.Add(table00); document.Add(table1); document.Close(); document.Dispose(); string text = DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss") + user.Name; reportHelper.reportPdf(fileName); reportHelper.SetWatermark(fileName, text); } catch (Exception ex) { }; return fileName; #endregion } public static void AddPdfCell(PdfPTable pdfTable, iTextSharp.text.Font fontb, string text, int Alignment, float PadLeft, int BorderWidth, int height, int Rowspan, int Colspan) { PdfPCell pdfCell = new PdfPCell(new Paragraph(text, fontb)); pdfCell.HorizontalAlignment = Alignment;//Element.ALIGN_CENTER pdfCell.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell.Padding = 5; pdfCell.PaddingLeft = PadLeft; pdfCell.BorderWidth = BorderWidth; pdfCell.MinimumHeight = height; pdfCell.Rowspan = Rowspan; pdfCell.Colspan = Colspan; pdfTable.AddCell(pdfCell); } } }
reportHelper
using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.IO; using System.Web; namespace SFMVC3._0.Controllers { public class reportHelper { #region 输出PDF public static string reportPdf(string fileName) { //string fileName = Guid.NewGuid().ToString() + ".pdf"; string basePath = AppDomain.CurrentDomain.BaseDirectory; try { BaseFont bfSon = BaseFont.CreateFont(basePath + "/fonts/simsunb.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); BaseFont bfHei = BaseFont.CreateFont(basePath + "/fonts/STXIHEI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(bfHei, 18); Font fontInfo = new Font(bfHei, 12, 0); Font fontTable = new Font(bfHei, 12, 1); Font fontFoot = new Font(bfHei, 10); int rotation = 0; string pdfTemplate = HttpContext.Current.Server.MapPath("/upload/tem_" + fileName);//文档位置; FileStream stream = new FileStream(pdfTemplate, FileMode.Open, FileAccess.Read); PdfReader reader = new PdfReader(stream); int pageCount = reader.NumberOfPages;//获取全部页面; Document newDocument = new Document(); File.Delete(basePath + "/upload/" + fileName); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, new FileStream(basePath + "/upload/" + fileName, FileMode.CreateNew));//创建PDF实例 newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; PdfContentByte cbs = pdfWriter.DirectContent; for (int pnum = 1; pnum <= pageCount; pnum++) { newDocument.SetPageSize(new Rectangle(595F, 842F)); newDocument.NewPage(); PdfImportedPage importedPage = pdfWriter.GetImportedPage(reader, pnum); rotation = reader.GetPageRotation(pnum); pdfContentByte.AddTemplate(importedPage, 0, 0); string pageNum = "第" + (pnum) + "页,共计" + pageCount + "页"; Phrase footer = new Phrase(pageNum, fontFoot); ColumnText.ShowTextAligned(cbs, Element.ALIGN_CENTER, footer, newDocument.PageSize.Width / 2, newDocument.Bottom - 20, 0); } //stream.Flush(); newDocument.Close(); reader.Close(); stream.Close(); } catch (Exception ex) { //logHelper.savePdfLog(Session["UID"].ToString(), ex.ToString()); return ""; } return fileName; } #endregion 结束输出PDF /// <summary> /// 添加普通偏转角度文字水印 /// </summary> /// #region 输出PDF public static void SetWatermark(string fileName, string text) { PdfReader pdfReader = null; PdfStamper pdfStamper = null; string basePath = AppDomain.CurrentDomain.BaseDirectory; string pdfTemplate = HttpContext.Current.Server.MapPath("/upload/" + fileName);//文档位置; string tempPath = Path.GetDirectoryName(pdfTemplate) + Path.GetFileNameWithoutExtension(pdfTemplate) + "_temp.pdf"; try { pdfReader = new PdfReader(pdfTemplate); pdfStamper = new PdfStamper(pdfReader, new FileStream(tempPath, FileMode.Create)); int total = pdfReader.NumberOfPages + 1; iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1); float width = psize.Width; float height = psize.Height; PdfContentByte content; BaseFont font = BaseFont.CreateFont(basePath + "/fonts/STXIHEI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); for (int i = 1; i < total; i++) { PdfGState gs = new PdfGState(); content = pdfStamper.GetOverContent(i);//在内容上方加水印 //content = pdfStamper.GetUnderContent(i);//在内容下方加水印 //透明度 gs.FillOpacity = 0.3f; content.SetGState(gs); //content.SetGrayFill(0.3f); //开始写入文本 content.BeginText(); content.SetColorFill(BaseColor.GRAY); content.SetFontAndSize(font, 20); content.SetTextMatrix(0, 0); content.ShowTextAligned(Element.ALIGN_CENTER, text, width - 150, height - 150, -45); content.EndText(); } } catch (Exception ex) { throw ex; } finally { if (pdfStamper != null) pdfStamper.Close(); if (pdfReader != null) pdfReader.Close(); System.IO.File.Copy(tempPath, pdfTemplate, true); System.IO.File.Delete(tempPath); } } #endregion } }