MultiColumnText.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 GrapeCity.Documents.Pdf;
  9. using GrapeCity.Documents.Text;
  10.  
  11. namespace DsPdfWeb.Demos.Basics
  12. {
  13. // Creates a simple 3-column text layout.
  14. // For a slightly more complex but practically more useful way
  15. // to render text in columns, see BalancedColumns.
  16. public class MultiColumnText
  17. {
  18. public int CreatePDF(Stream stream)
  19. {
  20. var doc = new GcPdfDocument();
  21. var g = doc.NewPage().Graphics;
  22. var tl = g.CreateTextLayout();
  23. tl.DefaultFormat.Font = StandardFonts.Times;
  24. tl.DefaultFormat.FontSize = 12;
  25. tl.TextAlignment = TextAlignment.Justified;
  26. tl.FirstLineIndent = 72 / 2;
  27. tl.ParagraphSpacing = 72 / 8;
  28. // Add some text (note that TextLayout interprets "\r\n" as paragraph delimiter):
  29. tl.Append(Common.Util.LoremIpsum(20));
  30. // Set up columns:
  31. const int colCount = 3;
  32. // 1/2" margins all around:
  33. const float margin = 72 / 2;
  34. // 1/4" gap between columns:
  35. const float colGap = margin / 4;
  36. float colWidth = (doc.Pages.Last.Size.Width - margin * 2) / colCount - colGap * (colCount - 1);
  37. tl.MaxWidth = colWidth;
  38. tl.MaxHeight = doc.Pages.Last.Size.Height - margin * 2;
  39. // Calculate glyphs and perform layout for the whole text:
  40. tl.PerformLayout(true);
  41. // In a loop, split and render the text in the current column:
  42. int col = 0;
  43. while (true)
  44. {
  45. // 'rest' will accept the text that did not fit:
  46. var splitResult = tl.Split(null, out TextLayout rest);
  47. g.DrawTextLayout(tl, new PointF(margin + col * (colWidth + colGap), margin));
  48. if (splitResult != SplitResult.Split)
  49. break;
  50. tl = rest;
  51. if (++col == colCount)
  52. {
  53. doc.Pages.Add();
  54. g = doc.Pages.Last.Graphics;
  55. col = 0;
  56. }
  57. }
  58. // Done:
  59. doc.Save(stream);
  60. return doc.Pages.Count;
  61. }
  62. }
  63. }
  64.