loyung

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

在.NET中没有很好操作pdf的类库,如果你需要对pdf进行编辑,加密,模板打印等等都可以选择使用ITextSharp来实现。

第一步:可以点击这里下载,新版本的插件升级和之前对比主要做了这几项重大改变

1.初始化对汉字的支持

2.对页眉页脚的加载形式

第二步:制作pdf模板

可以下载Adobe Acrobat DC等任意一款pdf编辑工具,视图——工具——准备表单,可以在需要赋值的地方放上一个文本框,可以把名称修改为有意义的名称,后面在赋值时要用到。

第三步:建项目引入各个操作类

介于前段时间项目所需特意把ITextSharp进行了二次封装,使我们对pdf操作起来更加方便。

列一下各文件的作用:

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

 

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

 

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

 

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-Object
            Document document = new Document();
            try
            {
                //Step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create));

                //Step 3: Open the document
                document.Open();

                PdfContentByte cb = writer.DirectContent;

                //The current file path
                string filename = fileName;

                // we create a reader for the document
                PdfReader 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 page
                    if (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 file
                document.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

 

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 GenerateFooter
        public 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

 

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

 

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

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

 

posted on 2017-05-19 18:56  loyung  阅读(29993)  评论(6编辑  收藏  举报