KeepWithNext.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 prevent a page break between a paragraph
  14. // and the next one when splitting a TextLayout.
  15. // Splitting of text in this sample is similar to that in PaginatedText,
  16. // see comments in PaginatedText for more info on text handling.
  17. public class KeepWithNext
  18. {
  19. public int CreatePDF(Stream stream)
  20. {
  21. const int NPAR = 40;
  22. var doc = new GcPdfDocument();
  23. var tl = new TextLayout(72)
  24. {
  25. FirstLineIndent = 72 / 2,
  26. MaxWidth = doc.PageSize.Width,
  27. MaxHeight = doc.PageSize.Height,
  28. MarginAll = 72,
  29.  
  30. };
  31. tl.DefaultFormat.Font = StandardFonts.Times;
  32. tl.DefaultFormat.FontSize = 12;
  33. // Text format for paragraphs kept together with next one:
  34. var tf = new TextFormat(tl.DefaultFormat)
  35. {
  36. FontSize = tl.DefaultFormat.FontSize + 2,
  37. FontBold = true
  38. };
  39. // We add a number of random 'lorem ipsum' paragraphs to this document,
  40. // adding a 'caption' before each paragraph which is kept together
  41. // with the following 'lorem ipsum' paragraph:
  42. for (int i = 0; i < NPAR; i++)
  43. {
  44. // 'Caption' kept together with the next paragraph:
  45. tl.Append("Caption kept together with the next paragraph. No page break after this.", tf);
  46. // AppendParagraphBreak adds a paragraph break but prevents a page break between the two paragraphs:
  47. tl.AppendParagraphBreak();
  48. // Random paragraph after 'caption':
  49. tl.Append(Common.Util.LoremIpsum(1));
  50. }
  51. tl.PerformLayout(true);
  52. // We force all paragraph lines to stay on the same page,
  53. // this makes it more obvious that 'caption' and following paragraph
  54. // are kept on the same page:
  55. var to = new TextSplitOptions(tl)
  56. {
  57. KeepParagraphLinesTogether = true,
  58. };
  59. // In a loop, split and render the text:
  60. while (true)
  61. {
  62. // 'rest' will accept the text that did not fit:
  63. var splitResult = tl.Split(to, out TextLayout rest);
  64. doc.Pages.Add().Graphics.DrawTextLayout(tl, PointF.Empty);
  65. if (splitResult != SplitResult.Split)
  66. break;
  67. tl = rest;
  68. }
  69. // Done:
  70. doc.Save(stream);
  71. return doc.Pages.Count;
  72. }
  73. }
  74. }
  75.