void AddWatermark(string filename)
{
// Open original XPS document
XpsDocument xpsOld = new XpsDocument(filename, FileAccess.Read);
FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence();
// Create new XPS document
string path = Path.GetFileName(filename);
Package container = Package.Open("new_" + path, FileMode.Create);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(new XpsDocument(container));
// Needed for writing multiple pages
SerializerWriterCollator vxpsd = writer.CreateVisualsCollator();
int pageno = 1;
vxpsd.BeginBatchWrite();
foreach (DocumentReference r in seqOld.References)
{
FixedDocument d = r.GetDocument(false);
// Walk through each page
foreach (PageContent pc in d.Pages)
{
FixedPage fixedPage = pc.GetPageRoot(false);
fixedPage.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(1, 1, 1, 1));
double width = fixedPage.Width;
double height = fixedPage.Height;
Size sz = new Size(width, height);
// Convert to WPF Visual
fixedPage.Measure(sz);
fixedPage.Arrange(new Rect(new Point(), sz));
fixedPage.UpdateLayout();
//将文档背景设置为透明色
ContainerVisual newpage = new ContainerVisual();
newpage.Children.Add(fixedPage);
newpage.Children.Add(CreateWatermark(width, height, "Confidential (" + pageno + ")"));
pageno++;
// Write out modified page
vxpsd.Write(newpage);
}
}
vxpsd.EndBatchWrite();
container.Close();
xpsOld.Close();
}
Visual CreateWatermark(double width, double height, string message)
{
DrawingVisual watermark = new DrawingVisual();
using (DrawingContext ctx = watermark.RenderOpen())
{
FormattedText text = new FormattedText(message,
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Times New Roman"), 96 * 1.5,
new SolidColorBrush(Color.FromScRgb(0.3f, 1f, 0f, 0f))
);
// Rotate transform, keep center
{
double diag = Math.Sqrt(width * width + height * height);
double cX = width / 2;
double cY = height / 2;
double sin = height / diag;
double cos = width / diag;
double dx = (cX * (1.0 - cos)) + (cY * sin);
double dy = (cY * (1.0 - cos)) - (cX * sin);
Transform mat = new MatrixTransform(cos, sin, -sin, cos, dx, dy);
ctx.PushTransform(mat);
}
// Centerlize
double x = (width - text.Width) / 2;
double y = (height - text.Height) / 2;
ctx.DrawText(text, new Point(x, y));
ctx.Pop();
}
return watermark;
}