SVG (Scalable Vector Graphics) is an image file format and it has the advantage of be edited and indexed easily. It is widely used for interactivity and animation. Starts from Spire.Doc V5.8, Spire.Doc offers a method doc.SaveToFile() to enable developers to save the word document to SVG file format in C# easily. This article will focus on demonstrate how to convert word document to SVG with the help of Spire.Doc by using a simple line of code in C#.

Firstly, please view the original word document:

How to Convert Word to SVG (Scalable Vector Graphics) in C#

Step 1: Create a C# project in visual studio, then add a reference to Spire.Doc.dll and use the following namespace.

using Spire.Doc;

Step 2: Create a word instance and load the source word document from file.

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

Step 3: Save the document to SVG file.

doc.SaveToFile("result.svg", FileFormat.SVG);

After running the code, we'll get the effective screenshot of the following result SVG file from word document:

How to Convert Word to SVG (Scalable Vector Graphics) in C#

Full codes:

using Spire.Doc;

namespace wordconversion.Case
{
    class WordtoSVG
    {

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

        doc.SaveToFile("result.svg", FileFormat.SVG);
         }

    }
}

Videos are common elements in PowerPoint, sometimes developers need to extract videos from PowerPoint documents and save them to disk programmatically. Spire.Presentation provides developers many flexible functions to manipulate PowerPoint documents including extract Videos. This article will explain how to achieve this task in C# and VB.NET using Spire.Presentation.

Note: Before start, please download and install Spire.Presentation correctly, after that add a reference to Spire.Presentation.dll in your project.

Detail steps:

Step 1: Instantiate an object of Presentation class and load the sample document.

Presentation presentation = new Presentation();
presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pptx");

Step 2: Loop through all shapes on the slides, find out the videos and then call VideoData.SaveToFile(string fileName) method to save them to disk.

int i = 0;
foreach (ISlide slide in presentation.Slides)
{
    foreach (IShape shape in slide.Shapes)
    {
        if (shape is IVideo)
        {
            (shape as IVideo).EmbeddedVideoData.SaveToFile(string.Format(@"Video\Video-{0}.mp4",i));
            i++;
        }
    }
}

Below are the extracted videos from the PowerPoint document:

How to Extract Videos from PowerPoint Documents in C#, VB.NET

Full code:

[C#]
using Spire.Presentation;

namespace Extract_Video
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            presentation.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pptx");
            int i = 0;
            foreach (ISlide slide in presentation.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape is IVideo)
                    {
                        (shape as IVideo).EmbeddedVideoData.SaveToFile(string.Format(@"Video\Video-{0}.mp4",i));
                        i++;
                    }
                }
            }

        }
    }
}
[VB.NET]
Imports Spire.Presentation

Namespace Extract_Video
	Class Program
		Private Shared Sub Main(args As String())
			Dim presentation As New Presentation()
			presentation.LoadFromFile("C:\Users\Administrator\Desktop\Sample.pptx")
			Dim i As Integer = 0
			For Each slide As ISlide In presentation.Slides
				For Each shape As IShape In slide.Shapes
					If TypeOf shape Is IVideo Then
						TryCast(shape, IVideo).EmbeddedVideoData.SaveToFile(String.Format("Video\Video-{0}.mp4", i))
						i += 1
					End If
				Next
			Next

		End Sub
	End Class
End Namespace

Required fields force the user to fill in the selected form field. If the user attempts to submit the form while a required field is blank, an error message appears and the empty required form field is highlighted.

Using Spire.PDF, we're able to enforce a form field as "Required" or determine which fields are required in an existing PDF document. This article mainly introduce how to detect the required form fields in C# and VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class and load a sample PDF file that contains some form fields.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.pdf");

Step 2: Get all form widgets from the PDF document.

PdfFormWidget formWidget = doc.Form as PdfFormWidget;

Step 3: Traverse the form widgets to find the form field that is required and print all results on console.

for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
    PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
    string fieldName = field.Name;
    bool isRequired = field.Required;
    if (isRequired)
    {
        Console.WriteLine(fieldName + " is required.");
    }
}

Output:

How to Detect the Required Form Field in PDF in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.pdf");

PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
    PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
    string fieldName = field.Name;
    bool isRequired = field.Required;
    if (isRequired)
    {
        Console.WriteLine(fieldName + " is required.");
    }
}
Console.ReadKey();
[VB.NET]
Dim doc As New PdfDocument()
doc.LoadFromFile("C: \Users\Administrator\Desktop\PdfFormExample.pdf")

Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget)
For i As Integer = 0 To formWidget.FieldsWidget.List.Count - 1
	Dim field As PdfField = TryCast(formWidget.FieldsWidget.List(i), PdfField)

    Dim fieldName As String = field.Name

    Dim isRequired As Boolean = field.Required

    If isRequired Then
        Console.WriteLine(fieldName & Convert.ToString(" is required."))
	End If
Next
Console.ReadKey()

Hyperlinks give more additional information for readers and it is widely used on our word documents. Spire.Doc has a powerful function of operating the word elements of hyperlinks. Developers can add hyperlinks, modify and remove hyperlinks from word documents. Spire.Doc also supports to preserve hyperlinks or not in word to PDF conversion. This article will show you how to preserve hyperlinks or disable the hyperlinks in C# when converting word document into PDF file format.

Here comes to the code snippets of how to disable or preserve hyperlinks from word to PDF.

Step 1: Load a word documents with hyperlinks.

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

Step 2: Create an instance of ToPdfParameterList.

ToPdfParameterList pdf = new ToPdfParameterList();

Step 3: Set DisableLink to true to remove the hyperlink effect for the result PDF page.

//set DisableLink to false to preserve the hyperlinks
pdf.DisableLink = true;

Step 4: Save the PDF file.

doc.SaveToFile("result.pdf", pdf);

Effective screenshot of preserve the hyperlinks from the result PDF page.

Preserve or disable hyperlinks from word to PDF conversion

Effective screenshot of disabled the hyperlinks from the result PDF page.

Preserve or disable hyperlinks from word to PDF conversion

Full codes of how to preserve the hyperlinks or not when convert word document to PDF file:

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

ToPdfParameterList pdf = new ToPdfParameterList();

    //set DisableLink to false to preserve the hyperlinks
    pdf.DisableLink = true;

    doc.SaveToFile("result.pdf", pdf);
}
Thursday, 13 October 2016 08:24

How to Create Pie Chart in PowerPoint in C#

A pie chart helps show proportions and percentages between categories, by dividing a circle into proportional segments. This article will introduce how to create a pie chart that looks like the below screenshot in PowerPoint document using Spire.Presentation in C#.

How to Create Pie Chart in PowerPoint in C#

Code Snippets:

Step 1: Initialize an instance of Presentation class.

Presentation ppt = new Presentation();

Step 2: Insert a Pie chart to the first slide by calling the AppendChart() method and set the chart title.

RectangleF rect1 = new RectangleF(40, 100, 550, 320);
IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.Pie, rect1, false);
chart.ChartTitle.TextProperties.Text = "Sales by Quarter";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;
chart.HasTitle = true;

Step 3: Define some data.

string[] quarters = new string[] { "1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr" };
int[] sales = new int[] { 210, 320, 180, 500 };

Step 4: Append data to ChartData, which represents a data table where the chart data is stored.

chart.ChartData[0, 0].Text = "Quarters";
chart.ChartData[0, 1].Text = "Sales";
for (int i = 0; i < quarters.Length; ++i)
{
    chart.ChartData[i + 1, 0].Value = quarters[i];
    chart.ChartData[i + 1, 1].Value = sales[i];
}

Step 5: Set category labels, series label and series data.

chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];
chart.Series[0].Values = chart.ChartData["B2", "B5"];

Step 6: Add data points to series and fill each data point with different color.

for (int i = 0; i < chart.Series[0].Values.Count; i++)
{
    ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
    cdp.Index = i;
    chart.Series[0].DataPoints.Add(cdp);

}
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.RosyBrown;
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.LightBlue;
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.LightPink;
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.MediumPurple;

Step 7: Set the data labels to display label value and percentage value.

chart.Series[0].DataLabels.LabelValueVisible = true;
chart.Series[0].DataLabels.PercentValueVisible = true;

Step 8: Save the file.

ppt.SaveToFile("PieChart.pptx", FileFormat.Pptx2010);

Full Code:

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System.Drawing;


namespace CreatePieChartInPowerPoint
{
    class Program
    {
        static void Main(string[] args)
        {

            Presentation ppt = new Presentation();

            RectangleF rect1 = new RectangleF(40, 100, 550, 320);
            IChart chart = ppt.Slides[0].Shapes.AppendChart(ChartType.Pie, rect1, false);
            chart.ChartTitle.TextProperties.Text = "Sales by Quarter";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;
            chart.HasTitle = true;

            string[] quarters = new string[] { "1st Qtr", "2nd Qtr", "3rd Qtr", "4th Qtr" };
            int[] sales = new int[] { 210, 320, 180, 500 };
            chart.ChartData[0, 0].Text = "Quarters";
            chart.ChartData[0, 1].Text = "Sales";
            for (int i = 0; i < quarters.Length; ++i)
            {
                chart.ChartData[i + 1, 0].Value = quarters[i];
                chart.ChartData[i + 1, 1].Value = sales[i];
            }
            
            chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];         
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];
            chart.Series[0].Values = chart.ChartData["B2", "B5"];

            for (int i = 0; i < chart.Series[0].Values.Count; i++)
            {
                ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
                cdp.Index = i;
                chart.Series[0].DataPoints.Add(cdp);

            }
            chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.RosyBrown;
            chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.LightBlue;
            chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.LightPink;
            chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.MediumPurple;

            chart.Series[0].DataLabels.LabelValueVisible = true;
            chart.Series[0].DataLabels.PercentValueVisible = true;

            ppt.SaveToFile("PieChart.pptx", FileFormat.Pptx2010);
            System.Diagnostics.Process.Start("PieChart.pptx");
        }
    }
}

With the help of Spire.Doc, we can easily add the hyperlinks and edit the hyperlinks on the word document. This article will focus on demonstrate how to remove all the hyperlinks from the word document in C#.

Here comes to the details of how to remove the hyperlinks from the word document. Firstly, view the sample document with many hyperlinks:

How to remove the hyperlinks from the word document in C#

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

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

Step 2: Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document.

private List FindAllHyperlinks(Document document)
 {
     List hyperlinks = new List();
     foreach (Section section in document.Sections)
     {
         foreach (DocumentObject sec in section.Body.ChildObjects)
         {
             if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
             {
                 foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                 {
                     if (para.DocumentObjectType == DocumentObjectType.Field)
                     {
                         Field field = para as Field;

                         if (field.Type == FieldType.FieldHyperlink)
                         {
                             hyperlinks.Add(field);
                         }
                     }
                 }
             } 
         }
     }
     return hyperlinks;
 }

Step 3: Remove the font color and underline format of the hyperlinks.

private void FormatFieldResultText(Body ownerBody,int sepOwnerParaIndex,int endOwnerParaIndex,int sepIndex,int endIndex)
{
    for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
    {
        Paragraph para = ownerBody.ChildObjects[i] as Paragraph;
        if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
        {
            for (int j = sepIndex + 1; j < endIndex; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
            
        }
        else if (i == sepOwnerParaIndex)
        {
            for (int j = sepIndex + 1; j < para .ChildObjects .Count ; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
        else if (i == endOwnerParaIndex)
        {
            for (int j = 0; j < endIndex; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
        else
        {
            for (int j = 0; j < para.ChildObjects.Count; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
    }
}
private void FormatText(TextRange tr)
{
    tr.CharacterFormat.TextColor = Color.Black;
    tr.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
}

Step 4: Flatten the hyperlink field.

private void FlattenHyperlinks(Field field)
{
    int ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
    int fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
    Paragraph sepOwnerPara = field.Separator.OwnerParagraph;
    int sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
    int sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
    int endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
    int endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);

    FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);

    field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);

    for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
    {
        if (i == sepOwnerParaIndex && i == ownerParaIndex)
        {
            for (int j = sepIndex; j >= fieldIndex; j--)
            {
                field.OwnerParagraph.ChildObjects.RemoveAt(j);

            }
        }
        else if (i == ownerParaIndex)
        {
            for (int j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--)
            {
                field.OwnerParagraph.ChildObjects.RemoveAt(j);
            }

        }
        else if (i == sepOwnerParaIndex)
        {
            for (int j = sepIndex; j >= 0; j--)
            {
                sepOwnerPara.ChildObjects.RemoveAt(j);
            }
        }
        else
        {
            field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
        }
    }
}

Step 5: Save the document to file.

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

Effective screenshot after remove the hyperlinks from the word document:

How to remove the hyperlinks from the word document in C#

Full codes of how to remove the hyperlinks from word document:

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

    List hyperlinks = FindAllHyperlinks(doc);

    for (int i = hyperlinks.Count - 1; i >= 0; i--)
    {
        FlattenHyperlinks(hyperlinks[i]);
    }

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

}
private List FindAllHyperlinks(Document document)
        {
            List hyperlinks = new List();
            foreach (Section section in document.Sections)
            {
                foreach (DocumentObject sec in section.Body.ChildObjects)
                {
                    if (sec.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject para in (sec as Paragraph).ChildObjects)
                        {
                            if (para.DocumentObjectType == DocumentObjectType.Field)
                            {
                                Field field = para as Field;

                                if (field.Type == FieldType.FieldHyperlink)
                                {
                                    hyperlinks.Add(field);
                                }
                            }
                        }
                    }
                }
            }
            return hyperlinks;
        }

private void FlattenHyperlinks(Field field)
{
    int ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
    int fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
    Paragraph sepOwnerPara = field.Separator.OwnerParagraph;
    int sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
    int sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
    int endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
    int endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);

    FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);

    field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);

    for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
    {
        if (i == sepOwnerParaIndex && i == ownerParaIndex)
        {
            for (int j = sepIndex; j >= fieldIndex; j--)
            {
                field.OwnerParagraph.ChildObjects.RemoveAt(j);

            }
        }
        else if (i == ownerParaIndex)
        {
            for (int j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--)
            {
                field.OwnerParagraph.ChildObjects.RemoveAt(j);
            }

        }
        else if (i == sepOwnerParaIndex)
        {
            for (int j = sepIndex; j >= 0; j--)
            {
                sepOwnerPara.ChildObjects.RemoveAt(j);
            }
        }
        else
        {
            field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
        }
    }
}

private void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
{
    for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
    {
        Paragraph para = ownerBody.ChildObjects[i] as Paragraph;
        if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
        {
            for (int j = sepIndex + 1; j < endIndex; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }

        }
        else if (i == sepOwnerParaIndex)
        {
            for (int j = sepIndex + 1; j < para.ChildObjects.Count; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
        else if (i == endOwnerParaIndex)
        {
            for (int j = 0; j < endIndex; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
        else
        {
            for (int j = 0; j < para.ChildObjects.Count; j++)
            {
                FormatText(para.ChildObjects[j] as TextRange);
            }
        }
    }
}
private void FormatText(TextRange tr)
{
    tr.CharacterFormat.TextColor = Color.Black;
    tr.CharacterFormat.UnderlineStyle = UnderlineStyle.None;
}

About SVG (Scalable Vector Graphics)

SVG (Scalable Vector Graphics) is an image file format for two-dimensional, XML based vector images developed by the World Wide Web Consortium (W3C). Comparing with other image file formats, SVG has many advantages such as supporting interactivity and animation, allowing users to search, index, script, and compress/enlarge images without losing quality and it can be created and edited with any text editor.

Convert PDF to SVG (Scalable Vector Graphics) using Spire.PDF

Very often, developers need to convert files like PDF to SVG file format. The following part shows how to accomplish this requirement using a powerful .NET PDF component - Spire.PDF. Below is the screenshot of the source PDF file:

Convert PDF to SVG (Scalable Vector Graphics) in C#, VB.NET

Detail steps:

Step 1: Create a C#/Vb.net project in visual studio, then add a reference to Spire.Pdf.dll and use the following namespace.

using Spire.Pdf;

Step 2: Instantiate an object of PdfDocument class and load the source PDF file.

PdfDocument document = new PdfDocument();
document.LoadFromFile("Test.pdf");

Step 3: Call SaveToFile(string filename, FileFormat fileFormat) method to save PDF file to SVG file format.

document.SaveToFile(@"E:\Program Files\Result.svg", FileFormat.SVG);

After running the code, we'll get the following result SVG file:

Convert PDF to SVG (Scalable Vector Graphics) in C#, VB.NET

Full code:

[C#]
using Spire.Pdf;

namespace Convert_PDF_to_SVG
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument document = new PdfDocument();
            document.LoadFromFile("Test.pdf");

            document.SaveToFile(@"E:\Program Files\Result.svg", FileFormat.SVG);
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace Convert_PDF_to_SVG
	Class Program
		Private Shared Sub Main(args As String())
			Dim document As New PdfDocument()
			document.LoadFromFile("Test.pdf")

			document.SaveToFile("E:\Program Files\Result.svg", FileFormat.SVG)
		End Sub
	End Class
End Namespace
Thursday, 29 September 2016 08:16

How to Copy a Chart in PowerPoint

In this article, we will explain how to copy an existing chart within the same PowerPoint document or between PowerPoint documents by using Spire.Presentation. Below example called a main method public IChart CreateChart(IChart baseChart, RectangleF rectangle, int nIndex).

There are three Parameters passed in this method:

  • baseChart: The source chart.
  • rectangle: The area that the chart will be copied to.
  • nIndex: The index of the rectangle shape. For example, -1 means append it as the last shape of the slide, 0 means append as the first shape.

Now refer to the following steps:

Copy chart within the same PowerPoint document

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

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

Step 2: Get the chart that is going to be copied.

IChart chart = ppt.Slides[0].Shapes[0] as IChart;

Step 3: Copy the chart from the first slide to the specified location of the second slide within the same document.

ppt.Slides[1].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), 0);

Step 4: Save the document.

ppt.SaveToFile("TestResult.pptx", FileFormat.Pptx2010);

Screenshot of copying chart within the same PowerPoint document:

Copy chart within the same PowerPoint document

Copy chart between PowerPoint documents

Step 1: Load the first PowerPoint document.

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

Step 2: Get the chart that is going to be copied.

IChart chart = ppt1.Slides[0].Shapes[0] as IChart;

Step 3: Load the second PowerPoint document.

Presentation ppt2 = new Presentation();
ppt2.LoadFromFile("Dest.pptx");

Step 4: Copy chart from the first document to the specified location of the second document.

ppt2.Slides[0].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), -1);

Step 5: Save the second document.

ppt2.SaveToFile("TestResult2.pptx", FileFormat.Pptx2010);

Screenshot of copying chart between PowerPoint documents:

Copy chart between PowerPoint documents

Full code:

Copy chart within the same PowerPoint document

using System.Drawing;
using Spire.Presentation;
using Spire.Presentation.Charts;

namespace Copy_Chart
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx");
            IChart chart = ppt.Slides[0].Shapes[0] as IChart;
            ppt.Slides[1].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), 0);
            ppt.SaveToFile("TestResult.pptx", FileFormat.Pptx2010);
        }
    }
}

Copy chart between PowerPoint documents

using System.Drawing;
using Spire.Presentation;
using Spire.Presentation.Charts;

namespace Copy_Chart
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation ppt1 = new Presentation();
            ppt1.LoadFromFile("Sample.pptx");
            IChart chart = ppt1.Slides[0].Shapes[0] as IChart;
            Presentation ppt2 = new Presentation();
            ppt2.LoadFromFile("Dest.pptx");
            ppt2.Slides[0].Shapes.CreateChart(chart, new RectangleF(100, 100, 500, 300), -1);
            ppt2.SaveToFile("TestResult2.pptx", FileFormat.Pptx2010);
        }
    }
}

Spire.XLS enable programmers to insert, modify as well as format comments in Excel. Also, it allows users to fill a comment with solid color, gradient, pattern or a picture to change the look of the comment. This article is going to introduce how to set background image for a comment in Excel using Spire.XLS.

Code Snippet:

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

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

Step 2: Fill the comment with a customized background picture.

Image image = Image.FromFile(@"C: \Users\Administrator\Desktop\logo.png");
sheet.Range["C6"].Comment.Fill.CustomPicture(image, "logo.png");

Step 3: Re-set the size of comment box.

sheet.Range["C6"].Comment.Height = image.Height;
sheet.Range["C6"].Comment.Width = image.Width;

Step 4: Save the file.

wb.SaveToFile("PicFillComment.xls", ExcelVersion.Version97to2003);

Output:

How to Set Picture Fill for Excel Comment in C#, VB.NET

Full Code:

[C#]
Workbook wb = new Workbook();
Worksheet sheet = wb.Worksheets[0];

Image image = Image.FromFile(@"C: \Users\Administrator\Desktop\logo.png");
sheet.Range["C6"].Comment.Fill.CustomPicture(image, "logo.png");
sheet.Range["C6"].Comment.Height = image.Height;
sheet.Range["C6"].Comment.Width = image.Width;

wb.SaveToFile("PicFill.xls", ExcelVersion.Version97to2003);
[VB.NET]
Dim wb As New Workbook()
Dim sheet As Worksheet = wb.Worksheets(0)

Dim image__1 As Image = Image.FromFile("C: \Users\Administrator\Desktop\logo.png")
sheet.Range("C6").Comment.Fill.CustomPicture(image__1, "logo.png")
sheet.Range("C6").Comment.Height = image__1.Height
sheet.Range("C6").Comment.Width = image__1.Width

wb.SaveToFile("PicFill.xls", ExcelVersion.Version97to2003)
Tuesday, 27 September 2016 03:47

How to use mail merge to merge the image value

Last article we have shown how to create the mail merge template and merge the text value to it by using Spire.Doc. As we know that, besides the text value, we also use the mail merge feature to merge the image value too. This article will demonstrate how to merge the image value to the mail merge template in C#.

Here comes to the details of how use the mail merge to merge the image value. Firstly, please view the mail merge template and the image later will be merged to it.

How to use mail merge to merge the image value

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

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

Step 2: Set the value for the mail merge template by the fieldname.

var fieldNames = new string[] { "MyImage" };
var fieldValues = new string[] { "logo.png" };

Step 3: Create a method to get the image file:

void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
        {
            string filePath = field.FieldValue as string;
            if (!string.IsNullOrEmpty(filePath))
            {
                field.Image = Image.FromFile(filePath);
            }

        }

Step 4: Call the method MailMerge_MergeImageField() to get the image and then merge the specified value into template.

doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

Step 5: Save the document to file.

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

Effective screenshot after merge the image value to the mail merge template:

How to use mail merge to merge the image value

Full codes:

class MailMergeImage
{
    public MailMergeImage()
    {
        Document doc = new Document();
        doc.LoadFromFile("Test.docx");
        var fieldNames = new string[] { "MyImage" };
        var fieldValues = new string[] { "logo.png" };

        doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);

        doc.MailMerge.Execute(fieldNames, fieldValues);

        doc.SaveToFile("result.docx", FileFormat.Docx);
    }

    void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field)
    {
        string filePath = field.FieldValue as string;
        if (!string.IsNullOrEmpty(filePath))
        {
            field.Image = Image.FromFile(filePath);
        }

    }
}