OpenXML Word docx add watermark PowerTools

Source: Internet
Author: User
/* Microshaoft this article code changed from http://powertools.codeplex.com/http://powertools.codeplex.com/releases/view/74771#DownloadId=291022 text watermark, transparency, rotation use this article code to replace Classes \ WatermarkAccessor. the Code Classes directory in the cs file contains the following 34 files: Classes \ BackgroundAccessor. cs Classes \ ChartsheetAccessor. cs Classes \ CommentAccessor. cs Classes \ CommentMerger. cs Classes \ ContentFormatAccessor. cs Classes \ ContentStyleAccessor. cs Classes \ CustomXmlAcc Essor. cs Classes \ DigitalSignatureAccessor. cs Classes \ DocumentBuilder. cs Classes \ DocumentComparer. cs Classes \ FooterAccessor. cs Classes \ HeaderAccessor. cs Classes \ HtmlConverter. cs Classes \ IndexAccessor. cs Classes \ ListItemRetriever. cs Classes \ MarkupSimplifier. cs Classes \ PictureAccessor. cs Classes \ PowerToolsExtensions. cs Classes \ PtOpenXmlDocument. cs Classes \ PtOpenXmlUtil. cs Classes \ PtUtil. cs Classes \ Re FerenceAdder. cs Classes \ RevisionAccepter. cs Classes \ SettingAccessor. cs Classes \ SpreadsheetDocumentManager. cs Classes \ SpreadSheetStyleAccessor. cs Classes \ SpreadSheetTableAccessor. cs Classes \ StyleAccessor. cs Classes \ TextReplacer. cs Classes \ ThemeAccessor. cs Classes \ WatermarkAccessor. cs Classes \ WordprocessingDocumentManager. cs Classes \ WorksheetAccessor. cs % windir % \ Microsoft. NET \ Framework \ v4.0.30319 \ cs C.exe/out: OpenXmlWordAddWaterMark.exe *. cs/r: "C: \ Program Files (x86) \ Reference Assemblies \ Microsoft \ Framework \ v3.0 \ WindowsBase. dll "," C: \ Program Files (x86) \ Open xml sdk \ V2.0 \ lib \ DocumentFormat. openXml. dll "*/namespace Microshaoft {using System; using System. collections. generic; using System. IO; using System. linq; using System. text; using OpenXmlPowerTools; class Class1 {static void Main (string [] Args) {// "position: absolute; margin-left: 0; margin-top: 0; width: 527.85pt; height: 131.95pt; rotation: 315; z-index: -251656192; mso-position-horizontal: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-position-vertical-relative: margin "; wmlDocument wmlDoc = new WmlDocument (@ "d: \ a.docx"); OpenXmlPowerToolsDocument doc = WatermarkAccessor. insertWatermark (wmlDoc, "test 123 abcA BC @ Microshaoft ", 527,200,110," ", 10," red ", 10); doc. saveAs (@ "d: \ a1.docx ");}}} namespace OpenXmlPowerTools {/************************************ * *********************************** Copyright (c) microsoft Corporation 2011. this code is licensed using the Microsoft Public License (Ms-PL ). the text of the license can be found here: http://www.microsoft.com/resources/sharedsource/li Censingbasics/publicliclicense. mspx *************************************** * **********************************/using System. collections. generic; using System. collections. objectModel; using System. linq; using System. xml. linq; using DocumentFormat. openXml. packaging; using System. drawing; // <summary> // Provides access to watermark operations // </summary> public class WatermarkAccessor {private Static XNamespace ns; private static XNamespace officens; private static XNamespace vmlns; private static XNamespace relationshipsns; private static string diagonalWatermarkStyle = "position: absolute; margin-left: 0; margin-top: 0; width: 527.85pt; height: 131.95pt; rotation: 315; z-index:-251656192; mso-position-horizontal: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-positi On-vertical-relative: margin "; private static string fontFamilySizeStyle =" font-family: & quot; Calibri & quot; font-size: 1pt "; private static string fillColor = "black"; private static int opacity = 50; // private static string defaultWatermarkStyle = "position: absolute; margin-left: 0; margin-top: 0; width: 468pt; height: 117pt; z-index:-251652096; mso-position-horizontal: center; mso-position-horizontal-relative: Margin; mso-position-vertical: center; mso-position-vertical-relative: margin "; static WatermarkAccessor () {ns =" http://schemas.openxmlformats.org/wordprocessingml/2006/main "; officens =" urn: schemas-microsoft-com: office "; vmlns =" urn: schemas-microsoft-com: vml "; relationshipsns =" http://schemas.openxmlformats.org/officeDocument/2006/relationships ";} /// <summary> /// Inserts a watermark t Ext inside a document /// </summary> /// <param name = "watermarkText"> text to show in the watermark </param> /// <param name =" diagonalOrientation "> specify that the text orientation will be in a diagonal way </param> public static OpenXmlPowerToolsDocument InsertWatermark (WmlDocument doc, string watermarkText, int width, int height, int rotation, string fontFamilyName, int fontSize, string fi LlColor, int opacityPercent //, bool diagonalOrientation) {// "position: absolute; margin-left: 0; margin-top: 0; width: 527.85pt; height: 131.95pt; rotation: 315; z-index:-251656192; mso-position-horizontal: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-position-vertical-relative: margin "; diagonalWatermarkStyle = string. format (@ "position: absolute; margin-left: 0; margin-t Op: 0; width: {0} pt; height: {1} pt; rotation: {2}; z-index:-251656192; mso-position-horizontal: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-position-vertical-relative: margin ", width, height, rotation); fontFamilySizeStyle = string. format (@ "font-family: & quot; {0} & quot; font-size: {1} pt", fontFamilyName, fontSize); opacity = opacityPercent; // diagonalWat ErmarkStyle = "position: absolute; margin-left: 0; margin-top: 0; width: 527.85pt; height: 131.95pt; rotation: 315; z-indexes:-251656192; mso-position-horizontal: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-position-vertical-relative: margin "; // defaultWatermarkStyle = "position: absolute; margin-left: 0; margin-top: 0; width: 468pt; height: 117pt; z-index:-251652096; mso-position-horizont Al: center; mso-position-horizontal-relative: margin; mso-position-vertical: center; mso-position-vertical-relative: margin "; using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument (doc) {using (WordprocessingDocument document = streamDoc. getWordprocessingDocument () {Collection <XDocument> headers = new Collection <XDocument> (); if (HeaderAccessor. getHeaderReference (document, Hea DerType. first, 0) = null) headers. add (HeaderAccessor. addNewHeader (document, HeaderType. first); else headers. add (HeaderAccessor. getHeader (document, HeaderType. first, 0); if (HeaderAccessor. getHeaderReference (document, HeaderType. even, 0) = null) headers. add (HeaderAccessor. addNewHeader (document, HeaderType. even); else headers. add (HeaderAccessor. getHeader (document, HeaderType. even, 0); if (Head ErAccessor. getHeaderReference (document, HeaderType. default, 0) = null) headers. add (HeaderAccessor. addNewHeader (document, HeaderType. default); else headers. add (HeaderAccessor. getHeader (document, HeaderType. default, 0); foreach (XDocument header in headers) {var runElement = header. descendants (ns + "r "). firstOrDefault (); if (runElement = null) {header. root. add (new XElement (ns + "sdt", new XEl Ement (ns + "sdtContent", new XElement (ns + "p", new XElement (ns + "pPr", new XElement (ns + "pStyle ", new XAttribute (ns + "val", "Header"), runElement = new XElement (ns + "r");} runElement. addBeforeSelf (CreateWatermarkVml (watermarkText);} HeaderAccessor. getHeaderPart (document, HeaderType. first, 0 ). putXDocument (); HeaderAccessor. getHeaderPart (document, HeaderType. even, 0 ). putXDocument (); HeaderAccessor. getHeaderPart (document, HeaderType. default, 0 ). putXDocument ();} return streamDoc. getModifiedDocument ();}} /// <summary> /// Creates the markup for watermark displaying // </summary> /// <param name = "watermarkText"> Text to include in markup </ param> /// <param name = "diagonalOrientation"> Orientation of text </param> /// <returns> Watermark markup </returns> private static XElement CreateWatermarkVml (string watermarkText) {return new XElement (ns + "r", new XElement (ns + "pict", new XElement (vmlns + "shapetype ", new XAttribute ("id", "_ x0000_t136"), new XAttribute ("coordsize", "21600,21600"), new XAttribute (officens + "spt", "136 "), new XAttribute ("associate", "10800"), new XAttribute ("path", "m @ 7, l @ 8, m @ 5, 21600l @ 6, 21600e "), new XElement (vmlns + "formulas", new XElement (vmlns + "f", New XAttribute ("eqn", "sum #0 10800"), new XElement (vmlns + "f", new XAttribute ("eqn ", "prod #0 2 1"), new XElement (vmlns + "f", new XAttribute ("eqn", "sum 21600 0 @ 1 ")), new XElement (vmlns + "f", new XAttribute ("eqn", "sum 0 0 @ 2"), new XElement (vmlns + "f ", new XAttribute ("eqn", "sum 21600 0 @ 3"), new XElement (vmlns + "f", new XAttribute ("eqn ", "if @ 0 @ 3 0"), new XElement (vmlns + "F", new XAttribute ("eqn", "if @ 0 21600 @ 1"), new XElement (vmlns + "f", new XAttribute ("eqn ", "if @ 0 0 @ 2"), new XElement (vmlns + "f", new XAttribute ("eqn", "if @ 0 @ 4 21600 ")), new XElement (vmlns + "f", new XAttribute ("eqn", "mid @ 5 @ 6"), new XElement (vmlns + "f ", new XAttribute ("eqn", "mid @ 8 @ 5"), new XElement (vmlns + "f", new XAttribute ("eqn ", "mid @ 7 @ 8"), new XElement (vmlns + "f ", New XAttribute ("eqn", "mid @ 6 @ 7"), new XElement (vmlns + "f", new XAttribute ("eqn ", "sum @ 6 0 @ 5"), new XElement (vmlns + "path", new XAttribute ("textpathok", "t "), new XAttribute (officens + "connecttype", "custom"), new XAttribute (officens + "connectlocs "), new XAttribute (officens + "connectangles", "270,180, 90,0"), new XElement (vmlns + "textpath", new XAttribute ("on", "t"), new XAttribute ("fitshape", "t"), new XElement (vmlns + "handles ", new XElement (vmlns + "h", new XAttribute ("position", "#0, bottomRight"), new XAttribute ("xrange", "6629,14971 "))), new XElement (officens + "lock", new XAttribute (vmlns + "ext", "edit"), new XAttribute ("text", "t "), new XAttribute ("shapetype", "t"), new XElement (vmlns + "shape", new XAttribute ("id", "Pow" ErPlusWaterMarkObject98078923 "), new XAttribute (officens +" spid "," _ x0000_s2055 "), new XAttribute (" type "," # _ x0000_t136 "), // new XAttribute ("style", diagonalOrientation? DiagonalWatermarkStyle: defaultWatermarkStyle), new XAttribute ("style", diagonalWatermarkStyle), new XAttribute (officens + "allowincell", "f"), new XAttribute ("fillcolor", fillColor ), new XAttribute ("stroked", "f"), new XElement (vmlns + "fill", new XAttribute ("opacity", opacity/100.0 )), new XElement (vmlns + "textpath", new XAttribute ("style", fontFamilySizeStyle), new XAttribute ("string", waterm ArkText )))));} /// <summary> // Gets the text related to watermark from a document /// </summary> /// <returns> Watermark text </returns> public static string getWatermarkText (WmlDocument doc) {IEnumerable <XElement> watermarkDescription = GetWatermark (doc); if (watermarkDescription! = Null) return watermarkDescription. descendants (vmlns + "shape "). descendants (vmlns + "textpath "). first (). attribute ("string "). value; else return string. empty ;} /// <summary> // Gets the document structure related to watermark description /// </summary> /// <returns> Document structure related to watermark description </returns> public static IEnumerable <XElement> GetWatermark (WmlDocument doc) {Using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument (doc) using (WordprocessingDocument document = streamDoc. getWordprocessingDocument () {// to get the watermark text, we have to look inside the document // get the default header reference and get the header reference id part XElement defaultHeaderReference = HeaderAccessor. getHeaderReference (document, HeaderType. defa Ult, 0); if (defaultHeaderReference! = Null) {string headerReferenceId = defaultHeaderReference. Attribute (relationshipsns + "id"). Value; OpenXmlPart headerPart = document. MainDocumentPart. GetPartById (headerReferenceId); if (headerPart! = Null) {XDocument headerPartXml = headerPart. GetXDocument (); return headerPartXml. Descendants (ns + "pict") ;}} return null ;}}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.