AddWatermark.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.Pdf;
  10. using GrapeCity.Documents.Text;
  11. using GCTEXT = GrapeCity.Documents.Text;
  12. using GCDRAW = GrapeCity.Documents.Drawing;
  13.  
  14. namespace DsPdfWeb.Demos
  15. {
  16. // This sample shows how to add a simple text watermark-like overlay
  17. // to all pages of an existing PDF.
  18. public class AddWatermark
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. var doc = new GcPdfDocument();
  23. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf"));
  24. doc.Load(fs);
  25. foreach (var page in doc.Pages)
  26. {
  27. var g = page.Graphics;
  28.  
  29. // Text layout used to draw the 'watermark':
  30. var tl = g.CreateTextLayout();
  31. tl.Append("DsPdf Demo");
  32. tl.DefaultFormat.Font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "calibrib.ttf"));
  33. tl.DefaultFormat.FontSize = g.Resolution;
  34. // Semi-transparent color:
  35. tl.DefaultFormat.ForeColor = Color.FromArgb(128, Color.Yellow);
  36. tl.DefaultFormat.GlyphAdvanceFactor = 1.5f;
  37. tl.PerformLayout();
  38.  
  39. // Rotation angle (radians) - from left/bottom to right/top corners of the page:
  40. var angle = -Math.Asin(g.CanvasSize.Width / g.CanvasSize.Height);
  41. // Page center:
  42. var center = new PointF(g.CanvasSize.Width / 2, g.CanvasSize.Height / 2);
  43. // Additional offset from text size:
  44. var delta = new PointF(
  45. (float)((tl.ContentWidth * Math.Cos(angle) - tl.ContentHeight * Math.Sin(angle)) / 2),
  46. (float)((tl.ContentWidth * Math.Sin(angle) + tl.ContentHeight * Math.Cos(angle)) / 2));
  47.  
  48. // Draw watermark text diagonally in the center of the page
  49. // (matrix transforms are applied from last to first):
  50. g.Transform =
  51. Matrix3x2.CreateRotation((float)angle) *
  52. Matrix3x2.CreateTranslation(center.X - delta.X, center.Y - delta.Y);
  53.  
  54. g.DrawTextLayout(tl, PointF.Empty);
  55. g.Transform = Matrix3x2.Identity;
  56. }
  57. doc.Save(stream);
  58. return doc.Pages.Count;
  59. }
  60. }
  61. }
  62.