原文链接https://www.cnblogs.com/loyung/p/6879917.html

目录

1、CanvasRectangle.cs对Rectangle对象的基类支持,可以灵活定义一个Rectangle

2、PdfBase.cs主要继承PdfPageEventHelper,并实现IPdfPageEvent接口的具体实现,其实也是在pdf的加载,分页等事件中可以重写一些具体操作

3、PdfImage.cs对图像文件的操作

4、PdfPageMerge.cs对pdf文件及文件、各种文件格式文件内容进行合并

5、PdfTable.cs对表格插入做支持,可以在表格插入时动态生成新页并可以为每页插入页眉页脚

6、PdfText.cs对pdf模板上的表单进行赋值,并生成新的pdf

7、PdfWatermark.cs可以为pdf文档添加文字和图片水印

8、PdfPage.aspx.cs页面调用


1、CanvasRectangle.cs对Rectangle对象的基类支持,可以灵活定义一个Rectangle

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{/// <summary>/// 画布对象/// </summary>public class CanvasRectangle{#region CanvasRectangle属性public float StartX { get; set; }public float StartY { get; set; }public float RectWidth { get; set; }public float RectHeight { get; set; }#endregion#region 初始化Rectangle/// <summary>/// 提供rectangle信息/// </summary>/// <param name="startX">起点X坐标</param>/// <param name="startY">起点Y坐标</param>/// <param name="rectWidth">指定rectangle宽</param>/// <param name="rectHeight">指定rectangle高</param>public CanvasRectangle(float startX, float startY, float rectWidth, float rectHeight){this.StartX = startX;this.StartY = startY;this.RectWidth = rectWidth;this.RectHeight = rectHeight;}#endregion#region 获取图形缩放百分比/// <summary>/// 获取指定宽高压缩后的百分比/// </summary>/// <param name="width">目标宽</param>/// <param name="height">目标高</param>/// <param name="containerRect">原始对象</param>/// <returns>目标与原始对象百分比</returns>public static float GetPercentage(float width, float height, CanvasRectangle containerRect){float percentage = 0;if (height > width){percentage = containerRect.RectHeight / height;if (width * percentage > containerRect.RectWidth){percentage = containerRect.RectWidth / width;}}else{percentage = containerRect.RectWidth / width;if (height * percentage > containerRect.RectHeight){percentage = containerRect.RectHeight / height;}}return percentage;}#endregion}}CanvasRectangle.cs

2、PdfBase.cs主要继承PdfPageEventHelper,并实现IPdfPageEvent接口的具体实现,其实也是在pdf的加载,分页等事件中可以重写一些具体操作

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{public class PdfBase : PdfPageEventHelper  {#region 属性  private String _fontFilePathForHeaderFooter = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMHEI.TTF");  /// <summary>  /// 页眉/页脚所用的字体  /// </summary>  public String FontFilePathForHeaderFooter  {  get  {  return _fontFilePathForHeaderFooter;  }  set  {  _fontFilePathForHeaderFooter = value;  }  }  private String _fontFilePathForBody = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SIMSUN.TTC,1");  /// <summary>  /// 正文内容所用的字体  /// </summary>  public String FontFilePathForBody  {  get { return _fontFilePathForBody; }  set { _fontFilePathForBody = value; }  }  private PdfPTable _header;  /// <summary>  /// 页眉  /// </summary>  public PdfPTable Header  {  get { return _header; }  private set { _header = value; }  }  private PdfPTable _footer;  /// <summary>  /// 页脚  /// </summary>  public PdfPTable Footer  {  get { return _footer; }  private set { _footer = value; }  }  private BaseFont _baseFontForHeaderFooter;  /// <summary>  /// 页眉页脚所用的字体  /// </summary>  public BaseFont BaseFontForHeaderFooter  {  get { return _baseFontForHeaderFooter; }  set { _baseFontForHeaderFooter = value; }  }  private BaseFont _baseFontForBody;  /// <summary>  /// 正文所用的字体  /// </summary>  public BaseFont BaseFontForBody  {  get { return _baseFontForBody; }  set { _baseFontForBody = value; }  }  private Document _document;  /// <summary>  /// PDF的Document  /// </summary>  public Document Document  {  get { return _document; }  private set { _document = value; }  }  #endregion  public override void OnOpenDocument(PdfWriter writer, Document document)  {  try  {  BaseFontForHeaderFooter = BaseFont.CreateFont(FontFilePathForHeaderFooter, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  BaseFontForBody = BaseFont.CreateFont(FontFilePathForBody, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);document.Add(new Phrase("\n\n"));Document = document;  }  catch (DocumentException de)  {  }  catch (System.IO.IOException ioe)  {  }  }  #region GenerateHeader  /// <summary>  /// 生成页眉  /// </summary>  /// <param name="writer"></param>  /// <returns></returns>  public virtual PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer)  {  return null;  }  #endregion  #region GenerateFooter  /// <summary>  /// 生成页脚  /// </summary>  /// <param name="writer"></param>  /// <returns></returns>  public virtual PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer)  {  return null;  }  #endregion  public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)  {base.OnEndPage(writer, document);//输出页眉  Header = GenerateHeader(writer);  Header.TotalWidth = document.PageSize.Width - 20f;  ///调用PdfTable的WriteSelectedRows方法。该方法以第一个参数作为开始行写入。  ///第二个参数-1表示没有结束行,并且包含所写的所有行。  ///第三个参数和第四个参数是开始写入的坐标x和y.  Header.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 20, writer.DirectContent);  //输出页脚  Footer = GenerateFooter(writer);  Footer.TotalWidth = document.PageSize.Width - 20f;  Footer.WriteSelectedRows(0, -1, 10, document.PageSize.GetBottom(50), writer.DirectContent);  }  }
}PdfBase.cs

3、PdfImage.cs对图像文件的操作

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{/// <summary>/// pdf图片操作类/// </summary>public class PdfImage{#region PdfImage属性/// <summary>/// 图片URL地址/// </summary>public string ImageUrl { get; set; }/// <summary>/// 图片域宽/// </summary>public float FitWidth { get; set; }/// <summary>/// 图片域高/// </summary>public float FitHeight { get; set; }/// <summary>/// 绝对X坐标/// </summary>public float AbsoluteX { get; set; }/// <summary>/// 绝对Y坐标/// </summary>public float AbsoluteY { get; set; }/// <summary>/// Img内容/// </summary>public byte[] ImgBytes { get; set; }/// <summary>/// 是否缩放/// </summary>public bool ScaleParent { get; set; }/// <summary>/// 画布对象/// </summary>public CanvasRectangle ContainerRect { get; set; }#endregion#region  PdfImage构造/// <summary>/// 网络图片写入/// </summary>/// <param name="imageUrl">图片URL地址</param>/// <param name="fitWidth"></param>/// <param name="fitHeight"></param>/// <param name="absolutX"></param>/// <param name="absoluteY"></param>/// <param name="scaleParent"></param>public PdfImage(string imageUrl, float fitWidth, float fitHeight, float absolutX, float absoluteY, bool scaleParent){this.ImageUrl = imageUrl;this.FitWidth = fitWidth;this.FitHeight = fitHeight;this.AbsoluteX = absolutX;this.AbsoluteY = absoluteY;this.ScaleParent = scaleParent;}/// <summary>/// 本地文件写入/// </summary>///  <param name="imageUrl">图片URL地址</param>/// <param name="fitWidth"></param>/// <param name="fitHeight"></param>/// <param name="absolutX"></param>/// <param name="absoluteY"></param>/// <param name="scaleParent"></param>/// <param name="imgBytes"></param>public PdfImage(string imageUrl, float fitWidth, float fitHeight, float absolutX, float absoluteY, bool scaleParent, byte[] imgBytes){this.ImageUrl = imageUrl;this.FitWidth = fitWidth;this.FitHeight = fitHeight;this.AbsoluteX = absolutX;this.AbsoluteY = absoluteY;this.ScaleParent = scaleParent;this.ImgBytes = imgBytes;}#endregion#region 指定pdf模板文件添加图片/// <summary>/// 指定pdf模板文件添加图片/// </summary>/// <param name="tempFilePath"></param>/// <param name="createdPdfPath"></param>/// <param name="pdfImages"></param>public void PutImages(string tempFilePath, string createdPdfPath, List<PdfImage> pdfImages){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{pdfReader = new PdfReader(tempFilePath);pdfStamper = new PdfStamper(pdfReader, new FileStream(createdPdfPath, FileMode.OpenOrCreate));var pdfContentByte = pdfStamper.GetOverContent(1);//获取PDF指定页面内容foreach (var pdfImage in pdfImages){Uri uri = null;Image img = null;var imageUrl = pdfImage.ImageUrl;//如果使用网络路径则先将图片转化位绝对路径if (imageUrl.StartsWith("http")){//var absolutePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(".."), imageUrl);  var absolutePath = System.Web.HttpContext.Current.Server.MapPath("..") + imageUrl;uri = new Uri(absolutePath);img = Image.GetInstance(uri);}else{//如果直接使用图片文件则直接创建iTextSharp的Image对象if (pdfImage.ImgBytes != null){img = Image.GetInstance(new MemoryStream(pdfImage.ImgBytes));}}if (img != null){if (pdfImage.ScaleParent){var containerRect = pdfImage.ContainerRect;float percentage = 0.0f;percentage =CanvasRectangle.GetPercentage(img.Width, img.Height, containerRect);img.ScalePercent(percentage * 100);pdfImage.AbsoluteX = (containerRect.RectWidth - img.Width * percentage) / 2 + containerRect.StartX;pdfImage.AbsoluteY = (containerRect.RectHeight - img.Height * percentage) / 2 + containerRect.StartY;}else{img.ScaleToFit(pdfImage.FitWidth, pdfImage.FitHeight);}img.SetAbsolutePosition(pdfImage.AbsoluteX, pdfImage.AbsoluteY);pdfContentByte.AddImage(img);}}pdfStamper.FormFlattening = true;}catch (Exception ex){throw ex;}finally{if (pdfStamper != null){pdfStamper.Close();}if (pdfReader != null){pdfReader.Close();}pdfStamper = null;pdfReader = null;}}#endregion}
}PdfImage.cs

4、PdfPageMerge.cs对pdf文件及文件、各种文件格式文件内容进行合并

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{public class PdfPageMerge{private PdfWriter pw;private PdfReader reader;       private Document document;private PdfContentByte cb;private PdfImportedPage newPage;private FileStream fs;/// <summary>/// 通过输出文件来构建合并管理,合并到新增文件中,合并完成后调用FinishedMerge方法/// </summary>/// <param name="sOutFiles">输出文件</param>public PdfPageMerge(string sOutFiles){document = new Document(PageSize.A4);fs=new FileStream(sOutFiles, FileMode.Create);pw = PdfWriter.GetInstance(document, fs);document.Open();cb = pw.DirectContent;}       /// <summary>/// 通过文件流来合并文件,合并到当前的可写流中,合并完成后调用FinishedMerge方法/// </summary>/// <param name="sm"></param>public PdfPageMerge(Stream sm){document = new Document();pw = PdfWriter.GetInstance(document, sm);            document.Open();cb = pw.DirectContent;}/// <summary>/// 合并文件/// </summary>/// <param name="sFiles">需要合并的文件路径名称</param>/// <returns></returns>public bool MergeFile(string sFiles){reader = new PdfReader(sFiles);           {int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){newPage = pw.GetImportedPage(reader, j);//Rectangle r = reader.GetPageSize(j);Rectangle r = reader.GetPageSizeWithRotation(j);document.SetPageSize(r);cb.AddTemplate(newPage, 0, 0);document.NewPage();}}reader.Close();            return true;}/// <summary>/// 通过字节数据合并文件/// </summary>/// <param name="pdfIn">PDF字节数据</param>/// <returns></returns>public bool MergeFile(byte[] pdfIn){reader = new PdfReader(pdfIn);{int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){newPage = pw.GetImportedPage(reader, j);Rectangle r = reader.GetPageSize(j);document.SetPageSize(r);document.NewPage();cb.AddTemplate(newPage, 0, 0);}}reader.Close();return true;}/// <summary>/// 通过PDF文件流合并文件/// </summary>/// <param name="pdfStream">PDF文件流</param>/// <returns></returns>public bool MergeFile(Stream pdfStream){reader = new PdfReader(pdfStream);{int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){newPage = pw.GetImportedPage(reader, j);Rectangle r = reader.GetPageSize(j);document.SetPageSize(r);document.NewPage();cb.AddTemplate(newPage, 0, 0);}}reader.Close();return true;}/// <summary>/// 通过网络地址来合并文件/// </summary>/// <param name="pdfUrl">需要合并的PDF的网络路径</param>/// <returns></returns>public bool MergeFile(Uri pdfUrl){reader = new PdfReader(pdfUrl);{int iPageNum = reader.NumberOfPages;for (int j = 1; j <= iPageNum; j++){newPage = pw.GetImportedPage(reader, j);Rectangle r = reader.GetPageSize(j);document.SetPageSize(r);document.NewPage();cb.AddTemplate(newPage, 0, 0);}}reader.Close();return true;}/// <summary>/// 完成合并/// </summary>public void FinishedMerge(){try{if (reader != null){reader.Close();}if (pw != null){pw.Flush();pw.Close();}if (fs != null){fs.Flush();fs.Close();}if (document.IsOpen()){document.Close();}}catch{}}public static string AddCommentsToFile(string fileName,string outfilepath, string userComments, PdfPTable newTable){string outputFileName = outfilepath;//Step 1: Create a Docuement-ObjectDocument document = new Document();try{//Step 2: we create a writer that listens to the documentPdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));//Step 3: Open the documentdocument.Open();PdfContentByte cb = writer.DirectContent;//The current file pathstring filename = fileName;// we create a reader for the documentPdfReader reader = new PdfReader(filename);for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++){document.SetPageSize(reader.GetPageSizeWithRotation(1));document.NewPage();//Insert to Destination on the first pageif (pageNumber == 1){Chunk fileRef = new Chunk(" ");fileRef.SetLocalDestination(filename);document.Add(fileRef);}PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);int rotation = reader.GetPageRotation(pageNumber);if (rotation == 90 || rotation == 270){cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);}else{cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);}}// Add a new page to the pdf filedocument.NewPage();Paragraph paragraph = new Paragraph();Font titleFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 15, iTextSharp.text.Font.BOLD, BaseColor.BLACK);Chunk titleChunk = new Chunk("Comments", titleFont);paragraph.Add(titleChunk);document.Add(paragraph);paragraph = new Paragraph();Font textFont = new Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);Chunk textChunk = new Chunk(userComments, textFont);paragraph.Add(textChunk);document.Add(paragraph);document.Add(newTable);}catch (Exception e){throw e;}finally{document.Close();}return outputFileName;}}
}PdfPageMerge.cs

5、PdfTable.cs对表格插入做支持,可以在表格插入时动态生成新页并可以为每页插入页眉页脚

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;namespace PDFReport
{/// <summary>/// Pdf表格操作类/// </summary>public class PdfTable:PdfBase{/// <summary>/// 向PDF中动态插入表格,表格内容按照htmltable标记格式插入/// </summary>/// <param name="pdfTemplate">pdf模板路径</param>/// <param name="tempFilePath">pdf导出路径</param>/// <param name="parameters">table标签</param>public void PutTable(string pdfTemplate, string tempFilePath, string parameter){Document doc = new Document();try{if (File.Exists(tempFilePath)){File.Delete(tempFilePath);}doc = new Document(PageSize.LETTER);FileStream temFs = new FileStream(tempFilePath, FileMode.OpenOrCreate);PdfWriter PWriter = PdfWriter.GetInstance(doc,temFs);PdfTable pagebase = new PdfTable();PWriter.PageEvent = pagebase;//添加页眉页脚BaseFont bf1 = BaseFont.CreateFont("C:\\Windows\\Fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);iTextSharp.text.Font CellFont = new iTextSharp.text.Font(bf1, 12);doc.Open();   PdfContentByte cb = PWriter.DirectContent;PdfReader reader = new PdfReader(pdfTemplate);for (int pageNumber = 1; pageNumber < reader.NumberOfPages+1 ; pageNumber++){doc.SetPageSize(reader.GetPageSizeWithRotation(1));PdfImportedPage page = PWriter.GetImportedPage(reader, pageNumber);int rotation = reader.GetPageRotation(pageNumber);cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);doc.NewPage();                         }XmlDocument xmldoc = new XmlDocument();xmldoc.LoadXml(parameter);XmlNodeList xnlTable = xmldoc.SelectNodes("table");if (xnlTable.Count > 0){foreach (XmlNode xn in xnlTable){//添加表格与正文之间间距doc.Add(new Phrase("\n\n"));// 由html标记和属性解析表格样式var xmltr = xn.SelectNodes("tr");foreach (XmlNode xntr in xmltr){var xmltd = xntr.SelectNodes("td");PdfPTable newTable = new PdfPTable(xmltd.Count);foreach (XmlNode xntd in xmltd){PdfPCell newCell = new PdfPCell(new Paragraph(1, xntd.InnerText, CellFont));newTable.AddCell(newCell);//表格添加内容var tdStyle = xntd.Attributes["style"];//获取单元格样式if (tdStyle != null){string[] styles = tdStyle.Value.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);Dictionary<string, string> dicStyle = new Dictionary<string, string>();foreach (string strpar in styles){ string[] keyvalue=strpar.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries);dicStyle.Add(keyvalue[0], keyvalue[1]);}//设置单元格宽度if (dicStyle.Select(sty => sty.Key.ToLower().Equals("width")).Count() > 0){newCell.Width =float.Parse(dicStyle["width"]);}//设置单元格高度if (dicStyle.Select(sty => sty.Key.ToLower().Equals("height")).Count() > 0){//newCell.Height = float.Parse(dicStyle["height"]);}}}doc.Add(newTable);}}                }doc.Close();temFs.Close();PWriter.Close();}catch (Exception ex){throw ex;}finally{doc.Close();}}#region GenerateHeader/// <summary>  /// 生成页眉  /// </summary>  /// <param name="writer"></param>  /// <returns></returns>  public override PdfPTable GenerateHeader(iTextSharp.text.pdf.PdfWriter writer){BaseFont baseFont = BaseFontForHeaderFooter;iTextSharp.text.Font font_logo = new iTextSharp.text.Font(baseFont, 18, iTextSharp.text.Font.BOLD);iTextSharp.text.Font font_header1 = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);iTextSharp.text.Font font_header2 = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.BOLD);iTextSharp.text.Font font_headerContent = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);float[] widths = new float[] { 355, 50, 90, 15, 20, 15 };PdfPTable header = new PdfPTable(widths);PdfPCell cell = new PdfPCell();cell.BorderWidthBottom = 2;cell.BorderWidthLeft = 2;cell.BorderWidthTop = 2;cell.BorderWidthRight = 2;cell.FixedHeight = 35;cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);//Image img = Image.GetInstance("http://simg.instrument.com.cn/home/20141224/images/200_50logo.gif");//img.ScaleToFit(100f, 20f);//cell.Image = img;cell.Phrase = new Phrase("LOGO", font_logo);cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;cell.VerticalAlignment = iTextSharp.text.Element.ALIGN_CENTER;cell.PaddingTop = -1;header.AddCell(cell);//cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);//cell.Phrase = new Paragraph("PDF报表", font_header1);//header.AddCell(cell);cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);cell.Phrase = new Paragraph("日期:", font_header2);header.AddCell(cell);cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_LEFT);cell.Phrase = new Paragraph(DateTime.Now.ToString("yyyy-MM-dd"), font_headerContent);header.AddCell(cell);cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);cell.Phrase = new Paragraph("第", font_header2);header.AddCell(cell);cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_CENTER);cell.Phrase = new Paragraph(writer.PageNumber.ToString(), font_headerContent);header.AddCell(cell);cell = GenerateOnlyBottomBorderCell(2, iTextSharp.text.Element.ALIGN_RIGHT);cell.Phrase = new Paragraph("页", font_header2);header.AddCell(cell);return header;}#region /// <summary>  /// 生成只有底边的cell  /// </summary>  /// <param name="bottomBorder"></param>  /// <param name="horizontalAlignment">水平对齐方式<see cref="iTextSharp.text.Element"/></param>  /// <returns></returns>  private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder,int horizontalAlignment){PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder, horizontalAlignment, iTextSharp.text.Element.ALIGN_BOTTOM);cell.PaddingBottom = 5;return cell;}/// <summary>  /// 生成只有底边的cell  /// </summary>  /// <param name="bottomBorder"></param>  /// <param name="horizontalAlignment">水平对齐方式<see cref="iTextSharp.text.Element"/></param>  /// <param name="verticalAlignment">垂直对齐方式<see cref="iTextSharp.text.Element"/</param>  /// <returns></returns>  private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder,int horizontalAlignment,int verticalAlignment){PdfPCell cell = GenerateOnlyBottomBorderCell(bottomBorder);cell.HorizontalAlignment = horizontalAlignment;cell.VerticalAlignment = verticalAlignment; ;return cell;}/// <summary>  /// 生成只有底边的cell  /// </summary>  /// <param name="bottomBorder"></param>  /// <returns></returns>  private PdfPCell GenerateOnlyBottomBorderCell(int bottomBorder){PdfPCell cell = new PdfPCell();cell.BorderWidthBottom = 2;cell.BorderWidthLeft = 0;cell.BorderWidthTop = 0;cell.BorderWidthRight = 0;return cell;}#endregion#endregion  #region GenerateFooterpublic override PdfPTable GenerateFooter(iTextSharp.text.pdf.PdfWriter writer){BaseFont baseFont = BaseFontForHeaderFooter;iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, 10, iTextSharp.text.Font.NORMAL);PdfPTable footer = new PdfPTable(new float[]{1,1,2,1});AddFooterCell(footer, "电话:010-51654077-8039", font);AddFooterCell(footer, "传真:010-82051730", font);AddFooterCell(footer, "电子邮件:yangdd@instrument.com.cn", font);AddFooterCell(footer, "联系人:杨丹丹", font);return footer;}private void AddFooterCell(PdfPTable foot, String text, iTextSharp.text.Font font){PdfPCell cell = new PdfPCell();cell.BorderWidthTop = 2;cell.BorderWidthRight = 0;cell.BorderWidthBottom = 0;cell.BorderWidthLeft = 0;cell.Phrase = new Phrase(text, font);cell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_CENTER;foot.AddCell(cell);}#endregion  }
}PdfTable.cs

6、PdfText.cs对pdf模板上的表单进行赋值,并生成新的pdf

using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{/// <summary>/// pdf文本域操作类/// </summary>public class PdfText{#region  pdf模板文本域复制/// <summary>/// 指定pdf模板为其文本域赋值/// </summary>/// <param name="pdfTemplate">pdf模板路径</param>/// <param name="tempFilePath">pdf导出路径</param>/// <param name="parameters">pdf模板域键值</param>public void PutText(string pdfTemplate, string tempFilePath, Dictionary<string, string> parameters){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{if (File.Exists(tempFilePath)){File.Delete(tempFilePath);}pdfReader = new PdfReader(pdfTemplate);pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate));AcroFields pdfFormFields = pdfStamper.AcroFields;pdfStamper.FormFlattening = true;BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);pdfFormFields.AddSubstitutionFont(simheiBase);foreach (KeyValuePair<string, string> parameter in parameters){if (pdfFormFields.Fields[parameter.Key] != null){pdfFormFields.SetField(parameter.Key, parameter.Value);}}}catch (Exception ex){throw ex;}finally{pdfStamper.Close();pdfReader.Close();pdfStamper = null;pdfReader = null;}}#endregion}
}PdfText.cs

7、PdfWatermark.cs可以为pdf文档添加文字和图片水印

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace PDFReport
{/// <summary>/// pdf水银操作/// </summary>public class PdfWatermark{#region 添加普通偏转角度文字水印/// <summary>/// 添加普通偏转角度文字水印/// </summary>/// <param name="inputfilepath">需要添加水印的pdf文件</param>/// <param name="outputfilepath">添加水印后输出的pdf文件</param>/// <param name="waterMarkName">水印内容</param>public  void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{if (File.Exists(outputfilepath)){File.Delete(outputfilepath);}pdfReader = new PdfReader(inputfilepath);pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.OpenOrCreate));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(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);PdfGState gs = new PdfGState();for (int i = 1; i < total; i++){content = pdfStamper.GetOverContent(i);//在内容上方加水印//content = pdfStamper.GetUnderContent(i);//在内容下方加水印//透明度gs.FillOpacity = 0.3f;content.SetGState(gs);//content.SetGrayFill(0.3f);//开始写入文本content.BeginText();content.SetColorFill(BaseColor.LIGHT_GRAY);content.SetFontAndSize(font, 100);content.SetTextMatrix(0, 0);content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50, height / 2 - 50, 55);//content.SetColorFill(BaseColor.BLACK);//content.SetFontAndSize(font, 8);//content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, 0, 0, 0);content.EndText();}}catch (Exception ex){throw ex;}finally{if (pdfStamper != null)pdfStamper.Close();if (pdfReader != null)pdfReader.Close();}}#endregion#region 添加倾斜水印,并加密文档/// <summary>/// 添加倾斜水印,并加密文档/// </summary>/// <param name="inputfilepath">需要添加水印的pdf文件</param>/// <param name="outputfilepath">添加水印后输出的pdf文件</param>/// <param name="waterMarkName">水印内容</param>/// <param name="userPassWord">用户密码</param>/// <param name="ownerPassWord">作者密码</param>/// <param name="permission">许可等级</param>public  void setWatermark(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{pdfReader = new PdfReader(inputfilepath);pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.OpenOrCreate));// 设置密码   //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission); int total = pdfReader.NumberOfPages + 1;PdfContentByte content;BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);PdfGState gs = new PdfGState();gs.FillOpacity = 0.2f;//透明度int j = waterMarkName.Length;char c;int rise = 0;for (int i = 1; i < total; i++){rise = 500;content = pdfStamper.GetOverContent(i);//在内容上方加水印//content = pdfStamper.GetUnderContent(i);//在内容下方加水印content.BeginText();content.SetColorFill(BaseColor.DARK_GRAY);content.SetFontAndSize(font, 50);// 设置水印文字字体倾斜 开始 if (j >= 15){content.SetTextMatrix(200, 120);for (int k = 0; k < j; k++){content.SetTextRise(rise);c = waterMarkName[k];content.ShowText(c + "");rise -= 20;}}else{content.SetTextMatrix(180, 100);for (int k = 0; k < j; k++){content.SetTextRise(rise);c = waterMarkName[k];content.ShowText(c + "");rise -= 18;}}// 字体设置结束 content.EndText();// 画一个圆 //content.Ellipse(250, 450, 350, 550);//content.SetLineWidth(1f);//content.Stroke(); }}catch (Exception ex){throw ex;}finally{if (pdfStamper != null)pdfStamper.Close();if (pdfReader != null)pdfReader.Close();}}#endregion#region 加图片水印/// <summary>/// 加图片水印/// </summary>/// <param name="inputfilepath"></param>/// <param name="outputfilepath"></param>/// <param name="ModelPicName"></param>/// <param name="top"></param>/// <param name="left"></param>/// <returns></returns>public  bool PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left){PdfReader pdfReader = null;PdfStamper pdfStamper = null;try{pdfReader = new PdfReader(inputfilepath);int numberOfPages = pdfReader.NumberOfPages;iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);float width = psize.Width;float height = psize.Height;pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.OpenOrCreate));PdfContentByte waterMarkContent;iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);image.GrayFill = 80;//透明度,灰色填充//image.Rotation = 40;//旋转image.RotationDegrees = 40;//旋转角度//水印的位置 if (left < 0){left = width / 2 - image.Width + left;}//image.SetAbsolutePosition(left, (height - image.Height) - top);image.SetAbsolutePosition(left, (height / 2 - image.Height) - top);//每一页加水印,也可以设置某一页加水印 for (int i = 1; i <= numberOfPages; i++){waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印//waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印waterMarkContent.AddImage(image);}//strMsg = "success";return true;}catch (Exception ex){throw ex;}finally{if (pdfStamper != null)pdfStamper.Close();if (pdfReader != null)pdfReader.Close();}}#endregion}
}PdfWatermark.cs

8、PdfPage.aspx.cs页面调用

using PDFReport;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;namespace CreatePDF
{public partial class PdfPage : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}#region  默认文档protected void defaultpdf_Click(object sender, EventArgs e){iframepdf.Attributes["src"] = "../PDFTemplate/pdfTemplate.pdf";}#endregion#region 文字域protected void CreatePdf_Click(object sender, EventArgs e){string pdfTemplate = Server.MapPath("~/PDFTemplate/pdfTemplate.pdf");string newpdf = Server.MapPath("~/PDFTemplate/newpdf.pdf");//追加文本##########Dictionary<string, string> dicPra = new Dictionary<string, string>();dicPra.Add("HTjiafang", "北京美嘉生物科技有限公司111111");dicPra.Add("Total", "1370000000000000");dicPra.Add("TotalDaXie", "壹万叁仟柒佰元整");dicPra.Add("Date", "2017年12月12日前付款3000元,2018年1月10日前付余款10700元");new PdfText().PutText(pdfTemplate, newpdf, dicPra);iframepdf.Attributes["src"]="../PDFTemplate/newpdf.pdf";//Response.Write("<script> alert('已生成pdf');</script>");}#endregion#region 普通水印protected void WaterMark_Click(object sender, EventArgs e){string pdfTemplate = Server.MapPath("~/PDFTemplate/pdfTemplate.pdf");string newpdf = Server.MapPath("~/PDFTemplate/newpdf1.pdf");//添加水印############new PdfWatermark().setWatermark(pdfTemplate, newpdf, "仪器信息网");iframepdf.Attributes["src"] = "../PDFTemplate/newpdf1.pdf";//Response.Write("<script> alert('已生成pdf');</script>");}#endregion#region 图片水印protected void WaterMarkPic_Click(object sender, EventArgs e){string pdfTemplate = Server.MapPath("~/PDFTemplate/pdfTemplate.pdf");string newpdf = Server.MapPath("~/PDFTemplate/newpdf2.pdf");//添加图片水印############new PdfWatermark().PDFWatermark(pdfTemplate, newpdf, Server.MapPath("~/Images/200_50logo.gif"), 0, 0);iframepdf.Attributes["src"] = "../PDFTemplate/newpdf2.pdf";//Response.Write("<script> alert('已生成pdf');</script>");}#endregion#region 添加印章protected void PdfImg_Click(object sender, EventArgs e){string pdfTemplate = Server.MapPath("~/PDFTemplate/pdfTemplate.pdf");string newpdf = Server.MapPath("~/PDFTemplate/newpdf3.pdf");//追加图片#############FileStream fs = new FileStream(Server.MapPath("~/Images/yinzhang.png"), FileMode.Open);byte[] byData = new byte[fs.Length];fs.Read(byData, 0, byData.Length);fs.Close();PdfImage pdfimg = new PdfImage("", 100f, 100f, 400f, 470f, false, byData);List<PdfImage> listimg = new List<PdfImage>();listimg.Add(pdfimg);pdfimg.PutImages(pdfTemplate, newpdf, listimg);iframepdf.Attributes["src"] = "../PDFTemplate/newpdf3.pdf";//Response.Write("<script> alert('已生成pdf');</script>");}#endregion#region 添加表格protected void PdfTable_Click(object sender, EventArgs e){string pdfTemplate = Server.MapPath("~/PDFTemplate/pdfTemplate.pdf");string newpdf = Server.MapPath("~/PDFTemplate/newpdf4.pdf");//追加表格############StringBuilder tableHtml = new StringBuilder();tableHtml.Append(@"<table><tr><td>项目</td><td>细类</td><td>价格</td><td>数量</td><td>投放时间</td><td>金额</td></tr><tr><td>钻石会员</td><td>基础服务</td><td>69800元/月</td><td>1年</td><td>2016.01.03-2017.01.02</td><td>69800</td></tr><tr><td>核酸纯化系统专场</td><td>金榜题名</td><td>70000元/月</td><td>1年</td><td>2016.01.03-2017.01.02</td><td>7000</td></tr></table>");new PdfTable().PutTable(pdfTemplate, newpdf, tableHtml.ToString());iframepdf.Attributes["src"] = "../PDFTemplate/newpdf4.pdf";//Response.Write("<script> alert('已生成pdf');</script>");}#endregion}
}PdfPage.aspx.cs

C#使用ITextSharp操作pdf相关推荐

  1. C#使用iTextSharp操作PDF文件

    概述 html文件怎么转成PDF文件?有的招聘网上的简历导成DOC文件,不能直接使用,这样造成很大的困扰,那么它还有一个格式,那就是html格式.将文件导出成html格式,然后再转成PDF文件,这样便 ...

  2. itextsharp操作pdf删除某页

    itextsharp没有删除方法,所以只能新建一个空的pdf,把你想留下的内容放在新的pdf里: iTextSharp.text.pdf.PdfReader pdfReader = new iText ...

  3. itextsharp操作pdf——插入图片

    itextsharp 插入图片操作 asp.net 用于审核后签字或者其他需要对pdf进行插入图片的操作. 在pdf添加图片方法: protected void AddImg(string oldP, ...

  4. 【译】在Asp.Net中操作PDF – iTextSharp -利用块,短语,段落添加文本

    本篇文章是讲述使用iTextSharp这个开源组件的系列文章的第三篇,iTextSharp可以通过Asp.Net创建PDFs,就像HTML和ASP.Net为文本提供了多种容器一样,iTextSharp ...

  5. ITextSharp生成PDF

    ITextSharp就不多介绍了,下面就把遇到的坑一一记录下来,希望能够帮助到正在使用它的开发者们.操作pdf的方法都被作者封装好了,只是没有注释和说明,不过大部分的方法属性还是能看懂的,看不懂的可以 ...

  6. 使用 iTextSharp 生成 PDF 表格

    iTextSharp 5 已经取消了 Table 类,我对照着一份 iTextSharp 4 的帮助文档,使用 VS 的智能提示找遍了所有的命名空间,都找不到 Table 类,幸好最终看到一个 Pdf ...

  7. .NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇) .

    该文主要介绍如何借助iTextSharp在C# 2.0中制作PDF文件,本文的架构大致按照iTextSharp的操作文档进行翻译,如果需要查看原文,请点击一下链接:http://itextsharp. ...

  8. .NET的那些事儿(9)——C# 2.0 中用iTextSharp制作PDF(基础篇)

    该文主要介绍如何借助iTextSharp在C# 2.0中制作PDF文件,本文的架构大致按照iTextSharp的操作文档进行翻译,如果需要查看原文,请点击一下链接:http://itextsharp. ...

  9. C# Json数据转DataTable并生成PDF在线下载--iTextSharp生成PDF实例(文件下载,json数据转换,PDF排版一步到位)

    前言 本文将重点介绍iTextSharp的使用方法和易踩的一些坑,顺便介绍了json转DataTable的简单快捷高效的方法及二进制流转换文件在线即时下载的方法.经测试生成40页的pdf仅需要1秒,大 ...

  10. 国产化系统下操作PDF

    本文围绕使用netcore 跨平台在国产系统(麒麟和统信)操作PDF 首先netcore 需要第三方dll  在Nuget里搜索itextsharp 选择图片中 安装即可 版本写了 itextshar ...

最新文章

  1. boost::safe_numerics模块测试 constexpr 转换
  2. boost::make_maximal_planar用法的测试程序
  3. sqlyog软件的使用
  4. php mysql数据备份命令_MySQL数据备份与恢复的相关操作命令
  5. max file descriptors_年轻族的战场!宋MAX强势对比嘉际
  6. 微海鼠标自动点击器 支持录制和循环播放
  7. eclipse 最全快捷键 分享快乐与便捷
  8. 从SqlServer转手Oracle的一些坑
  9. Centos6.7 简单搭建dns服务器
  10. linux TCP协议(1)---连接管理与状态机
  11. title和alt属性有什么作用?
  12. Spring boot项目启动报无法加载主类
  13. thymeleaf渲染搜索页面(template: “class path resource [templates/serach.html]“)-serach2021-09-23
  14. Unity ECS Sample解析(1)
  15. 从事前端开发如何提升自我能力?
  16. 通过无线网络实现两台计算机共享打印机共享,同一WiFi环境中两台电脑共享打印机技巧方法...
  17. 仿京东收货地址三级联动
  18. 手机如何实现边有线上网边充电?
  19. 大数据冲击下图书出版编辑转型策略探析(非原创)
  20. Scala学习(五)练习

热门文章

  1. 值得注意的两个friendster新服务:校友和web共享搜索
  2. 【Python脚本进阶】2.4、conficker蠕虫(中):Python脚本与Metasploit交互
  3. Python 的切片语法为什么不会出现索引越界呢?
  4. 2017大学网考计算机b,(热)2017年4月网考 大学英语b网考 电大英语网考 计算机应用.doc...
  5. 简析:世博会燃印刷业激情
  6. excel报表导出功能
  7. 津巴布韦 apn_津巴布韦的回忆-你负担不起回家
  8. 主板开启网络唤醒_主板远程唤醒设置
  9. 网上订餐php论文,php032网上订餐系统
  10. 皮尔森相关系数(Pearson correlation coefficient)