AddWatermark.cs
- //
- // This code is part of Document Solutions for PDF demos.
- // Copyright (c) MESCIUS inc. All rights reserved.
- //
- using System;
- using System.IO;
- using System.Drawing;
- using System.Numerics;
- using GrapeCity.Documents.Pdf;
- using GrapeCity.Documents.Text;
- using GCTEXT = GrapeCity.Documents.Text;
- using GCDRAW = GrapeCity.Documents.Drawing;
-
- namespace DsPdfWeb.Demos
- {
- // This sample shows how to add a simple text watermark-like overlay
- // to all pages of an existing PDF.
- public class AddWatermark
- {
- public int CreatePDF(Stream stream)
- {
- var doc = new GcPdfDocument();
- using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "SlidePages.pdf"));
- doc.Load(fs);
- foreach (var page in doc.Pages)
- {
- var g = page.Graphics;
-
- // Text layout used to draw the 'watermark':
- var tl = g.CreateTextLayout();
- tl.Append("DsPdf Demo");
- tl.DefaultFormat.Font = GCTEXT.Font.FromFile(Path.Combine("Resources", "Fonts", "calibrib.ttf"));
- tl.DefaultFormat.FontSize = g.Resolution;
- // Semi-transparent color:
- tl.DefaultFormat.ForeColor = Color.FromArgb(128, Color.Yellow);
- tl.DefaultFormat.GlyphAdvanceFactor = 1.5f;
- tl.PerformLayout();
-
- // Rotation angle (radians) - from left/bottom to right/top corners of the page:
- var angle = -Math.Asin(g.CanvasSize.Width / g.CanvasSize.Height);
- // Page center:
- var center = new PointF(g.CanvasSize.Width / 2, g.CanvasSize.Height / 2);
- // Additional offset from text size:
- var delta = new PointF(
- (float)((tl.ContentWidth * Math.Cos(angle) - tl.ContentHeight * Math.Sin(angle)) / 2),
- (float)((tl.ContentWidth * Math.Sin(angle) + tl.ContentHeight * Math.Cos(angle)) / 2));
-
- // Draw watermark text diagonally in the center of the page
- // (matrix transforms are applied from last to first):
- g.Transform =
- Matrix3x2.CreateRotation((float)angle) *
- Matrix3x2.CreateTranslation(center.X - delta.X, center.Y - delta.Y);
-
- g.DrawTextLayout(tl, PointF.Empty);
- g.Transform = Matrix3x2.Identity;
- }
- doc.Save(stream);
- return doc.Pages.Count;
- }
- }
- }
-