这个导出PDF还是满费劲的,百度了好久都是零零散散的,要不就是收费的,最终还是拼出来了一个简单的版本。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text;
using Models;namespace FundingForecast
{public class ExportPDF{private static ExportPDF instance;public static ExportPDF GetInstance(){if (instance == null){instance = new ExportPDF();}return instance;}private static Document doc;//string fontdb = AppDomain.CurrentDomain.BaseDirectory + "Template\\msyh.ttc";//private static BaseFont bf = BaseFont.CreateFont(@"C://Windows/Fonts/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//需要有合适的字体static string fontdb = (AppDomain.CurrentDomain.BaseDirectory + "Template\\思源宋体 SC-Bold.otf").Replace("\\", "/");private static BaseFont bf = BaseFont.CreateFont(fontdb + "", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//四种字体private static Font fontBig = new Font(bf, 9, Font.BOLD);private static Font fontSmall = new Font(bf, (float)10.5, Font.BOLD);private static Font fontSmallNoBold = new Font(bf, (float)10.5);private static float IndentationLeft = 50;//距左边距//如果要传参数进来,可自定义public string GeneratePDF(List<WO_Rating_ChangeModel> model){doc = new Document(PageSize.A4);string filePath = string.Empty;try{//MemoryStream ms2 = new MemoryStream();string fileName = string.Format("{0}.pdf", DateTime.Now.ToString("yyyyMMddHHmmss"));filePath = AppDomain.CurrentDomain.BaseDirectory + "Template\\" + fileName;FileStream fs = new FileStream(filePath, FileMode.Create);//创建临时文件,到时生成好后删除PdfWriter writer = PdfWriter.GetInstance(doc, fs);writer.CloseStream = false;//把doc内容写入流中doc.Open();//核心操作//CreateLine();//生成一条下横线#region 添加水印string waterMarkName = "SIEMENS";#endregionPdfPTable table = new PdfPTable(24); //列table.TotalWidth = 600f; //table widthtable.LockedWidth = true; //配合table widthtable.SpacingBefore = 10f; //margin-toptable.SpacingAfter = 30f; //margin-bottomtable.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right (float)//创建cell单元格 作为首行PdfPCell tile  = new PdfPCell(new Phrase("BP No."));//添加到Tabletable.AddCell(tile);//循环遍历出所有的内容foreach (var item in model){PdfPCell cell1 = new PdfPCell(new Phrase(Convert.ToString(item.Customer_Number) + "aa"));cell1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right (text)table.AddCell(cell1);PdfPCell cell2 = new PdfPCell(new Phrase(Convert.ToString(item.Customer_Name) + "rr"));cell2.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right (text)table.AddCell(cell2);}//添加到Documentdoc.Add(table);doc.Close();MemoryStream ms = new MemoryStream();if (fs != null){byte[] bytes = new byte[fs.Length];//定义一个长度为fs长度的字节数组fs.Read(bytes, 0, (int)fs.Length);//把fs的内容读到字节数组中ms.Write(bytes, 0, bytes.Length);//把字节内容读到流中fs.Flush();fs.Close();}MemoryStream waterMS = SetWaterMark(ms, filePath, waterMarkName);//先生成水印,再删除临时文件if (File.Exists(filePath))//判断临时文件是否存在,如果存在则删除{File.Delete(filePath);GC.Collect();//回收垃圾}SendFile(fileName, waterMS);//把PDF文件发送回浏览器}catch (DocumentException ex){throw new Exception(ex.Message);}return filePath;}#region 生成一条横线private static void CreateLine(){PdfPTable table = new PdfPTable(1);//一个单元格的PdfPCell cell = new PdfPCell();cell.BorderWidth = 0f;cell.BorderWidthBottom = 0.2f;table.AddCell(cell);doc.Add(table);}#endregion#region 生成页码private static void AddPageNumberContent(){var content = new Paragraph("共   页  第   页", fontSmall);content.IndentationRight = IndentationLeft + 20;content.Alignment = 2;    //居左doc.Add(content);}#endregion#region 生成水印private static MemoryStream SetWaterMark(MemoryStream ms, string filePath, string waterMarkName, string waterMarkAddr = null){MemoryStream msWater = new MemoryStream();PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{pdfReader = new PdfReader(filePath);pdfStamper = new PdfStamper(pdfReader, msWater);int total = pdfReader.NumberOfPages + 1;//获取PDF的总页数iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);//获取第一页float width = psize.Width;//PDF页面的宽度,用于计算水印倾斜float height = psize.Height;PdfContentByte waterContent;BaseFont basefont = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);PdfGState gs = new PdfGState();for (int i = 1; i < total; i++){waterContent = pdfStamper.GetOverContent(i);//在内容上方加水印//透明度waterContent.SetGState(gs);//开始写入文本waterContent.BeginText();waterContent.SetColorFill(BaseColor.RED);waterContent.SetFontAndSize(basefont, 18);waterContent.SetTextMatrix(0, 0);if (waterMarkAddr == null || waterMarkAddr == ""){waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2, 55);}else{waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2, height / 2 + 100, 55);waterContent.ShowTextAligned(Element.ALIGN_CENTER, waterMarkAddr, width / 2, height / 2 - 100, 55);}waterContent.EndText();}}catch (Exception){return ms;}finally{if (pdfStamper != null)pdfStamper.Close();if (pdfReader != null)pdfReader.Close();}return msWater;}#endregion//-----------------------发送PDF文件回浏览器端----------------------public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null){fileName = (fileName + "").Replace(" ", "");encoding = encoding ?? Encoding.UTF8;if (ms != null && !string.IsNullOrEmpty(fileName)){System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;response.Clear();response.Charset = encoding.BodyName;// "utf-8";if (!HttpContext.Current.Request.UserAgent.Contains("Firefox") && !HttpContext.Current.Request.UserAgent.Contains("Chrome")){fileName = HttpUtility.UrlEncode(fileName, encoding);}response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);//为了解决打开,导出NPOI生成的xlsx文件时,提示发现不可读取内容。if (!(fileName + "").ToLower().EndsWith(".xlsx")){response.AddHeader("Content-Type", "application/octet-stream");response.BinaryWrite(ms.GetBuffer());}else{response.BinaryWrite(ms.ToArray());}ms.Close();ms = null;response.Flush();response.End();}}}
}

整个的流程就是 创建PDF 创建表格 创建单元格将单元格添加到表格 将表格添加到document 结束。查的过程中还有很多的样式一类的,我的这些也是从百度上找到的一拼凑出来的,因为有的东西可以用有的用不了。遇到过几次的错误就是字体没有啦导不出内容这种,百度就能解决。

C#使用iTextSharp将数据导出成PDF相关推荐

  1. 用Itext把数据导出到Pdf文档

    工夫不负有心人!先用POI实现了把数据导出为Excel,现在又实现了用Itext把数据导出为Pdf文档.因为这些技术是以前都没有接触的,而现在又都基本掌握了,所以心里略有一些成就感.现把完整程序代码列 ...

  2. python抓取数据库数据封装成json_用Python将mysql数据导出成json的方法

    1.相关说明 此脚本可以将Mysql的数据导出成Json格式,导出的内容可以进行select查询确定. 数据传入参数有:dbConfigName, selectSql, jsonPath, fileN ...

  3. Pl/sql 如何将oracle的表数据导出成excel文件?

    oracle将表数据导出成excel文件的方法 1)在SQL窗体上,查询需要导出的数据 --查询数据条件--select MID,CODE,NAME from Dxc_Goods_Cate where ...

  4. 查询php 输出表格,php输出excel表格数据-PHP如何将查询出来的数据导出成excel表格(最好做......

    PHP如何将查询出来的数据导出成excel表格(最好做... php 把数据导出excel表格有多种方法,使用 phpExcel 等,以下代码接通过 header 生成 excel 文件的代码示例: ...

  5. Vue将echarts数据导出成excel文件

    Vue将echarts数据导出成excel文件 一.下载vendor插件 下载 vendor 文件放置项目的 src 目录下 链接:https://pan.baidu.com/s/1XYYQ186zo ...

  6. 【前端html页面数据导出为pdf文件】

    [前端html页面数据导出为pdf文件] 文前白话 在网页端导出 Excel 数据表格保存本地 前端html页面数据导出为pdf文件 文前白话 项目需要,将网页端查询的数据结果与数据分析结果导出文件, ...

  7. 关于数据导出成excel表

    关于数据导出成excel表 咱们这里分享简单导出成excel表和筛选导出excel表,希望对各位有帮助,欢迎大家交流和点赞!!!! 我在这里使用的是一个导出工具类,如下: package cn.ms. ...

  8. vue导出excel加一个进度条_vue项目中如何把数据导出成excel文件

    Loading... 关于vue中如何把数据导出成excel文件 ### 1. 安装依赖 ``` yarn add file-saver yarn add xlsx yarn add script-l ...

  9. Axure RP Pro 相关问题 导出成PDF

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! Axur ...

最新文章

  1. velocity-1.7中vm文件的存放位置
  2. 帮朋友招一个IM开发人员
  3. lisp直线连接圆象限电_圆并不难,为什么很多考生就是学不会?
  4. 十佳运动员有奖评选系统_2019年度国际足坛十佳运动员,利物浦三星在列,第十名属私心...
  5. 前端模板Nunjucks简介
  6. c语言字符串定界符,关于c ++:按字符分割字符串
  7. 【2016年第3期】中国电信大数据应用实践
  8. TurboMail独家提供邮件服务器与Outlook间的地址簿同步插件
  9. 电脑保密检查清除痕迹_保密安全|2020年国家安全与保密宣传周来啦!
  10. Android About ContentProvider
  11. c语言ll和 amp amp 优先级,关于C语言自增自减运算符的灵活使用.pdf
  12. c语言switch case ppt,C语言-09switch-case多分支开路语句.ppt
  13. c语言 wchar_t,一个【wchar_t】引发的学案
  14. R语言:Error in file(out, “wt“) : cannot open the connection
  15. 程序发生run time error原因及解决方案
  16. 求最大公约数代码 Java_java怎么求最大公约数?
  17. 计算机关机界面卡住,电脑关机时卡在关机界面的解决方法
  18. 大曝光!武汉最牛的互联网公司全在这了
  19. 二十、哈希表的基础知识
  20. 3ds Max 2014安装SupperMap 插件

热门文章

  1. Database Mirroring
  2. 刀片服务器改台式电脑_详解刀片服务器如何走向融合
  3. 玩转华为数据中心交换机系列 | 配置LACP模式的跨设备聚合(单机)
  4. ESP8266-01 使用 Arduino IDE
  5. rank over pation
  6. 2.8 Multisim应用举例
  7. 计算机毕业设计SSM电影票购票系统【附源码数据库】
  8. Java中资源文件获取源码浅析
  9. Translational Psychiatry:重度抑郁障碍的神经进行性特征:内在连接组分析
  10. 万字拆解!追溯ChatGPT各项能力的起源