RotatedText2.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.Numerics;
  9. using GrapeCity.Documents.Drawing;
  10. using GrapeCity.Documents.Pdf;
  11. using GrapeCity.Documents.Text;
  12.  
  13. namespace DsPdfWeb.Demos.Basics
  14. {
  15. // Shows how to use GcPdfGraphics.Transform to rotate a text string
  16. // (alternative way using matrix multiplication).
  17. // See also RotatedText.
  18. public class RotatedText2
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. // Rotation angle, degrees clockwise:
  23. float angle = -45;
  24. //
  25. var doc = new GcPdfDocument();
  26. var g = doc.NewPage().Graphics;
  27. // Create a text layout, pick a font and font size:
  28. TextLayout tl = g.CreateTextLayout();
  29. tl.DefaultFormat.Font = StandardFonts.Times;
  30. tl.DefaultFormat.FontSize = 24;
  31. // Add a text, and perform layout:
  32. tl.Append("Rotated text.");
  33. tl.PerformLayout(true);
  34. // Text insertion point at (1",1"):
  35. var ip = new PointF(72, 72);
  36. // Now that we have text size, create text rectangle with top left at insertion point:
  37. var rect = new RectangleF(ip.X, ip.Y, tl.ContentWidth, tl.ContentHeight);
  38. // Rotation center point in the middel of text bounding rectangle:
  39. var center = new PointF(ip.X + tl.ContentWidth / 2, ip.Y + tl.ContentHeight / 2);
  40. // Transformations can be combined by multiplying matrices.
  41. // Note that matrix multiplication is not commutative -
  42. // the sequence of operands is important, and is applied from last to first
  43. // matrices being multiplied:
  44. // 3) Translate the origin back to (0,0):
  45. // 2) Rotate around new origin by the specified angle:
  46. // 1) Translate the origin from default (0,0) to rotation center:
  47. g.Transform =
  48. Matrix3x2.CreateTranslation(-center.X, -center.Y) *
  49. Matrix3x2.CreateRotation((float)(angle * Math.PI) / 180f) *
  50. Matrix3x2.CreateTranslation(center.X, center.Y);
  51. // Draw rotated text and bounding rectangle:
  52. g.DrawTextLayout(tl, ip);
  53. g.DrawRectangle(rect, Color.Black, 1);
  54. // Remove transformation and draw the bounding rectangle where the non-rotated text would have been:
  55. g.Transform = Matrix3x2.Identity;
  56. g.DrawRectangle(rect, Color.ForestGreen, 1);
  57. // Done:
  58. doc.Save(stream);
  59. return doc.Pages.Count;
  60. }
  61. }
  62. }
  63.