Using Spire.XLS, the password of an encrypted workbook can be removed or modified in case you know the open password. This article presents how to load a password protected Excel workbook, remove the protection or reset the password and then save the changes to the original file.

Step 1: Initialize an instance of Workbook class.

Workbook wb = new Workbook();

Step 2: Specify the open password and then load the encrypted Excel file.

wb.OpenPassword = "oldpassword";
wb.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.xlsx");

Step 3: Remove the password protection with UnProtect() method or reset the password by Protect() method.

//unprotect workbook
wb.UnProtect();

//reset password
wb.Protect("newpassword");

Step 4: Save the changes to file.

wb.SaveToFile(@"C:\Users\Administrator\Desktop\Encrypted.xlsx, ExcelVersion.Version2010");

Full Code:

[C#]
Workbook wb = new Workbook();
wb.OpenPassword = "oldpassword";
wb.LoadFromFile(@"C:\Users\Administrator\Desktop\Encrypted.xlsx");

////unprotect workbook
//wb.UnProtect();

//reset password
wb.Protect("newpassword");
wb.SaveToFile(@"C:\Users\Administrator\Desktop\Encrypted.xlsx", ExcelVersion.Version2010);   
[VB.NET]
Dim wb As New Workbook()
wb.OpenPassword = "oldpassword"
wb.LoadFromFile("C:\Users\Administrator\Desktop\Encrypted.xlsx")

'''/unprotect workbook
'wb.UnProtect();

'reset password
wb.Protect("newpassword")
wb.SaveToFile("C:\Users\Administrator\Desktop\Encrypted.xlsx", ExcelVersion.Version2010)

We have already shown you how to set the Excel Properties in C# with the help of Spire.XLS. This article focuses introducing method to get Excel properties and custom properties on the Excel workbook in C#.

Here comes to the steps of how to get the Excel Properties even with custom properties:

Step 1: Initialize an instance of Workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Use workbook.DocumentProperties to get the general excel properties.

BuiltInDocumentProperties p = workbook.DocumentProperties;

How to Get Excel Properties and Custom Properties in C#

Step 3: Use CustomDocumentProperties property for workbook object to get the custom properties.

ICustomDocumentProperties properties = workbook.CustomDocumentProperties;

for (int i = 0; i < properties.Count; i++)
{
    string name = properties[i].Name;
    string value = properties[i].Text;

 }

How to Get Excel Properties and Custom Properties in C#

Full codes:

static void Main(string[] args)
 
{

     Workbook workbook = new Workbook();
     workbook.LoadFromFile("Sample.xlsx");

   
     BuiltInDocumentProperties p = workbook.DocumentProperties;               

     ICustomDocumentProperties properties = workbook.CustomDocumentProperties;
   
     for (int i = 0; i < properties.Count; i++)
     {
         string name = properties[i].Name;
         string value = properties[i].Text;

      }             
                      
 }

Spire.XLS provides a class named Workbook that represents an Excel workbook. This class contains a method named IsPasswordProtected(string fileName) which returns a boolean value. If the value is true, means the workbook is encrypted with password, otherwise it's not.

This is an Excel workbook protected with password:

Detect if an Excel Workbook is Password Protected in C#, VB.NET

Now refer below code to detect if the Excel workbook is password protected:

[C#]
using System;
using Spire.Xls;

namespace Detect_if_workbook_is_password_protected
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "E:\\Program Files\\Sample.xlsx";
            //Detect if the Excel workbook is password protected.
            bool value = Workbook.IsPasswordProtected(fileName);
            Console.WriteLine(value);
            Console.ReadKey();
        }
    }
}
[VB.NET]
Imports Spire.Xls

Namespace Detect_if_workbook_is_password_protected
	Class Program
		Private Shared Sub Main(args As String())
			Dim fileName As String = "E:\Program Files\Sample.xlsx"
			'Detect if the Excel workbook is password protected.
			Dim value As Boolean = Workbook.IsPasswordProtected(fileName)
			Console.WriteLine(value)
			Console.ReadKey()
		End Sub
	End Class
End Namespace

After running the project, we get the Output that shows the workbook is password protected:

Detect if an Excel Workbook is Password Protected in C#, VB.NET

Friday, 06 January 2017 05:48

How to Get the Titles of All Slides with C#

There can be many types of titles such as centered title, subtitle and title on PowerPoint slides. This article demonstrates how to get such titles from all the slides of a PowerPoint document by using Spire.Presentation and C#.

This is a PowerPoint document which contains a centered title and a subtitle on the first slide and a title on the second slide.

How to Get the Titles of All Slides with C#

Follow below steps to get the titles:

Step 1: Instantiate a Presentation object and load the PowerPoint document.

Presentation ppt = new Presentation();
ppt.LoadFromFile("test.pptx");

Step 2: Instantiate a list of IShape objects.

List<IShape> shapelist = new List<IShape>();

Step 3: Loop through all sildes in the document and all shapes on each slide, add the shape which placeholder type is title or centered title or subtitle to the list.

foreach (ISlide slide in ppt.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        if (shape.Placeholder != null)
        {
            switch (shape.Placeholder.Type)
            {
                case PlaceholderType.Title:
                    shapelist.Add(shape);
                    break;
                case PlaceholderType.CenteredTitle:
                    shapelist.Add(shape);
                    break;
                case PlaceholderType.Subtitle:
                    shapelist.Add(shape);
                    break;
            }
        }
    }
}

Step 4: Loop through the list and print out the inner text of all shapes in the list.

for (int i = 0; i < shapelist.Count; i++)
{
    IAutoShape shape1 = shapelist[i] as IAutoShape;
    Console.WriteLine(shape1.TextFrame.Text);
}

Output:

How to Get the Titles of All Slides with C#

Full code:

using System;
using System.Collections.Generic;
using Spire.Presentation;

namespace Get_the_Titles_of_All_Slides
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("test.pptx");
            List<IShape> shapelist = new List<IShape>();
            foreach (ISlide slide in ppt.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape.Placeholder != null)
                    {
                        switch (shape.Placeholder.Type)
                        {
                            case PlaceholderType.Title:
                                shapelist.Add(shape);
                                break;
                            case PlaceholderType.CenteredTitle:
                                shapelist.Add(shape);
                                break;
                            case PlaceholderType.Subtitle:
                                shapelist.Add(shape);
                                break;
                        }
                    }
                }
            }
            for (int i = 0; i < shapelist.Count; i++)
            {
                IAutoShape shape1 = shapelist[i] as IAutoShape;
                Console.WriteLine(shape1.TextFrame.Text);
            }
            Console.ReadKey();
        }
    }
}

Every time when we change the slide's size, we need to reset the size and position for the shape to ensure the shape on the slide shows orderly. This tutorial will focus on demonstrating how to reset the size and position for the shape in C#.

Firstly, please view the original shape:

Reset the size and position for the shape on presentation slides in C#

Code snippet of how to set the size and position of the shape:

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

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

Step 2: Define the original slide size.

float currentHeight = presentation.SlideSize.Size.Height;
float currentWidth = presentation.SlideSize.Size.Width;

Step 3: Change the slide size as A3.

presentation.SlideSize.Type = SlideSizeType.A3;

Step 4: Define the new slide size.

float newHeight = presentation.SlideSize.Size.Height;
float newWidth = presentation.SlideSize.Size.Width;

Step 5: Define the ratio from the old and new slide size.

float ratioHeight = newHeight / currentHeight;
float ratioWidth = newWidth / currentWidth;

Step 6: Reset the size and position of the shape on the slide.

foreach (ISlide slide in presentation.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        //Reset the shape size
        shape.Height = shape.Height * ratioHeight;
        shape.Width = shape.Width * ratioWidth;

        //Reset the shape position
        shape.Left = shape.Left * ratioHeight;
        shape.Top = shape.Top * ratioWidth;

    }

Step 7: Save the document to file.

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

Effective screenshot after reset the size and position of the shape on the slide:

Reset the size and position for the shape on presentation slides in C#

Full codes:

{
 Presentation presentation = new Presentation();
 presentation.LoadFromFile("Sample.pptx");

 float currentHeight = presentation.SlideSize.Size.Height;
 float currentWidth = presentation.SlideSize.Size.Width;
 
 presentation.SlideSize.Type = SlideSizeType.A3;

 float newHeight = presentation.SlideSize.Size.Height;
 float newWidth = presentation.SlideSize.Size.Width;

 float ratioHeight = newHeight / currentHeight;
 float ratioWidth = newWidth / currentWidth;

 foreach (ISlide slide in presentation.Slides)
 {
     foreach (IShape shape in slide.Shapes)
     {
         shape.Height = shape.Height * ratioHeight;
         shape.Width = shape.Width * ratioWidth;

         shape.Left = shape.Left * ratioHeight;
         shape.Top = shape.Top * ratioWidth;
     }

     presentation.SaveToFile("resize.pptx", FileFormat.Pptx2010);
 }
}

Polygon annotations are displayed as a series of connected vertices and can be double-clicked to display its note. Users can customize the shape of polygon by setting the vertex coordinates. This article will introduce how to add a polygon annotation to PDF using Spire.PDF.

Step 1: Create a PDF document object, add a new page.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Initialize an instance of PdfPolygonAnnotation, specifying all vertex coordinates which can form a complete shape.

PdfPolygonAnnotation polygon = new PdfPolygonAnnotation(page, new PointF[] { new PointF(0, 30), new PointF(30, 15), new PointF(60, 30),
new PointF(45, 50), new PointF(15, 50), new PointF(0, 30)});

Step 3: Set the border color, text, border effect and other properties of polygon annotation.

polygon.Color = Color.PaleVioletRed;
polygon.Text = "This is a polygon annotation";
polygon.Author = "E-ICEBLUE";
polygon.Subject = "polygon annotation demo";
polygon.BorderEffect = PdfBorderEffect.BigCloud;
polygon.ModifiedDate = DateTime.Now;

Step 4: Add the annotation to PDF page and save the document.

page.AnnotationsWidget.Add(polygon);
pdf.SaveToFile("Polygon_Annotation.pdf");

Result:

How to Add a Polygon Annotation to PDF in C#, VB.NET

Full Code:

[C#]
PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

PdfPolygonAnnotation polygon = new PdfPolygonAnnotation(page, new PointF[] { new PointF(0, 30), new PointF(30, 15), new PointF(60, 30),
    new PointF(45, 50), new PointF(15, 50), new PointF(0, 30)});
polygon.Color = Color.PaleVioletRed;
polygon.Text = "This is a polygon annotation";
polygon.Author = "E-ICEBLUE";
polygon.Subject = "polygon annotation demo";
polygon.BorderEffect = PdfBorderEffect.BigCloud;
polygon.ModifiedDate = DateTime.Now;

page.AnnotationsWidget.Add(polygon);
pdf.SaveToFile("Polygon_Annotation.pdf");
[VB.NET]
Dim pdf As PdfDocument = New PdfDocument()
Dim page As PdfPageBase = pdf.Pages.Add()

PdfPolygonAnnotation polygon = New PdfPolygonAnnotation(page, New PointF()
{
    New PointF(0, 30), New PointF(30, 15), New PointF(60, 30),
    New PointF(45, 50), New PointF(15, 50), New PointF(0, 30)
    }
)
polygon.Color = Color.PaleVioletRed
polygon.Text = "This is a polygon annotation"
polygon.Author = "E-ICEBLUE"
polygon.Subject = "polygon annotation demo"
polygon.BorderEffect = PdfBorderEffect.BigCloud
polygon.ModifiedDate = DateTime.Now

page.AnnotationsWidget.Add(polygon)
pdf.SaveToFile("Polygon_Annotation.pdf")
Thursday, 29 December 2016 07:59

Create a GoToE Action to an Embedded PDF File

The GoToE (or embedded go-to) action is similar to a remote go-to action but allows jumping to a PDF file that is embedded in another PDF file. With Spire.PDF, it’s possible to create a GoToE action to direct from the current PDF file to the embedded PDF file. This article demonstrates how to accomplish this goal programmatically with C#.

At first, it's necessary to introduce you the parameters of public PdfEmbeddedGoToAction(string fileName, PdfDestination dest, bool newWindow);

Parameters:

  • fileName - the name of the target file.
  • dest - the destination inside the target file.
  • newWindow - if true open the file in a new window, if false the current file is replaced by the new file.

Now Follow below Detail steps:

Step 1: Create a PDF file and add a page to it.

PdfDocument pdf = new PdfDocument();
PdfPageBase page = pdf.Pages.Add();

Step 2: Attach a PDF file to the newly created file.

PdfAttachment attachment = new PdfAttachment("New Zealand.pdf");
pdf.Attachments.Add(attachment);

Step 3: Draw text on the page.

string text = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
float width = 490f;
float height = font.Height * 2.2f;
RectangleF rect = new RectangleF(0, 100, width, height);
page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);

Step 4: Create an embedded go-to action (/GoToE) which allows jumping to the attached PDF file and open it in a new window at the 2nd page and 200% zoom factor.

PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);
PdfEmbeddedGoToAction action = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);

Step 5: Create an action annotation with the embedded go-to action and then add it to the page.

PdfActionAnnotation annotation = new PdfActionAnnotation(rect, action);
(page as PdfNewPage).Annotations.Add(annotation);

Step 6: Save the document.

pdf.SaveToFile("result.pdf");

Effective Screenshot:

Create a GoToE Action to an Embedded PDF File

Full code:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Attachments;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;

namespace Create_A_GoToE_Action
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            PdfPageBase page = pdf.Pages.Add();
            PdfAttachment attachment = new PdfAttachment("New Zealand.pdf");
            pdf.Attachments.Add(attachment);
            string text = "Test embedded go-to action! Click this will open the attached PDF in a new window.";
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
            float width = 490f;
            float height = font.Height * 2.2f;
            RectangleF rect = new RectangleF(0, 100, width, height);
            page.Canvas.DrawString(text, font, PdfBrushes.Black, rect);
            PdfDestination dest = new PdfDestination(1, new PointF(0, 842), 2f);
            PdfEmbeddedGoToAction action = new PdfEmbeddedGoToAction(attachment.FileName, dest, true);
            PdfActionAnnotation annotation = new PdfActionAnnotation(rect, action);
            (page as PdfNewPage).Annotations.Add(annotation);
            pdf.SaveToFile("result.pdf");            
        }
    }		 
}
Wednesday, 28 December 2016 08:08

How to update Ask Field in C#

With Spire.Doc for .NET, developers can easily operate the word fields from code. We have already shown how to create an IF field and remove Custom Property Fields in C#. From Spire.Doc V5.8.33, our developers add a new event UpdateFields to handle the Ask Field. This article will focus on demonstrating how to update the ASK field on the word document in C#.

Firstly, please view the sample document with an Ask filed which will be updated later:

How to update Ask Field in C#

Step 1: Create a new instance of Spire.Doc.Document class and load the document from file.

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

Step 2: Call UpdateFieldsHandler event to update the ASK field.

doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

Step 3: Update the fields in the document.

doc.IsUpdateFields = true;

Step 4: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

The following doc_UpdateFields () method shows how to update the ask field:

private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

Effective screenshot after updating the Ask Field in C#:

How to update Ask Field in C#

Full codes:

public AskField()
 {

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

     doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);

     doc.IsUpdateFields = true;

     doc.SaveToFile("output.docx", FileFormat.Docx);
     
 }
 private static void doc_UpdateFields(object sender, IFieldsEventArgs args)
 {
     if (args is AskFieldEventArgs)
     {
         AskFieldEventArgs askArgs = args as AskFieldEventArgs;

         askArgs.ResponseText = "Female";
     }
 }

Adding rows and columns are common tasks in Word table processing, on the contrary, sometimes we also have the requirement of deleting rows or columns from a table. This article demonstrates how to delete a row and a column from an existing Word table using Spire.Doc.

Below is the screenshot of the original table. Afterwards, we will remove the colored row and column from the table.

How to Delete Rows and Columns from a Word Table in C#, VB.NET

Detail steps:

Step 1: Instantiate a Document object and load the Word document.

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

Step 2: Get the table from the document.

Table table = doc.Sections[0].Tables[0] as Table;   

Step 3: Delete the third row from the table.

table.Rows.RemoveAt(2);

Step 4: Delete the third column from the table.

for (int i = 0; i < table.Rows.Count; i++)
{
    table.Rows[i].Cells.RemoveAt(2);
}

Step 5: Save the document.

doc.SaveToFile("result.docx",FileFormat.docx2013);

Output:

How to Delete Rows and Columns from a Word Table in C#, VB.NET

Full code:

[C#]
using Spire.Doc;

namespace Delete_Rows_and_Columns
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");
            Table table = doc.Sections[0].Tables[0] as Table;           
            table.Rows.RemoveAt(2);
            for (int i = 0; i < table.Rows.Count; i++)
            {
                table.Rows[i].Cells.RemoveAt(2);
            }
            doc.SaveToFile("result.docx",FileFormat.docx2013);
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace Delete_Rows_and_Columns
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			doc.LoadFromFile("Sample.docx")
			Dim table As Table = TryCast(doc.Sections(0).Tables(0), Table)
			table.Rows.RemoveAt(2)
			For i As Integer = 0 To table.Rows.Count - 1
				table.Rows(i).Cells.RemoveAt(2)
			Next
			doc.SaveToFile("result.docx",FileFormat.docx2013);
		End Sub
	End Class
End Namespace

With the help of Spire.XLS, we could easily add header and footer to the excel page; we can also set different Header and Footer for Odd and Even Pages in Excel. This article will demonstrate how to add different header & footer for the first page on the excel worksheet.

Here comes to the code snippets of how to set different header and footer for the first page:

Step 1: Initialize an instance of Workbook and get the first worksheet.

Workbook workbook = new Workbook();
Worksheet sheet = workbook.Worksheets[0];

Step 2: Set the value of DifferentFirst as 1, which indicates that headers/footers for first page are different from the other pages.

Step 3: Set the header and footer for the first page.

sheet.PageSetup.FirstHeaderString = "Different First page";
sheet.PageSetup.FirstFooterString = "Different First footer";

Step 4: Set the other pages' header and footer. If we don't need to set the header and footer for other pages, we can ignore this step.

sheet.PageSetup.LeftHeader = "Demo of Spire.XLS";
sheet.PageSetup.CenterFooter = "Footer by Spire.XLS";

Step 5: Save the document to file.

workbook.SaveToFile("Result.xlsx", FileFormat.Version2010); 

Effective screenshot:

How to add different header & footer for the first page

Full codes:

static void Main(string[] args)
{
    Workbook workbook = new Workbook();
    Worksheet sheet = workbook.Worksheets[0];

    sheet.PageSetup.DifferentFirst = 1;

    sheet.PageSetup.FirstHeaderString = "Different First page";
    sheet.PageSetup.FirstFooterString = "Different First footer";
                
    sheet.PageSetup.LeftHeader = "Demo of Spire.XLS";
    sheet.PageSetup.CenterFooter = "Footer by Spire.XLS";
                                        
    workbook.SaveToFile("result.xlsx", FileFormat.Version2010);            
}