C# 生成PDF文件(itextsharp二次封裝)

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 MakePDF
{
    public enum TextAlign
    {
        ////單元格文字對齊方式
        //const int horizontalAlignment = Element.ALIGN_CENTER;
        //const int verticalAlignment = Element.ALIGN_MIDDLE;
        //const int bottomAlignment = Element.ALIGN_BOTTOM;
        //const int leftHAlignment = Element.ALIGN_LEFT;
        //const int rightHAlignment = Element.ALIGN_RIGHT;

        /// <summary>
        /// 水平居中
        /// </summary>
        HA = Element.ALIGN_CENTER,
        /// <summary>
        /// 垂直居中
        /// </summary>
        VA = Element.ALIGN_MIDDLE,
        /// <summary>
        /// 下對齊
        /// </summary>
        BA = Element.ALIGN_BOTTOM,
        /// <summary>
        /// 左對齊
        /// </summary>
        LA = Element.ALIGN_LEFT,
        /// <summary>
        /// 右對齊
        /// </summary>
        RA = Element.ALIGN_RIGHT
    }
    public class MPDF
    {
        public Document doc = null;
        MemoryStream pdfMS = null;
        //不要私自改這個變量的值
        public float top = 0;
        public float maxTop = 0;
        string path = null;
        int pageNum = 1;
        public iTextSharp.text.Rectangle size = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="size">例如:PageSize.A4</param>
        /// <param name="size">pdf文件保存路徑</param>
        public MPDF(iTextSharp.text.Rectangle size, string path)
        {
            this.path = path;
            this.size = size;
            doc = new Document(size);//定義一個Document,並設置頁面大小爲A4,橫向
            pdfMS = new MemoryStream();
            PdfWriter.GetInstance(doc, pdfMS);//PDF內容放入到流中
            doc.Open();
            maxTop = size.Height - doc.BottomMargin - doc.TopMargin;
        }

        /// <summary>
        /// 只是給MPDF_Table調用的,不需額外調用
        /// </summary>
        public void Add(PdfPTable ptable)
        {
            doc.Add(ptable);
            top += ptable.TotalHeight;
            pageNum = (int)(top / maxTop);
            float more = top - maxTop * pageNum;
            if (more > 0)
                pageNum++;
        }

        public string save()
        {
            try
            {
                doc.NewPage();//分頁
                doc.Close();
                byte[] fileByte = pdfMS.GetBuffer();
                FileStream fs = new FileStream(path, FileMode.Create);
                BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(fileByte);
                bw.Close();
                fs.Close();
                return null;
            }
            catch (Exception e)
            {
                return e.ToString();
            }
        }
    }
    public class MPDF_Table
    {
        //字體集合
        BaseFont[] bfs = new BaseFont[] {
            BaseFont.CreateFont("C://WINDOWS//Fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED),//宋體
            BaseFont.CreateFont("C://WINDOWS//Fonts//simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)//黑體
        };

        iTextSharp.text.Font font = null;
        PdfPTable pdfTableInfo = null;
        MPDF pdf = null;
        int fontIndex = 0;
        int fontSize = 0;
        float cellHeight = 0;
        int hasUseCellNum = 0;
        public int maxCellNum = 0;//每行必須填滿,否則不會顯示
        /// <summary>
        /// 表格,注意:當添加一個表格到pdf後,下一個添加的表格的初始y值會在上一個表格的y和高度和的基礎上疊加
        /// </summary>
        /// <param name="cellWidths">表格的列寬集合</param>
        /// <param name="pdf">該表格將寫入的pdf文件</param>
        /// <param name="fontSize">表格默認字體大小</param>
        /// <param name="cellHeight">表格默認行高</param>
        /// <param name="fontIndex">表格默認字體,即文件C:/WINDOWS/Fonts/下的字體文件名</param>
        /// <param name="align">表格默對齊方式,水平居中,只能調整水平方向</param>
        /// 
        public MPDF_Table(float[] cellWidths, MPDF pdf, int fontSize, float cellHeight, int fontIndex = 0, TextAlign align = TextAlign.HA)
        {
            this.fontSize = fontSize;
            maxCellNum = cellWidths.Length;
            this.cellHeight = cellHeight;
            font = new iTextSharp.text.Font(bfs[fontIndex], fontSize);
            this.fontIndex = fontIndex;
            this.pdf = pdf;
            pdfTableInfo = new PdfPTable(cellWidths.Length);
            pdfTableInfo.SetWidthPercentage(cellWidths, pdf.size);
            pdfTableInfo.NormalizeHeadersFooters();
            pdfTableInfo.SplitLate = false;
            pdfTableInfo.HorizontalAlignment = (int)align;
            //pdfTableInfo.TotalWidth = 605;
        }

        /// <summary>
        /// 添加單元格,規則:疊加式,第一行堆滿自動換行到第二行,特殊情況:例如,當某行只剩一個單元格的時候,你添加一個佔兩個單元格位置的單元格,那麼它實際佔用的只有一個單元格。
        /// </summary>
        /// <param name="txt">單元格內容</param>
        /// <param name="Colspan">單元格佔據多少個格子</param>
        /// <param name="fontIndex">字體設置,-1代表使用表格所設字體</param>
        /// <param name="fontSize">字體設置,-1代表使用表格所設字體大小</param>
        /// <param name="BorderWidthTop">單元格邊框線條寬度,默認0,即無線條</param>
        /// <param name="BorderWidthLeft">單元格邊框線條寬度,默認0,即無線條</param>
        /// <param name="BorderWidthRight">單元格邊框線條寬度,默認0,即無線條</param>
        /// <param name="BorderWidthBottom">單元格邊框線條寬度,默認0,即無線條</param>
        /// <param name="cellHeight">單元格高度默認0,即表格初始化所用高度</param>
        /// <param name="HorizontalAlignment">單元格文本水平對齊方式</param>
        /// <param name="VerticalAlignment">單元格文本垂直對齊方式</param>
        public void AddTextCell(string txt,
            int Colspan = 1,
            int fontIndex = -1,
            int fontSize = -1,
            int BorderWidthTop = 0,
            int BorderWidthLeft = 0,
            int BorderWidthRight = 0,
            int BorderWidthBottom = 0,
            float cellHeight = 0,
            TextAlign HorizontalAlignment = TextAlign.LA,
            TextAlign VerticalAlignment = TextAlign.HA)
        {
            iTextSharp.text.Font font = null;
            if (fontSize == -1)
                fontSize = this.fontSize;
            if (fontIndex == -1)
                font = this.font;
            else
                font = new iTextSharp.text.Font(bfs[fontIndex], fontSize);

            if (cellHeight == 0)
                cellHeight = this.cellHeight;
            PdfPCell pdfPInfoCell = new PdfPCell(new Phrase(txt, font));
            pdfPInfoCell.MinimumHeight = cellHeight;
            pdfPInfoCell.BorderWidthTop = BorderWidthTop;
            pdfPInfoCell.BorderWidthLeft = BorderWidthLeft;
            pdfPInfoCell.BorderWidthRight = BorderWidthRight;
            pdfPInfoCell.BorderWidthBottom = BorderWidthBottom;
            pdfPInfoCell.Colspan = Colspan;
            pdfPInfoCell.BorderColor = new BaseColor(0, 0, 0); //單元格邊框顏色,默認黑色
            pdfPInfoCell.HorizontalAlignment = (int)HorizontalAlignment;
            pdfPInfoCell.VerticalAlignment = (int)VerticalAlignment;
            pdfTableInfo.AddCell(pdfPInfoCell);

            hasUseCellNum += Colspan;
            if (hasUseCellNum >= maxCellNum)
                hasUseCellNum = 0;
        }

        /// <summary>
        /// 將一張圖片填在單元格
        /// </summary>
        /// <param name="ImagePath">圖片路徑</param>
        /// <param name="Colspan">單元格佔用空間,默認佔用一個基礎格子</param>
        /// <param name="Border">邊框線條寬度,默認0,無邊框</param>
        /// <param name="HorizontalAlignment">單元格內容水平對齊方式</param>
        /// <param name="VerticalAlignment">單元格內容垂直對齊方式</param>
        public void AddImageCell(string ImagePath,
            int Colspan = 1,
            int Border = 0,
            TextAlign HorizontalAlignment = TextAlign.LA,
            TextAlign VerticalAlignment = TextAlign.HA)
        {
            PdfPCell pdfPInfoCell = new PdfPCell();
            pdfPInfoCell.Border = Border;
            pdfPInfoCell.Colspan = Colspan;
            pdfPInfoCell.HorizontalAlignment = (int)HorizontalAlignment;
            pdfPInfoCell.VerticalAlignment = (int)VerticalAlignment;
            pdfPInfoCell.PaddingLeft = 10;
            //System.IO.Directory.GetCurrentDirectory() + @"\title2.png"
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ImagePath);
            pdfPInfoCell.Image = image; //圖片
            pdfTableInfo.AddCell(pdfPInfoCell);

            hasUseCellNum += Colspan;
            if (hasUseCellNum >= maxCellNum)
                hasUseCellNum = 0;
        }

        /// <summary>
        /// 添加一個沒有邊框的佔據表格的一行的單元格
        /// </summary>
        /// <param name="height"></param>
        public void AddEmptyLine(float height)
        {
            AddTextCell("", maxCellNum, -1, -1, 0, 0, 0, 0, height);
        }
        public void AddEmptyLine()
        {
            AddTextCell("", maxCellNum, -1, -1, 0, 0, 0, 0, cellHeight);
        }
        //填滿最後一行
        public void FullEndLine()
        {
            if (hasUseCellNum < maxCellNum && hasUseCellNum != 0)
            {
                AddTextCell("", maxCellNum - hasUseCellNum);
                hasUseCellNum = 0;
            }
        }
        public void AddTableToPDF()
        {
            //補齊
            FullEndLine();
            pdf.Add(pdfTableInfo);
        }
        /// <summary>
        /// 把表格添加到末尾,執行了這一個方法後,這一頁就不能再添加內容了!後來添加的將放到下一頁,當然,如果末尾裝不下,會換到下一頁的末尾,這個有點坑
        /// </summary>
        public void AddTableToPDF_InEnd()
        {
            int pageNum = (int)(pdf.top / pdf.maxTop);
            float more = pdf.top - pdf.maxTop * pageNum;
            more = pdf.maxTop - more;
            if (pdfTableInfo.TotalHeight > more)
            {
                MPDF_Table table = new MPDF_Table(new float[] { 10, 10 }, pdf, 1, more);
                table.AddEmptyLine();
                table.AddTableToPDF();
            }
            else
            {
                MPDF_Table table = new MPDF_Table(new float[] { 10, 10 }, pdf, 1, more - pdfTableInfo.TotalHeight);
                table.AddEmptyLine();
                table.AddTableToPDF();
            }

            AddTableToPDF();
        }


    }

    //測試例子
    public class MPDF_TEST
    {
        /// <summary>
        /// 測試例子
        /// </summary>
        /// <param name="path">必須是完整的路徑,並且要保證路徑所在文件夾存在</param>
        public static void GetYangWFZ_PDF(string path)
        {
            MPDF pdf = new MPDF(PageSize.A4, path);

            MPDF_Table table = new MPDF_Table(new float[] { 50, 50, 81, 81, 172, 15, 157 }, pdf, 10, 20, 1);

            //==============logo==================
            string imagePath = System.IO.Directory.GetCurrentDirectory() + @"\title2.png";//這時一個圖片的路徑
            table.AddTextCell("");
            table.AddImageCell(imagePath, 4);
            table.AddTextCell("");
            table.AddTextCell("XXXXXX區長征路24號\n0000-000000", 1, 0, -1, 0, 0, 0, 0, 0, TextAlign.HA, TextAlign.BA);

            table.AddEmptyLine(5);
            //================基本信息===========================
            table.AddTextCell("體液檢驗 MZFUS200", 3);
            table.AddTextCell("", 2);
            table.AddTextCell("標本編號:20192232322", 2);

            table.AddTextCell("姓名:XXXXX", 2);
            table.AddTextCell("病人類別:XXXX", 2);
            table.AddTextCell("病員編號:502936");
            table.AddTextCell("標本種類:XXXX", 2);

            table.AddTextCell("性別:男", 2);
            table.AddTextCell("病區科室:XXXXX", 2);
            table.AddTextCell("臨牀診斷:");
            table.AddTextCell("病員牀號:1111123", 2);

            table.AddTextCell("年齡:20", 2, -1, -1, 0, 0, 0, 1);
            table.AddTextCell("申請時間:2019/9/12 20:34", 2, -1, -1, 0, 0, 0, 1);
            table.AddTextCell("送檢時間:2019/9/12 20:35", 1, -1, -1, 0, 0, 0, 1);
            table.AddTextCell("採樣時間:2019/9/12 20:34", 2, -1, -1, 0, 0, 0, 1);
            //==================培養結果==========================

            table.AddTextCell("培養結果:", 4, 0);
            table.AddTextCell("        菌落計數:", 3, 0);
            table.AddTextCell("    " + "支原體", 4, 1);//培養結果
            table.AddTextCell("            " + ">10萬cfu/ml", 3, 0);
            //==================藥敏試驗==========================
            table.AddEmptyLine();
            table.AddEmptyLine();
            table.AddTextCell("  藥敏試驗:", 4, 0);
            table.FullEndLine();
            table.AddTableToPDF();

            table = new MPDF_Table(new float[] { 101, 101, 90, 11, 11, 90, 101, 101 }, pdf, 10, 13, 0);
            table.AddTextCell("支原體", table.maxCellNum, 1, -1, 1, 0, 0, 0, 20, TextAlign.LA, TextAlign.BA);
            table.AddTextCell("", 8, -1, -1, 0, 0, 0, 0, 5);
            table.AddTextCell("", 4, -1, -1, 0, 0, 1, 1, 5);
            table.AddTextCell("", 4, -1, -1, 0, 0, 0, 1, 5);
            table.AddTextCell("藥物名稱", 1, -1, -1, 0, 0, 0, 1, 22);
            table.AddTextCell("DISK(mm)", 1, -1, -1, 0, 0, 0, 1, 22, TextAlign.HA);
            table.AddTextCell("敏感度", 1, -1, -1, 0, 0, 0, 1, 22, TextAlign.RA);
            table.AddTextCell("", 1, -1, -1, 0, 0, 1, 1, 22, TextAlign.RA);

            table.AddTextCell("", 1, -1, -1, 0, 0, 0, 1, 22, TextAlign.RA);
            table.AddTextCell("藥物名稱", 1, -1, -1, 0, 0, 0, 1, 22);
            table.AddTextCell("DISK(mm)", 1, -1, -1, 0, 0, 0, 1, 22, TextAlign.HA);
            table.AddTextCell("敏感度  ", 1, -1, -1, 0, 0, 0, 1, 22, TextAlign.RA);

            //模擬內容====
            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);
            table.AddTextCell("", 1, -1, -1, 0, 0, 1);
            table.AddTextCell("");
            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);

            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);
            table.AddTextCell("", 1, -1, -1, 0, 0, 1);
            table.AddTextCell("");
            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);

            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);
            table.AddTextCell("", 1, -1, -1, 0, 0, 1);
            table.AddTextCell("");
            table.AddTextCell("頭孢");
            table.AddTextCell("");
            table.AddTextCell("耐藥", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);
            //========
            table.AddTextCell("", 4, -1, -1, 1, 0, 1);
            table.AddTextCell("", 4, -1, -1, 1);


            table.AddTableToPDF();

            MPDF_Table table2 = new MPDF_Table(new float[] { 100, 170, 170, 160 }, pdf, 9, 14);
            table2.AddTextCell("備註:", 4, -1, -1, 1);

            table2.AddTextCell("送檢醫生:XXXX", 1, -1, -1, 1);
            table2.AddTextCell("報告時間:2019/9/12 20:36", 1, -1, -1, 1);
            table2.AddTextCell("檢驗:XXXX", 1, -1, -1, 1);
            table2.AddTextCell("審覈:系統管理員", 1, -1, -1, 1);

            table2.AddEmptyLine();

            table2.AddTextCell("注:本次實驗報告僅對本次標本負責,如有疑問,請於24小時內提出諮詢", 3);
            table2.AddTextCell("第1頁/共1頁", 1, -1, -1, 0, 0, 0, 0, 0, TextAlign.RA);
            table2.AddTableToPDF_InEnd();

            pdf.save();
        }

    }
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章