【C#】iTextSharps.dll操作Excel、PDF

一、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;
using System.Windows.Forms;

namespace WindowsFormsApplication1.Others
{
    class CreatePdf
    {
        public CreatePdf()
        {
            CreatePdfSetInfo();
        }

        /// <summary>
        /// 设置页面大小、作者、标题等相关信息设置
        /// </summary>
        private bool CreatePdfSetInfo()
        {
            string fileName = string.Empty;
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
            dlg.InitialDirectory = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Report";
            dlg.DefaultExt = ".pdf";
            dlg.Filter = "Text documents (.pdf)|*.pdf";
            dlg.RestoreDirectory = true;
            DialogResult result = dlg.ShowDialog();
            if (result == DialogResult.OK)
            {
                try
                {
                    fileName = dlg.FileName;

                    //设置页面大小
                    //iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(216f, 716f);
                    //pageSize.BackgroundColor = new iTextSharp.text.BaseColor(0xFF, 0xFF, 0xDE);

                    //设置边界
                    Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);//iTextSharp实例
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));

                    document.Open();

                    // 添加文档内容
                    string[] content = new string[] { "内容1", "内容2" };
                    AddFirstPage(document, writer, "标题", content);
                    AddNewPage(document);

                    document.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    //MessageBox.Show(ex.ToString());
                    return false;
                }
            }
            return false;
        }

        private Font SetFont(int fontSize)
        {
            BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\SIMSUN.TTC,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font FontSong = new iTextSharp.text.Font(baseFont, fontSize);
            return FontSong;
        }

        /// <summary>
        /// 添加扉页
        /// </summary>
        /// <param name="document"></param>
        private void AddFirstPage(Document document, PdfWriter writer, string title, string[] content)
        {
            Paragraph pg = new Paragraph(title + "\n\n\n\n", SetFont(22));
            pg.Alignment = 1;
            document.Add(pg); //添加一行
            for (int i = 0; i < content.Count(); i++)
            {
                document.Add(new iTextSharp.text.Paragraph(content[i] + ":\n\n", SetFont(16)));
            }
            ////为表头内容添加下划线
            //PdfContentByte cb = writer.DirectContent;
            //int lineCount = 2;
            //for (int i = 0; i < lineCount; i++)
            //{
            //    cb.SetLineWidth((float)(1.0));
            //    cb.MoveTo(75, 765 - i * 48);
            //    cb.LineTo(505, 765 - i * 48);
            //    cb.Stroke();
            //}
        }

        private void AddNewPage(Document document)
        {
            string title = "子标题";
            string content = "表格1:";
            // 添加新页面
            document.NewPage();

            Paragraph pg = new Paragraph(title + "\n\n", SetFont(22));
            pg.Alignment = 1;
            document.Add(pg);
            document.Add(new iTextSharp.text.Paragraph(content + "\n\n", SetFont(18)));

            string[] cellStr = new string[30];
            int[] colSpan = new int[30];
            for (int i = 0; i < 30; i++)
            {
                cellStr[i] = i.ToString();
            }
            colSpan = Enumerable.Repeat(1, 30).ToArray();
            AddTable(document, 5, 30, cellStr, colSpan);

            //AddPicture(document, AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Login2.jpg");
        }

        /// <summary>
        /// 添加表格
        /// </summary>
        /// <param name="document"></param>
        /// <param name="tableLength">表格横向的总长度</param>
        /// <param name="cellNum">单元格总数</param>
        /// <param name="cellStr">单元格内容数组</param>
        /// <param name="colSpan">单元格长度数组</param>
        private void AddTable(Document document, int tableLength, int cellNum, string[] cellStr, int[] colSpan)
        {
            PdfPTable table = new PdfPTable(tableLength); //若tableLength=5,Colspan=1 则一行有五个单元格
            for (int i = 0; i < cellNum; i++)
            {
                //设置单元格格式
                PdfPCell cell = new PdfPCell(new Phrase(cellStr[i], SetFont(8)));
                cell.Colspan = colSpan[i];
                cell.HorizontalAlignment = 1;
                table.AddCell(cell);
            }
            document.Add(table);
        }

        /// <summary>
        /// 添加文档信息(必须在document.open前调用) //打开文档后右键 >> 文档属性 查看
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="subject">主题</param>
        /// <param name="keywords">关键字</param>
        /// <param name="creator">应用程序</param>
        /// <param name="author">作者</param>
        private void AddPdfInfo(Document document, string title, string subject, string keywords, string creator, string author)
        {
            document.AddTitle("PDFInfo");
            document.AddSubject("Demo of PDFInfo");
            document.AddKeywords("Info, PDF, Demo");
            document.AddCreator("SetPdfInfoDemo");
            document.AddAuthor("sa");
        }

        private void AddPicture(Document document, string imagePath)
        {
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagePath);

            float percentage = 1;
            //图片原始宽高
            float resizedWidht = img.Width;
            float resizedHeight = img.Height;

            //判断图片宽度是否大于页面宽度减去页边距
            while (resizedWidht > (document.PageSize.Width - document.LeftMargin - document.RightMargin) * 0.8)
            {
                percentage = percentage * 0.9f;
                resizedHeight = img.Height * percentage;
                resizedWidht = img.Width * percentage;
            }

            while (resizedHeight > (document.PageSize.Height - document.TopMargin - document.BottomMargin) * 0.8)
            {
                percentage = percentage * 0.9f; //缩小的百分比会越来越小  
                resizedHeight = img.Height * percentage;
                resizedWidht = img.Width * percentage;
            }

            //这里用计算出来的百分比来缩小图片  
            img.ScalePercent(percentage * 100);
            //图片定位。设置0,0就是页面的左下角 让图片的中心点与页面的中心点进行重合  
            img.SetAbsolutePosition(document.PageSize.Width / 2 - resizedWidht / 2, document.PageSize.Height / 2 - resizedHeight / 2);
            document.Add(img);
        }
    }


}

 

向pdf插入图片:https://blog.csdn.net/weixin_41529093/article/details/104978740

生成pdf文件流:https://www.cnblogs.com/albertay/p/6606305.html

posted @ 2022-09-23 16:54  不溯流光  阅读(630)  评论(0编辑  收藏  举报