TagParagraphs.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. using GrapeCity.Documents.Pdf.Structure;
  11. using GrapeCity.Documents.Pdf.MarkedContent;
  12.  
  13. namespace DsPdfWeb.Demos.Basics
  14. {
  15. // This sample shows how to create tagged (structured) PDF.
  16. // To see/explore the tags, open the document in Adobe Acrobat Pro and go to
  17. // View | Navigation Panels | Tags.
  18. public class TagParagraphs
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. var doc = new GcPdfDocument();
  23. var rnd = Common.Util.NewRandom();
  24. int pageCount = rnd.Next(3, 7);
  25.  
  26. // Create Part element, it will contain P (paragraph) elements
  27. var sePart = new StructElement("Part");
  28. doc.StructTreeRoot.Children.Add(sePart);
  29.  
  30. // Add some pages, on each page add some paragraphs and tag them:
  31. for (int pageIndex = 0; pageIndex < pageCount; ++pageIndex)
  32. {
  33. // Add page:
  34. var page = doc.Pages.Add();
  35. var g = page.Graphics;
  36. const float margin = 36;
  37. const float dy = 18;
  38.  
  39. // Add some paragraphs:
  40. int paraCount = rnd.Next(1, 5);
  41. float y = margin;
  42. for (int i = 0; i < paraCount; ++i)
  43. {
  44. // Create paragraph element:
  45. var seParagraph = new StructElement("P") { DefaultPage = page };
  46. // Add it to Part element:
  47. sePart.Children.Add(seParagraph);
  48.  
  49. // Create paragraph:
  50. var tl = g.CreateTextLayout();
  51. tl.DefaultFormat.Font = StandardFonts.Helvetica;
  52. tl.DefaultFormat.FontSize = 12;
  53. tl.Append(Common.Util.LoremIpsum(1, 1, 5, 5, 10));
  54. tl.MaxWidth = page.Size.Width;
  55. tl.MarginLeft = tl.MarginRight = margin;
  56. tl.PerformLayout(true);
  57.  
  58. // Draw TextLayout within tagged content:
  59. g.BeginMarkedContent(new TagMcid("P", i));
  60. g.DrawTextLayout(tl, new PointF(0, y));
  61. g.EndMarkedContent();
  62.  
  63. y += tl.ContentHeight + dy;
  64.  
  65. // Add content item to paragraph StructElement:
  66. seParagraph.ContentItems.Add(new McidContentItemLink(i));
  67. }
  68. }
  69.  
  70. // Mark document as tagged:
  71. doc.MarkInfo.Marked = true;
  72.  
  73. // Done:
  74. doc.Save(stream);
  75. return doc.Pages.Count;
  76. }
  77. }
  78. }
  79.