示例#1
0
文件: Paragraph.cs 项目: kozanid/DocX
        /// <summary>
        /// Insert a field of type document property, this field will display the custom property cp, at the end of this paragraph.
        /// </summary>
        /// <param name="cp">The custom property to display.</param>
        /// <param name="f">The formatting to use for this text.</param>
        /// <example>
        /// Create, add and display a custom property in a document.
        /// <code>
        /// // Load a document
        /// using (DocX document = DocX.Create(@"Test.docx"))
        /// {
        ///     // Create a custom property.
        ///     CustomProperty name = new CustomProperty("name", "Cathal Coffey");
        ///        
        ///     // Add this custom property to this document.
        ///     document.AddCustomProperty(name);
        ///
        ///     // Create a text formatting.
        ///     Formatting f = new Formatting();
        ///     f.Bold = true;
        ///     f.Size = 14;
        ///     f.StrikeThrough = StrickThrough.strike;
        ///
        ///     // Insert a new paragraph.
        ///     Paragraph p = document.InsertParagraph("Author: ", false, f);
        ///
        ///     // Insert a field of type document property to display the custom property name and track this change.
        ///     p.InsertDocProperty(name, true, f);
        ///
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// }// Release this document from memory.
        /// </code>
        /// </example>
        public DocProperty InsertDocProperty(CustomProperty cp, bool trackChanges = false, Formatting f = null)
        {
            XElement f_xml = null;
            if (f != null)
                f_xml = f.Xml;

            XElement e = new XElement
            (
                XName.Get("fldSimple", DocX.w.NamespaceName),
                new XAttribute(XName.Get("instr", DocX.w.NamespaceName), string.Format(@"DOCPROPERTY {0} \* MERGEFORMAT", cp.Name)),
                    new XElement(XName.Get("r", DocX.w.NamespaceName),
                        new XElement(XName.Get("t", DocX.w.NamespaceName), f_xml, cp.Value))
            );

            XElement xml = e;
            if (trackChanges)
            {
                DateTime now = DateTime.Now;
                DateTime insert_datetime = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Utc);
                e = CreateEdit(EditType.ins, insert_datetime, e);
            }

            Xml.Add(e);

            return new DocProperty(Document, xml);
        }
示例#2
0
        // Create an invoice template.
        private static DocX CreateInvoiceTemplate()
        {
            // Create a new document.
            DocX document = DocX.Create(@"docs\InvoiceTemplate.docx");

            // Create a table for layout purposes (This table will be invisible).
            Table layout_table = document.InsertTable(2, 2);
            layout_table.Design = TableDesign.TableNormal;
            layout_table.AutoFit = AutoFit.Window;

            // Dark formatting
            Formatting dark_formatting = new Formatting();
            dark_formatting.Bold = true;
            dark_formatting.Size = 12;
            dark_formatting.FontColor = Color.FromArgb(31, 73, 125);

            // Light formatting
            Formatting light_formatting = new Formatting();
            light_formatting.Italic = true;
            light_formatting.Size = 11;
            light_formatting.FontColor = Color.FromArgb(79, 129, 189);

            #region Company Name
            // Get the upper left Paragraph in the layout_table.
            Paragraph upper_left_paragraph = layout_table.Rows[0].Cells[0].Paragraphs[0];

            // Create a custom property called company_name
            CustomProperty company_name = new CustomProperty("company_name", "Company Name");

            // Insert a field of type doc property (This will display the custom property 'company_name')
            layout_table.Rows[0].Cells[0].Paragraphs[0].InsertDocProperty(company_name, f: dark_formatting);

            // Force the next text insert to be on a new line.
            upper_left_paragraph.InsertText("\n", false);
            #endregion

            #region Company Slogan
            // Create a custom property called company_slogan
            CustomProperty company_slogan = new CustomProperty("company_slogan", "Company slogan goes here.");

            // Insert a field of type doc property (This will display the custom property 'company_slogan')
            upper_left_paragraph.InsertDocProperty(company_slogan, f: light_formatting);
            #endregion

            #region Company Logo
            // Get the upper right Paragraph in the layout_table.
            Paragraph upper_right_paragraph = layout_table.Rows[0].Cells[1].Paragraphs[0];

            // Add a template logo image to this document.
            RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
            rd.Up(2);
            Image logo = document.AddImage(rd.Path + @"\images\logo_template.png");

            // Insert this template logo into the upper right Paragraph.
            upper_right_paragraph.InsertPicture(logo.CreatePicture());

            upper_right_paragraph.Alignment = Alignment.right;
            #endregion

            // Custom properties cannot contain newlines, so the company address must be split into 3 custom properties.
            #region Hired Company Address
            // Create a custom property called company_address_line_one
            CustomProperty hired_company_address_line_one = new CustomProperty("hired_company_address_line_one", "Street Address,");

            // Get the lower left Paragraph in the layout_table.
            Paragraph lower_left_paragraph = layout_table.Rows[1].Cells[0].Paragraphs[0];
            lower_left_paragraph.InsertText("TO:\n", false, dark_formatting);

            // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_one')
            lower_left_paragraph.InsertDocProperty(hired_company_address_line_one, f: light_formatting);

            // Force the next text insert to be on a new line.
            lower_left_paragraph.InsertText("\n", false);

            // Create a custom property called company_address_line_two
            CustomProperty hired_company_address_line_two = new CustomProperty("hired_company_address_line_two", "City,");

            // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_two')
            lower_left_paragraph.InsertDocProperty(hired_company_address_line_two, f: light_formatting);

            // Force the next text insert to be on a new line.
            lower_left_paragraph.InsertText("\n", false);

            // Create a custom property called company_address_line_two
            CustomProperty hired_company_address_line_three = new CustomProperty("hired_company_address_line_three", "Zip Code");

            // Insert a field of type doc property (This will display the custom property 'hired_company_address_line_three')
            lower_left_paragraph.InsertDocProperty(hired_company_address_line_three, f: light_formatting);
            #endregion

            #region Date & Invoice number
            // Get the lower right Paragraph from the layout table.
            Paragraph lower_right_paragraph = layout_table.Rows[1].Cells[1].Paragraphs[0];

            CustomProperty invoice_date = new CustomProperty("invoice_date", DateTime.Today.Date.ToString("d"));
            lower_right_paragraph.InsertText("Date: ", false, dark_formatting);
            lower_right_paragraph.InsertDocProperty(invoice_date, f: light_formatting);

            CustomProperty invoice_number = new CustomProperty("invoice_number", 1);
            lower_right_paragraph.InsertText("\nInvoice: ", false, dark_formatting);
            lower_right_paragraph.InsertText("#", false, light_formatting);
            lower_right_paragraph.InsertDocProperty(invoice_number, f: light_formatting);

            lower_right_paragraph.Alignment = Alignment.right;
            #endregion

            // Insert an empty Paragraph between two Tables, so that they do not touch.
            document.InsertParagraph(string.Empty, false);

            // This table will hold all of the invoice data.
            Table invoice_table = document.InsertTable(4, 4);
            invoice_table.Design = TableDesign.LightShadingAccent1;
            invoice_table.Alignment = Alignment.center;

            // A nice thank you Paragraph.
            Paragraph thankyou = document.InsertParagraph("\nThank you for your business, we hope to work with you again soon.", false, dark_formatting);
            thankyou.Alignment = Alignment.center;

            #region Hired company details
            CustomProperty hired_company_details_line_one = new CustomProperty("hired_company_details_line_one", "Street Address, City, ZIP Code");
            CustomProperty hired_company_details_line_two = new CustomProperty("hired_company_details_line_two", "Phone: 000-000-0000, Fax: 000-000-0000, e-mail: [email protected]");

            Paragraph companyDetails = document.InsertParagraph(string.Empty, false);
            companyDetails.InsertDocProperty(hired_company_details_line_one, f: light_formatting);
            companyDetails.InsertText("\n", false);
            companyDetails.InsertDocProperty(hired_company_details_line_two, f: light_formatting);
            companyDetails.Alignment = Alignment.center;
            #endregion

            // Return the document now that it has been created.
            return document;
        }
示例#3
0
文件: Paragraph.cs 项目: kozanid/DocX
 /// <summary>
 /// Append a field of type document property, this field will display the custom property cp, at the end of this paragraph.
 /// </summary>
 /// <param name="cp">The custom property to display.</param>
 /// <param name="f">The formatting to use for this text.</param>
 /// <example>
 /// Create, add and display a custom property in a document.
 /// <code>
 ///// Load a document.
 ///using (DocX document = DocX.Create("CustomProperty_Add.docx"))
 ///{
 ///    // Add a few Custom Properties to this document.
 ///    document.AddCustomProperty(new CustomProperty("fname", "cathal"));
 ///    document.AddCustomProperty(new CustomProperty("age", 24));
 ///    document.AddCustomProperty(new CustomProperty("male", true));
 ///    document.AddCustomProperty(new CustomProperty("newyear2012", new DateTime(2012, 1, 1)));
 ///    document.AddCustomProperty(new CustomProperty("fav_num", 3.141592));
 ///
 ///    // Insert a new Paragraph and append a load of DocProperties.
 ///    Paragraph p = document.InsertParagraph("fname: ")
 ///        .AppendDocProperty(document.CustomProperties["fname"])
 ///        .Append(", age: ")
 ///        .AppendDocProperty(document.CustomProperties["age"])
 ///        .Append(", male: ")
 ///        .AppendDocProperty(document.CustomProperties["male"])
 ///        .Append(", newyear2012: ")
 ///        .AppendDocProperty(document.CustomProperties["newyear2012"])
 ///        .Append(", fav_num: ")
 ///        .AppendDocProperty(document.CustomProperties["fav_num"]);
 ///    
 ///    // Save the changes to the document.
 ///    document.Save();
 ///}
 /// </code>
 /// </example>
 public Paragraph AppendDocProperty(CustomProperty cp, bool trackChanges = false, Formatting f = null)
 {
     this.InsertDocProperty(cp, trackChanges, f);
     return this;
 }
示例#4
0
文件: DocX.cs 项目: EnergonV/BestCS
        /// <summary>
        /// Add a custom property to this document. If a custom property already exists with the same name it will be replace. CustomProperty names are case insensitive.
        /// </summary>
        /// <param name="cp">The CustomProperty to add to this document.</param>
        /// <example>
        /// Add a custom properties of each type to a document.
        /// <code>
        /// // Load Example.docx
        /// using (DocX document = DocX.Load(@"C:\Example\Test.docx"))
        /// {
        ///     // A CustomProperty called forename which stores a string.
        ///     CustomProperty forename;
        ///
        ///     // If this document does not contain a custom property called 'forename', create one.
        ///     if (!document.CustomProperties.ContainsKey("forename"))
        ///     {
        ///         // Create a new custom property called 'forename' and set its value.
        ///         document.AddCustomProperty(new CustomProperty("forename", "Cathal"));
        ///     }
        ///
        ///     // Get this documents custom property called 'forename'.
        ///     forename = document.CustomProperties["forename"];
        ///
        ///     // Print all of the information about this CustomProperty to Console.
        ///     Console.WriteLine(string.Format("Name: '{0}', Value: '{1}'\nPress any key...", forename.Name, forename.Value));
        ///     
        ///     // Save all changes made to this document.
        ///     document.Save();
        /// } // Release this document from memory.
        ///
        /// // Wait for the user to press a key before exiting.
        /// Console.ReadKey();
        /// </code>
        /// </example>
        /// <seealso cref="CustomProperty"/>
        /// <seealso cref="CustomProperties"/>
        public void AddCustomProperty(CustomProperty cp)
        {
            // If this document does not contain a customFilePropertyPart create one.
            if (!package.PartExists(new Uri("/docProps/custom.xml", UriKind.Relative)))
                HelperFunctions.CreateCustomPropertiesPart(this);

            XDocument customPropDoc;
            PackagePart customPropPart = package.GetPart(new Uri("/docProps/custom.xml", UriKind.Relative));
            using (TextReader tr = new StreamReader(customPropPart.GetStream(FileMode.Open, FileAccess.Read)))
                customPropDoc = XDocument.Load(tr, LoadOptions.PreserveWhitespace);

            // Each custom property has a PID, get the highest PID in this document.
            IEnumerable<int> pids =
            (
                from d in customPropDoc.Descendants()
                where d.Name.LocalName == "property"
                select int.Parse(d.Attribute(XName.Get("pid")).Value)
            );

            int pid = 1;
            if (pids.Count() > 0)
                pid = pids.Max();

            // Check if a custom property already exists with this name
            // 2013-05-25: IgnoreCase while searching for custom property as it would produce a currupted docx.
            var customProperty =
            (
                from d in customPropDoc.Descendants()
                where (d.Name.LocalName == "property") && (d.Attribute(XName.Get("name")).Value.Equals(cp.Name, StringComparison.InvariantCultureIgnoreCase))
                select d
            ).SingleOrDefault();

            // If a custom property with this name already exists remove it.
            if (customProperty != null)
                customProperty.Remove();

            XElement propertiesElement = customPropDoc.Element(XName.Get("Properties", customPropertiesSchema.NamespaceName));
            propertiesElement.Add
            (
                new XElement
                (
                    XName.Get("property", customPropertiesSchema.NamespaceName),
                    new XAttribute("fmtid", "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}"),
                    new XAttribute("pid", pid + 1),
                    new XAttribute("name", cp.Name),
                        new XElement(customVTypesSchema + cp.Type, cp.Value ?? "")
                )
            );

            // Save the custom properties
            using (TextWriter tw = new StreamWriter(customPropPart.GetStream(FileMode.Create, FileAccess.Write)))
                customPropDoc.Save(tw, SaveOptions.None);

            // Refresh all fields in this document which display this custom property.
            UpdateCustomPropertyValue(this, cp.Name, (cp.Value ?? "").ToString()); 
        }