C#使用ITextSharp操作pdf


在.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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM