MultiFormattedText.cs
  1. // 完毕:
  2. using System;
  3. using System.IO;
  4. using System.Drawing;
  5. using GrapeCity.Documents.Drawing;
  6. using GrapeCity.Documents.Pdf;
  7. using GrapeCity.Documents.Text;
  8.  
  9. namespace DsPdfWeb.Demos.Basics
  10. {
  11. // 该示例展示了如何使用不同的文本格式
  12. // (字体、颜色)在一个段落中。
  13. public class MultiFormattedText
  14. {
  15. public int CreatePDF(Stream stream)
  16. {
  17. // 生成引用其格式选项的示例文本的函数:
  18. Func<TextFormat, string> makeSampleText = (tf_) =>
  19. {
  20. string boldItalic = string.Empty;
  21. if (tf_.Font.FontBold)
  22. boldItalic = "bold ";
  23. if (tf_.Font.FontItalic)
  24. boldItalic += "italic ";
  25. if (boldItalic == string.Empty)
  26. boldItalic = "normal ";
  27. return $"This is {boldItalic}text drawn using font '{tf_.Font.FullFontName}', font size {tf_.FontSize} points, " +
  28. $"text color {tf_.ForeColor}, background color {tf_.BackColor}. ";
  29. };
  30. // 字体名称:
  31. const string times = "times new roman";
  32. const string arial = "arial";
  33. // 创建文档和文本布局:
  34. var doc = new GcPdfDocument();
  35. var page = doc.NewPage();
  36. var g = page.Graphics;
  37. var tl = g.CreateTextLayout();
  38. // 使用 TextLayout 布局整个页面并保持边距:
  39. tl.MaxHeight = page.Size.Height;
  40. tl.MaxWidth = page.Size.Width;
  41. tl.MarginAll = 72;
  42. // 获取一些字体:
  43. var fc = new FontCollection();
  44. fc.RegisterDirectory(Path.Combine("Resources", "Fonts"));
  45. var fTimes = fc.FindFamilyName(times, false, false);
  46. var fTimesBold = fc.FindFamilyName(times, true, false);
  47. var fTimesItalic = fc.FindFamilyName(times, false, true);
  48. var fTimesBoldItalic = fc.FindFamilyName(times, true, true);
  49. var fArial = fc.FindFamilyName(arial, false, false);
  50. // 使用不同的字体和字体大小将文本添加到 TextLayout:
  51. var tf = new TextFormat() { Font = fTimes, FontSize = 12, };
  52. tl.Append(makeSampleText(tf), tf);
  53. tf.Font = fTimesBold;
  54. tf.FontSize += 2;
  55. tl.Append(makeSampleText(tf), tf);
  56. tf.Font = fTimesItalic;
  57. tf.FontSize += 2;
  58. tl.Append(makeSampleText(tf), tf);
  59. tf.Font = fTimesBoldItalic;
  60. tf.FontSize += 2;
  61. tl.Append(makeSampleText(tf), tf);
  62. tf.Font = fArial;
  63. tf.FontSize += 2;
  64. tl.Append(makeSampleText(tf), tf);
  65. // 添加具有不同前景色和背景色的文本:
  66. tf.Font = fTimesBold;
  67. tf.ForeColor = Color.Tomato;
  68. tl.Append(makeSampleText(tf), tf);
  69. tf.Font = fTimesBoldItalic;
  70. tf.FontSize = 16;
  71. tf.ForeColor = Color.SlateBlue;
  72. tf.BackColor = Color.Orange;
  73. tl.Append(makeSampleText(tf), tf);
  74. // 再次在透明上涂上纯黑色:
  75. tl.Append("The end.", new TextFormat() { Font = fTimes, FontSize = 14, });
  76. // 布局和绘制文本:
  77. tl.PerformLayout(true);
  78. g.DrawTextLayout(tl, PointF.Empty);
  79. // 完毕:
  80. doc.Save(stream);
  81. return doc.Pages.Count;
  82. }
  83. }
  84. }
  85.