SubSuperScript.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using System.Text.RegularExpressions;
  9. using GrapeCity.Documents.Drawing;
  10. using GrapeCity.Documents.Pdf;
  11. using GrapeCity.Documents.Text;
  12. using GCTEXT = GrapeCity.Documents.Text;
  13. using GCDRAW = GrapeCity.Documents.Drawing;
  14.  
  15. namespace DsPdfWeb.Demos.Basics
  16. {
  17. // This sample shows how to render subscript and superscript text.
  18. public class SubSuperScript
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. var doc = new GcPdfDocument();
  23. var page = doc.NewPage();
  24. var g = page.Graphics;
  25.  
  26. var rc = Common.Util.AddNote(
  27. "Demo of the TextFormat.Subscript and TextFormat.Superscript properties. " +
  28. "We draw a random 'lorem ipsum' paragraph, rendering all instances of 'lorem' as subscript, " +
  29. "and all instances of 'ipsum' as superscript.",
  30. page);
  31.  
  32. // Get a random 'lorem ipsum' paragraph:
  33. var para = Common.Util.LoremIpsum(1, 18, 20, 20, 20);
  34.  
  35. // Split the paragraph into 'lorem', 'ipsum' and everything else:
  36. const string sub = "lorem";
  37. const string super = "ipsum";
  38. var frags = Regex.Split(para, $"({sub})|({super})");
  39.  
  40. var font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "times.ttf"));
  41.  
  42. // Create text formats for subscript and superscript:
  43. var tfSub = new TextFormat() { Font = font, FontSize = 12, Subscript = true };
  44. var tfSuper = new TextFormat(tfSub) { Subscript = false, Superscript = true };
  45.  
  46. // Add text to a TextLayout using special formats for 'lorem' and 'ipsum':
  47. var tl = g.CreateTextLayout();
  48. tl.DefaultFormat.Font = font;
  49. tl.DefaultFormat.FontSize = 12;
  50. foreach (var frag in frags)
  51. {
  52. if (frag == sub)
  53. tl.Append(frag, tfSub);
  54. else if (frag == super)
  55. tl.Append(frag, tfSuper);
  56. else
  57. tl.Append(frag);
  58. }
  59.  
  60. // Set layout properties and render the text:
  61. tl.MaxWidth = page.Size.Width;
  62. tl.MaxHeight = page.Size.Height - rc.Height;
  63. tl.MarginAll = 72;
  64. tl.MarginTop = rc.Bottom + 36;
  65. tl.PerformLayout(true);
  66. g.DrawTextLayout(tl, PointF.Empty);
  67.  
  68. // Done:
  69. doc.Save(stream);
  70. return doc.Pages.Count;
  71. }
  72. }
  73. }
  74.