PaginatedText.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. // This sample shows how to render a long text spanning multiple pages.
  14. public class PaginatedText
  15. {
  16. public int CreatePDF(Stream stream)
  17. {
  18. var doc = new GcPdfDocument();
  19. // Use TextLayout to render text:
  20. var tl = new TextLayout(72);
  21. // If not specifying formats for individual runs, we MUST provide
  22. // font and font size on TextLayout.DefaultFormat:
  23. tl.DefaultFormat.Font = StandardFonts.Times;
  24. tl.DefaultFormat.FontSize = 12;
  25. // First line offset 1/2":
  26. tl.FirstLineIndent = 72 / 2;
  27. //
  28. // All other formatting properties are left at their default values.
  29. // In particular, TextLayout's default resolution is 72 dpi -
  30. // the same as DsPdf's, and WordWrap is true.
  31. //
  32. // Set TextLayout's area to the whole page:
  33. tl.MaxWidth = doc.PageSize.Width;
  34. tl.MaxHeight = doc.PageSize.Height;
  35. // ...and have it manage the page margins (1" all around):
  36. tl.MarginAll = tl.Resolution;
  37. //
  38. // Append the text (20 paragraphs so they would not fit on a single page)
  39. // (note that TextLayout interprets "\r\n" as paragraph delimiter):
  40. tl.Append(Common.Util.LoremIpsum(20));
  41. //
  42. // When all text has been added, we must calculate the glyphs needed to render the text,
  43. // and perform the layout. This can be done by a single call to PerformLayout, passing true to
  44. // recalculate glyphs first (even though the text won't all fit in the specified max size,
  45. // we only need to call PerformLayout once):
  46. tl.PerformLayout(true);
  47. // Use split options to provide widow/orphan control:
  48. var to = new TextSplitOptions(tl);
  49. to.MinLinesInFirstParagraph = 2;
  50. to.MinLinesInLastParagraph = 2;
  51. // In a loop, split and render the text:
  52. while (true)
  53. {
  54. // 'rest' will accept the text that did not fit:
  55. var splitResult = tl.Split(to, out TextLayout rest);
  56. doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty);
  57. if (splitResult != SplitResult.Split)
  58. break;
  59. tl = rest;
  60. }
  61. // Done:
  62. doc.Save(stream);
  63. return doc.Pages.Count;
  64. }
  65. }
  66. }
  67.