AddWatermark.cs
- // 完毕:
- 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
- {
- // 此示例展示了如何添加简单的类似文本水印的叠加层
- // 到现有 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;
-
- // 用于绘制“水印”的文本布局:
- 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;
- // 半透明颜色:
- tl.DefaultFormat.ForeColor = Color.FromArgb(128, Color.Yellow);
- tl.DefaultFormat.GlyphAdvanceFactor = 1.5f;
- tl.PerformLayout();
-
- // 旋转角度(弧度)- 从页面的左/下角到右/上角:
- var angle = -Math.Asin(g.CanvasSize.Width / g.CanvasSize.Height);
- // 页面中心:
- var center = new PointF(g.CanvasSize.Width / 2, g.CanvasSize.Height / 2);
- // 文本大小的额外偏移:
- 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));
-
- // 在页面中心对角绘制水印文本
- // (矩阵变换从最后到第一个应用):
- 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;
- }
- }
- }
-