C#中PDFsharp & MigraDoc Foundation 相关用法 (一)

2023-10-07 22:01:14 浏览数 (1)

1、设置页眉页脚

代码语言:javascript复制
var section = Document.AddSection();
 section.PageSetup.PageHeight = Height;//Height 为你的页高
 section.PageSetup.PageWidth = Width;//Width 为你设置的页宽
 section.PageSetup.HeaderDistance = 10;//设置页眉距离上边距为10
 var par=  section.Headers.Primary.AddParagraph();//新增页眉段落
 paragraph.AddText("我是页眉!");
 paragraph.Format.Alignment = ParagraphAlignment.Right;//新增了一个靠右的页眉
 //如果设置左右对称页眉 或者多段页眉 可以参考设置一个table 在页眉,就可以等分做页眉了
 var table = section.Headers.Primary.AddTable();
 table.Borders.Visible = false;
 table.TopPadding = 5;
 //页脚相同设置方法

2、设置Table自适应列宽

代码语言:javascript复制
        /// <summary>
        /// 获取table
        /// </summary>
        /// <param name="section"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public Table GetTable(Section section, Dictionary<string, double> headers, bool autoWidth = false)
        {
            //创建一个Table
            Table table = section.AddTable();
            table.Format.KeepTogether = false;
            table.Format.KeepWithNext = false;
            table.Format.Alignment = ParagraphAlignment.Left;
            //设置table边框不显示
            table.Borders.Width =0;
            table.Borders.Color = Colors.Transparent;
            if (autoWidth)//如果是自动宽度
            {
                //找出所有份数之和
                var all = headers.Values.Sum(p => p);
                //页宽-左右边距60*2 /分数 得到代表每一份的宽度
                var pre = (Width - 120) / all;
                foreach (var item in headers)
                {
                    //按照宽度来设定列宽
                    table.AddColumn(Unit.FromPoint(pre * item.Value));
                }
            }
            else
            {
                //非自动列宽下  均分
                var pre = (Width - 160) / (headers.Count);

                for (var i = 0; i < headers.Count; i  )
                {
                    table.AddColumn(Unit.FromPoint(pre));
                }
            }
            return table;
         }

3、设置Table中单元格内字符溢出自动换行

代码语言:javascript复制
        /// <summary>
        /// 表格自适应txt
        /// </summary>
        /// <param name="instring">输入字符串</param>
        /// <param name="cell">要插入字符的单元格</param>
        /// <param name="fontsize">字体大小</param>
        /// <returns></returns>
        public Paragraph AddTextToCell(string instring, Cell cell, Unit fontsize, Paragraph paragraph = null)
        {
            if (instring == null)
                instring = " ";
            using (PdfDocument pdfd = new PdfDocument())
            {
                PdfPage pg = pdfd.AddPage();

                using (XGraphics oGFX = XGraphics.FromPdfPage(pg))
                {
                    //列宽-padding宽度 得到实际宽度
                    Unit maxWidth = cell.Column.Width - (cell.Column.LeftPadding   cell.Column.RightPadding);
                    Paragraph par = paragraph;
                    //测量需要指定字体和字体大小
                    XFont font = new XFont(ConfigHelper.Config.PdfFontFamliy, fontsize);
                    //测量字体大小
                    var result = oGFX.MeasureString(instring, font);
                    ///如果字体宽度小于列宽或者  跟列宽差值在1.5则认为不需要分行  这个判断后加的 其实判断后边的条件就好
                    if (result.Width < maxWidth.Value || result.Width - maxWidth.Value < 1.5)
                    {
                        if (par != null)
                        {
                            var text = par.AddText(instring);
                        }
                        else
                        {
                            par = cell.AddParagraph(instring);
                        }
                    }
                    else 
                    {
                        //如果字符宽度大于列宽 且包含空格,这种情况下MigraDoc会进行自动换行 不用管
                        //适用于英文下描述的单元格 比如 Hello World 这种 如果列宽在Wor处截断显然不合适 让他自己划分单词就好了
                        var ds = instring.Split(' ');
                        if (ds.Length > 1)
                        {
                            if (par == null)
                                par = cell.AddParagraph(instring);
                            else par.AddText(instring);
                        }
                        else
                        {
                            if (par == null)
                                par = cell.AddParagraph();

                            double width = 0;
                            //将字符串拆分成字符数组
                            var fontStrs = instring.ToArray();
                            string str = "";
                            foreach (var item in fontStrs)
                            {
                                //挨个测量字符并将长度相加
                                width  = oGFX.MeasureString(item.ToString(), font).Width;
                                if (width > maxWidth.Value - 2)//如果长度差2 则插入换行符实现换行
                                {
                                    var txt = par.AddText(str.Trim());
                                    par.AddFormattedText("r");
                                    str = "";
                                    width = 0;
                                }
                                str  = item.ToString();
                            }
                            par.AddText(str);
                        }
                    }
                    return par;
                }
            }
        }

3、PDFSharp指定字体文件(这段代码网上找的 自己参考参考就好)

代码语言:javascript复制
internal class TangFontResolver : IFontResolver
    {
        public byte[] GetFont(string faceName)
        {
            string str = "";
            str = Path.Combine(DataHelper.Icons, ConfigHelper.Config.PdfFontFileName);
            return LoadFontData(str);
        }
        byte[] LoadFontData(string name)
        {
            if (string.IsNullOrWhiteSpace(name)) return null;
            if (!File.Exists(name)) return null;
            using (Stream stream = new MemoryStream(File.ReadAllBytes(name)))
            {
                if (stream == null)
                    throw new ArgumentException("No resource with name "   name);

                var count = (int)stream.Length;
                var data = new byte[count];
                stream.Read(data, 0, count);
                return data;
            }
        }
        public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
        {
            string lowerFamilyName = familyName.ToLowerInvariant();

            // Looking for a JetBrains Mono font?
            if (lowerFamilyName == ConfigHelper.Config.PdfFontFamliy.ToLower())
            {
                // Bold simulation is not recommended, but used here for demonstration.
                bool simulateBold = false;

                // Since Segoe WP typefaces do not contain any italic font
                // always simulate italic if it is requested.
                bool simulateItalic = false;

                string faceName;
                faceName = ConfigHelper.Config.PdfFontFamliy;
                // In this sample family names are case sensitive. You can relax this in your own implementation
                // and make them case insensitive.
                //switch (familyName)
                //{
                //    case FamilyNames.JetBrainsMonoRegular:
                //        faceName = FaceNames.JetBrainsMonoRegular;
                //        break;

                //    case FamilyNames.HansRegular:
                //        faceName = FaceNames.HansRegular;
                //        break;

                //    default:
                //        Debug.Assert(false, "Unknown JetBrains Mono font: "   lowerFamilyName);
                //        goto case FamilyNames.JetBrainsMonoRegular;  // Alternatively throw an exception in this case.
                //}

                // Tell the caller the effective typeface name and whether bold  or italic should be simulated.
                return new FontResolverInfo(faceName, simulateBold, simulateItalic);
            }

            // Return null means that the typeface cannot be resolved and PDFsharp stops working.
            // Alternatively forward call to PlatformFontResolver.
            return PlatformFontResolver.ResolveTypeface(familyName, isBold, isItalic);
        }
    }
    //使用
      PdfSharp.Fonts.GlobalFontSettings.FontResolver = new TangFontResolver();
      

原文

0 人点赞