Borders can make the associative perception of a table stronger, but sometimes, especially in PowerPoint, you may want to remove them in order to achieve a better visual effect. In this part, we're going to introduce how to set and remove border of an existing table in PowerPoint by using Spire.Presentation for .NET.

Before start, please download and install Spire.Presentation correctly, after that add the Spire.Presentation.dll file as the reference of your project.

Detail steps overview:

Set table border:

Step 1: Create a new presentation instance and load the sample document from file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("testTable.pptx");

Step 2: Find the table by looping through all the slides, and then set borders for it. Users can set different border styles according to their requirements.

foreach (ISlide slide in presentation.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        if (shape is ITable)
        {
            foreach (TableRow row in (shape as ITable).TableRows)
            {
                foreach (Cell cell in row)
                {
                    cell.BorderTop.FillType = FillFormatType.Solid;
                    cell.BorderBottom.FillType = FillFormatType.Solid;
                    cell.BorderLeft.FillType = FillFormatType.Solid;
                    cell.BorderRight.FillType = FillFormatType.Solid;
                }
            }
        }
    }
}

Step 3: Save the file as Border.pptx.

presentation.SaveToFile("Border.pptx", FileFormat.Pptx2010);

Remove table border:

Remove table border is very simple, refer to the following codes:

cell.BorderTop.FillType = FillFormatType.None;
cell.BorderBottom.FillType = FillFormatType.None;
cell.BorderLeft.FillType = FillFormatType.None;
cell.BorderRight.FillType = FillFormatType.None;

Effective screenshots:

Before:

How to Set and Remove Table Border in PowerPoint

After:

How to Set and Remove Table Border in PowerPoint

Full codes:

using Spire.Presentation;
using Spire.Presentation.Drawing;

namespace Set_and_Remove_Table_Border_in_PPT
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.LoadFromFile("testTable.pptx");
            foreach (ISlide slide in presentation.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape is ITable)
                    {
                        foreach (TableRow row in (shape as ITable).TableRows)
                        {
                            foreach (Cell cell in row)
                            {
                                //Add top border and set its FillType as Solid.
                                cell.BorderTop.FillType = FillFormatType.Solid;
                                //Remove top border
                                //cell.BorderTop.FillType = FillFormatType.None;

                                cell.BorderBottom.FillType = FillFormatType.Solid;
                                //cell.BorderBottom.FillType = FillFormatType.None;

                                cell.BorderLeft.FillType = FillFormatType.Solid;
                                //cell.BorderLeft.FillType = FillFormatType.None;

                                cell.BorderRight.FillType = FillFormatType.Solid;
                                //cell.BorderRight.FillType = FillFormatType.None;
                            }
                        }
                    }
                }
            }
            presentation.SaveToFile("Border.pptx", FileFormat.Pptx2010);
        }
    }
}

How to Convert Word to PDF in WPF

2016-01-15 03:31:19 Written by Koohji

PDF and Word are the two most commonly used files in our daily life, however, sometimes we need to do conversion between them due to their own advantages, disadvantages or our different requirements. Spire.Doc for WPF as a professional word component enables developers to convert Word to PDF easily by invoking the document.SaveToFile() method.

This is the screenshot of the original word document:

How to Convert Word to PDF in WPF

Now follow the steps below:

First, please download and install Spire.Doc correctly, then create a WPF application project and add the Spire.Doc.Wpf.dll as the reference of your project.

Second, drag a button to the MainWindow, double click the button to add following codes to convert Word to PDF.

[C#]
//Load document
Document document = new Document();
document.LoadFromFile("sample.docx");

//convert to PDF
document.SaveToFile("toPDF.PDF",FileFormat.PDF);

//Launch the file
System.Diagnostics.Process.Start("toPDF.PDF");
[VB.NET]
'Load document
Dim document As New Document()
document.LoadFromFile("sample.docx")

'convert to PDF            
document.SaveToFile("toPDF.PDF",FileFormat.PDF)

'Launch the file            
System.Diagnostics.Process.Start("toPDF.PDF")

Effective screenshot:

How to Convert Word to PDF in WPF

With the help of Spire.Doc for WPF, developers can create and edit word documents easily and flexibly for their WPF applications. Sometimes developers need to protect their word documents for being read and edit by others. They may need to add password for the word files to protect them confidential. Then others have to enter the password to open the view the encrypted word documents. Spire.Doc for WPF offers a method of Document.Encrypt(); to enable developers to set the password for word documents and Document.RemoveEncryption(); to remove the encryption for word documents.

This article will demonstrate how to encrypt and word documents with password and decrypt the word documents in C# for WPF applications.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc.Wpf.dll in the bin folder as the reference of Visual Studio.

Here comes to the code snippets:

Step 1: Create a new word document and load the document from file.

Document document = new Document();
document.LoadFromFile("Sample.docx");

Step 2: Encrypt the document with password.

document.Encrypt("eiceblue");

Step 3: Save the encrypted document to file.

document.SaveToFile("Encryption.docx", FileFormat.Docx);

Step 4: Create a second new word document and load the encrypted document from file with the password.

Document document2 = new Document();
document2.LoadFromFile("Encryption.docx",FileFormat.Docx,"eiceblue");

Step 5: Decrypted the word document.

document2.RemoveEncryption();

Step 6: Save the decrypted document to file.

document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

Please check the effective screenshots of the encrypted word document and the decrypted word documents as below:

Encrypted document with password:

Encrypt and decrypt word document for WPF applications

Decrypted word document:

Encrypt and decrypt word document for WPF applications

Full codes:

using Spire.Doc;
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Document document = new Document();
            document.LoadFromFile("Sample.docx");

            document.Encrypt("eiceblue");

            document.SaveToFile("Encryption.docx", FileFormat.Docx);

            Document document2 = new Document();
            document2.LoadFromFile("Encryption.docx", FileFormat.Docx, "eiceblue");
            document2.RemoveEncryption();

            document2.SaveToFile("Decrytion.docx", FileFormat.Docx);

        }
    }
}

class Program
    {
        static void Main(string[] args)
        {
            const string fileName = "SetCustomProperty.docx";
            Console.WriteLine("Manager = " +
                SetCustomProperty(fileName, "Manager", "Peter", PropertyTypes.Text));
            Console.WriteLine("ReviewDate = " +
                SetCustomProperty(fileName, "ReviewDate",
                DateTime.Parse("12/21/2010"), PropertyTypes.DateTime));
        }
        public enum PropertyTypes : int
        {
            YesNo,
            Text,
            DateTime,
            NumberInteger,
            NumberDouble
        }

        public static string SetCustomProperty(
            string fileName,
            string propertyName,
            object propertyValue,
            PropertyTypes propertyType)
        {
            // Given a document name, a property name/value, and the property type, 
            // add a custom property to a document. The method returns the original
            // value, if it existed.

            string returnValue = null;

            var newProp = new CustomDocumentProperty();
            bool propSet = false;

            // Calculate the correct type.
            switch (propertyType)
            {
                case PropertyTypes.DateTime:

                    // Be sure you were passed a real date, 
                    // and if so, format in the correct way. 
                    // The date/time value passed in should 
                    // represent a UTC date/time.
                    if ((propertyValue) is DateTime)
                    {
                        newProp.VTFileTime =
                            new VTFileTime(string.Format("{0:s}Z",
                                Convert.ToDateTime(propertyValue)));
                        propSet = true;
                    }

                    break;

                case PropertyTypes.NumberInteger:
                    if ((propertyValue) is int)
                    {
                        newProp.VTInt32 = new VTInt32(propertyValue.ToString());
                        propSet = true;
                    }

                    break;

                case PropertyTypes.NumberDouble:
                    if (propertyValue is double)
                    {
                        newProp.VTFloat = new VTFloat(propertyValue.ToString());
                        propSet = true;
                    }

                    break;

                case PropertyTypes.Text:
                    newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString());
                    propSet = true;

                    break;

                case PropertyTypes.YesNo:
                    if (propertyValue is bool)
                    {
                        // Must be lowercase.
                        newProp.VTBool = new VTBool(
                          Convert.ToBoolean(propertyValue).ToString().ToLower());
                        propSet = true;
                    }
                    break;
            }

            if (!propSet)
            {
                // If the code was not able to convert the 
                // property to a valid value, throw an exception.
                throw new InvalidDataException("propertyValue");
            }

            // Now that you have handled the parameters, start
            // working on the document.
            newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
            newProp.Name = propertyName;

            using (var document = WordprocessingDocument.Open(fileName, true))
            {
                var customProps = document.CustomFilePropertiesPart;
                if (customProps == null)
                {
                    // No custom properties? Add the part, and the
                    // collection of properties now.
                    customProps = document.AddCustomFilePropertiesPart();
                    customProps.Properties =
                        new DocumentFormat.OpenXml.CustomProperties.Properties();
                }

                var props = customProps.Properties;
                if (props != null)
                {
                    // This will trigger an exception if the property's Name 
                    // property is null, but if that happens, the property is damaged, 
                    // and probably should raise an exception.
                    var prop =
                        props.Where(
                        p => ((CustomDocumentProperty)p).Name.Value
                            == propertyName).FirstOrDefault();

                    // Does the property exist? If so, get the return value, 
                    // and then delete the property.
                    if (prop != null)
                    {
                        returnValue = prop.InnerText;
                        prop.Remove();
                    }

                    // Append the new property, and 
                    // fix up all the property ID values. 
                    // The PropertyId value must start at 2.
                    props.AppendChild(newProp);
                    int pid = 2;
                    foreach (CustomDocumentProperty item in props)
                    {
                        item.PropertyId = pid++;
                    }
                    props.Save();
                }
            }
            return returnValue;
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            string fileName = "OpenXML.docx";
            GetCommentsFromDocument(fileName);
        }
        public static void GetCommentsFromDocument(string fileName)
        {
            using (WordprocessingDocument wordDoc =
                WordprocessingDocument.Open(fileName, false))
            {
                WordprocessingCommentsPart commentsPart =
                    wordDoc.MainDocumentPart.WordprocessingCommentsPart;

                if (commentsPart != null && commentsPart.Comments != null)
                {
                    foreach (Comment comment in commentsPart.Comments.Elements())
                    {
                        Console.WriteLine(comment.InnerText);
                        
                    }
                }
            }
            Console.ReadLine();
        }
    }

How to Remove the headers and footers

2016-01-13 07:57:02 Written by Koohji

class Program
    {
        static void Main(string[] args)
        {
            RemoveHeadersAndFooters("HeadersAndFooters.docx");
        }
        // Remove all of the headers and footers from a document.
        public static void RemoveHeadersAndFooters(string filename)
        {
            // Given a document name, remove all of the headers and footers
            // from the document.
            using (WordprocessingDocument doc =
                WordprocessingDocument.Open(filename, true))
            {
                // Get a reference to the main document part.
                var docPart = doc.MainDocumentPart;

                // Count the header and footer parts and continue if there 
                // are any.
                if (docPart.HeaderParts.Count() > 0 ||
                    docPart.FooterParts.Count() > 0)
                {
                    // Remove the header and footer parts.
                    docPart.DeleteParts(docPart.HeaderParts);
                    docPart.DeleteParts(docPart.FooterParts);

                    // Get a reference to the root element of the main
                    // document part.
                    Document document = docPart.Document;

                    // Remove all references to the headers and footers.

                    // First, create a list of all descendants of type
                    // HeaderReference. Then, navigate the list and call
                    // Remove on each item to delete the reference.
                    var headers =
                      document.Descendants().ToList();
                    foreach (var header in headers)
                    {
                        header.Remove();
                    }

                    // First, create a list of all descendants of type
                    // FooterReference. Then, navigate the list and call
                    // Remove on each item to delete the reference.
                    var footers =
                      document.Descendants().ToList();
                    foreach (var footer in footers)
                    {
                        footer.Remove();
                    }

                    // Save the changes.
                    document.Save();
                }
            }
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            string document = "Word9.docx";
            string fileName = "test.jpg";
            InsertAPicture(document, fileName);
        }
        public static void InsertAPicture(string document, string fileName)
        {
            using (WordprocessingDocument wordprocessingDocument =WordprocessingDocument.Open(document, true))
            {
                MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

                ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

                using (FileStream stream = new FileStream(fileName, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }

                AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
            }
        }

        private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
        {
            // Define the reference of the image.
            var element =
                 new Drawing(
                     new DW.Inline(
                         new DW.Extent() { Cx = 990000L, Cy = 792000L },
                         new DW.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new DW.DocProperties()
                         {
                             Id = (UInt32Value)1U,
                             Name = "Picture 1"
                         },
                         new DW.NonVisualGraphicFrameDrawingProperties(
                             new A.GraphicFrameLocks() { NoChangeAspect = true }),
                         new A.Graphic(
                             new A.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = "New Bitmap Image.jpg"
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new A.Blip(
                                             new A.BlipExtensionList(
                                                 new A.BlipExtension()
                                                 {
                                                     Uri =
                                                        "{28A0092B-C50C-407E-A947-70E740481C1C}"
                                                 })
                                         )
                                         {
                                             Embed = relationshipId,
                                             CompressionState =
                                             A.BlipCompressionValues.Print
                                         },
                                         new A.Stretch(
                                             new A.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new A.Transform2D(
                                             new A.Offset() { X = 0L, Y = 0L },
                                             new A.Extents() { Cx = 990000L, Cy = 792000L }),
                                         new A.PresetGeometry(
                                             new A.AdjustValueList()
                                         )
                                         { Preset = A.ShapeTypeValues.Rectangle }))
                             )
                             { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     )
                     {
                         DistanceFromTop = (UInt32Value)0U,
                         DistanceFromBottom = (UInt32Value)0U,
                         DistanceFromLeft = (UInt32Value)0U,
                         DistanceFromRight = (UInt32Value)0U,
                         EditId = "50D07946"
                     });

            // Append the reference to body, the element should be in a Run.
            wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            AddCommentOnFirstParagraph("Word8.docx","Open", "test", "This is my comment.");
        }
        // Insert a comment on the first paragraph.
        public static void AddCommentOnFirstParagraph(string fileName,
            string author, string initials, string comment)
        {
            // Use the file name and path passed in as an 
            // argument to open an existing Wordprocessing document. 
            using (WordprocessingDocument document =WordprocessingDocument.Open(fileName, true))
            {
                // Locate the first paragraph in the document.
                Paragraph firstParagraph =
                    document.MainDocumentPart.Document.Descendants().First();
                Comments comments = null;
                string id = "0";

                // Verify that the document contains a 
                // WordProcessingCommentsPart part; if not, add a new one.
                if (document.MainDocumentPart.GetPartsCountOfType() > 0)
                {
                    comments =
                        document.MainDocumentPart.WordprocessingCommentsPart.Comments;
                    if (comments.HasChildren)
                    {
                        // Obtain an unused ID.
                        id = comments.Descendants().Select(e => e.Id.Value).Max();
                    }
                }
                else
                {
                    // No WordprocessingCommentsPart part exists, so add one to the package.
                    WordprocessingCommentsPart commentPart =
                        document.MainDocumentPart.AddNewPart();
                    commentPart.Comments = new Comments();
                    comments = commentPart.Comments;
                }

                // Compose a new Comment and add it to the Comments part.
                Paragraph p = new Paragraph(new Run(new Text(comment)));
                Comment cmt =
                    new Comment()
                    {
                        Id = id,
                        Author = author,
                        Initials = initials,
                        Date = DateTime.Now
                    };
                cmt.AppendChild(p);
                comments.AppendChild(cmt);
                comments.Save();

                // Specify the text range for the Comment. 
                // Insert the new CommentRangeStart before the first run of paragraph.
                firstParagraph.InsertBefore(new CommentRangeStart()
                { Id = id }, firstParagraph.GetFirstChild());

                // Insert the new CommentRangeEnd after last run of paragraph.
                var cmtEnd = firstParagraph.InsertAfter(new CommentRangeEnd()
                { Id = id }, firstParagraph.Elements().Last());

                // Compose a run with CommentReference and insert it.
                firstParagraph.InsertAfter(new Run(new CommentReference() { Id = id }), cmtEnd);
            }
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            DeleteComments("DeleteComments.docx","Gary zhang");

        }
        public static void DeleteComments(string fileName, string author = "")
        {
            // Get an existing Wordprocessing document.
            using (WordprocessingDocument document =
                WordprocessingDocument.Open(fileName, true))
            {
                // Set commentPart to the document WordprocessingCommentsPart, 
                // if it exists.
                WordprocessingCommentsPart commentPart =
                    document.MainDocumentPart.WordprocessingCommentsPart;

                // If no WordprocessingCommentsPart exists, there can be no 
                // comments. Stop execution and return from the method.
                if (commentPart == null)
                {
                    return;
                }

                // Create a list of comments by the specified author, or
                // if the author name is empty, all authors.
                List commentsToDelete =
                    commentPart.Comments.Elements().ToList();
                if (!String.IsNullOrEmpty(author))
                {
                    commentsToDelete = commentsToDelete.
                    Where(c => c.Author == author).ToList();
                }
                IEnumerable commentIds =
                    commentsToDelete.Select(r => r.Id.Value);

                // Delete each comment in commentToDelete from the 
                // Comments collection.
                foreach (Comment c in commentsToDelete)
                {
                    c.Remove();
                }

                // Save the comment part change.
                commentPart.Comments.Save();

                Document doc = document.MainDocumentPart.Document;

                // Delete CommentRangeStart for each
                // deleted comment in the main document.
                List commentRangeStartToDelete =
                    doc.Descendants().
                    Where(c => commentIds.Contains(c.Id.Value)).ToList();
                foreach (CommentRangeStart c in commentRangeStartToDelete)
                {
                    c.Remove();
                }

                // Delete CommentRangeEnd for each deleted comment in the main document.
                List commentRangeEndToDelete =
                    doc.Descendants().
                    Where(c => commentIds.Contains(c.Id.Value)).ToList();
                foreach (CommentRangeEnd c in commentRangeEndToDelete)
                {
                    c.Remove();
                }

                // Delete CommentReference for each deleted comment in the main document.
                List commentRangeReferenceToDelete =
                    doc.Descendants().
                    Where(c => commentIds.Contains(c.Id.Value)).ToList();
                foreach (CommentReference c in commentRangeReferenceToDelete)
                {
                    c.Remove();
                }

                // Save changes back to the MainDocumentPart part.
                doc.Save();
            }
        }

    }

class Program
    {
        static void Main(string[] args)
        {
            string filename = "WithMacros.docm";
            ConvertDOCMtoDOCX(filename);
        }
        // Given a .docm file (with macro storage), remove the VBA 
        // project, reset the document type, and save the document with a new name.
        public static void ConvertDOCMtoDOCX(string fileName)
        {
            bool fileChanged = false;

            using (WordprocessingDocument document =
                WordprocessingDocument.Open(fileName, true))
            {
                // Access the main document part.
                var docPart = document.MainDocumentPart;

                // Look for the vbaProject part. If it is there, delete it.
                var vbaPart = docPart.VbaProjectPart;
                if (vbaPart != null)
                {
                    // Delete the vbaProject part and then save the document.
                    docPart.DeletePart(vbaPart);
                    docPart.Document.Save();

                    // Change the document type to
                    // not macro-enabled.
                    document.ChangeDocumentType(
                        WordprocessingDocumentType.Document);

                    // Track that the document has been changed.
                    fileChanged = true;
                }
            }

            // If anything goes wrong in this file handling,
            // the code will raise an exception back to the caller.
            if (fileChanged)
            {
                // Create the new .docx filename.
                var newFileName = Path.ChangeExtension(fileName, ".docx");

                // If it already exists, it will be deleted!
                if (File.Exists(newFileName))
                {
                    File.Delete(newFileName);
                }

                // Rename the file.
                File.Move(fileName, newFileName);
            }
        }
    }

page 44