Spire.OCR for .NET Program Guide Content

2023-02-13 08:46:02 Written by Koohji

Spire.OCR for .NET is a professional OCR library to read text from Images in JPG, PNG, GIF, BMP and TIFF formats. Developers can easily add OCR functionalities within .NET applications in C# and VB.NET. It supports commonly used image formats and provides functionalities like reading multiple characters and fonts from images, bold and italic styles, scanning of the whole image and much more.

Spire.OCR for .NET provides a very easy way to read text from images. With just one line of code in C# and VB.NET, Spire.OCR supports variable common image formats, such as Bitmap, JPG, PNG, TIFF and GIF.

Spire.Barcode for .NET is a professional barcode library specially designed for .NET developers ( C#, VB.NET, ASP.NET, .NET Core, .Net Standard, .NET 5.0, MonoAndroid, Xamarin.iOS ) to generate, read and scan 1D & 2D barcodes. Developers and programmers can use Spire.Barcode to add Enterprise-Level barcode formats to their .net applications quickly and easily.

Spire.Barcode for .NET provides a very easy way to integrate barcode processing. With just one line of code to create, read 1D & 2D barcode, Spire.Barcode supports variable common image formats, such as Bitmap, JPG, PNG, EMF, TIFF, GIF and WMF.

C#/VB.NET: Convert PDF to PowerPoint

2023-01-11 02:09:43 Written by Koohji

PDF files are great for presenting on different types of devices and sharing across platforms, but it has to admit that editing PDF is a bit challenging. When you receive a PDF file and need to prepare a presentation based on the content inside, it is recommended to convert the PDF file to a PowerPoint document to have a better presentation effect and also to ensure the content can be further edited. This article will demonstrate how to programmatically convert PDF to PowerPoint presentation using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Convert PDF to PowerPoint Presentation in C# and VB.NET

From Version 8.11.10, Spire.PDF for .NET supports converting PDF to PPTX using PdfDocument.SaveToFile() method. With this method, each page of your PDF file will be converted to a single slide in PowerPoint. Below are the steps to convert a PDF file to an editable PowerPoint document.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Save the document as a PowerPoint document using PdfDocument.SaveToFile(string filename, FileFormat.PPTX) method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace PDFtoPowerPoint
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            //Load a sample PDF document
            pdf.LoadFromFile(@"C:\Users\Administrator\Desktop\Sample.pdf");

            //Convert the PDF to PPTX document
            pdf.SaveToFile("ConvertPDFtoPowerPoint.pptx", FileFormat.PPTX);
        }
    }
}

C#/VB.NET: Convert PDF to PowerPoint

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Character formatting is used to change the appearance of individual words or phrases. Formatted text can direct the reader's attention to select sections of a document and highlight key information. There are quite a lot of forms of characters formatting that you can use in Word. In this article, you will learn how to apply various types of formatting to characters in Word in C# and VB.NET using Spire.Doc for .NET.

  • Font Name
  • Font Size
  • Font Color
  • Highlight Color
  • Bold
  • Italic
  • Underline
  • Strikethrough
  • Border
  • Shadow Effect
  • Emphasis Mark
  • Subscript and Superscript

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Apply Formatting to Characters in Word in C# and VB.NET

In order to apply formatting to a piece of text, you need to get the text in a TextRange and then format the characters within the TextRange through the CharacterFormat property. The following are the detailed steps.

  • Create a Document object.
  • Add a section to the document using Document.AddSection() method.
  • Add a paragraph to the section using Section.AddParagraph() method.
  • Append text to the paragraph using Paragraph.AppendText() method and return a TextRange object.
  • Apply formatting such as font name, font size, border and highlight color to the characters within the text range through TextRange.CharacterFormat property.
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace ApplyFormattingToCharacters
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document object
            Document document = new Document();

            //Add a section
            Section sec = document.AddSection();

            //Add a paragraph
            Paragraph paragraph = sec.AddParagraph();
            paragraph.AppendText("Here is a paragraph with various character styles. This is ");

            //Append text to the paragraph and return a TextRange object
            TextRange tr = paragraph.AppendText("text with strikeout");

            //Set the character format to strikeout via TextRange object
            tr.CharacterFormat.IsStrikeout = true;

            //Apply shadow effect to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text with shadow");
            tr.CharacterFormat.IsShadow = true;

            //Set font size 
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text in a large font size");
            tr.CharacterFormat.FontSize = 20;

            //Set font name 
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text in the font of Arial Black");
            tr.CharacterFormat.FontName = "Arial Black";

            //Set font color 
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text in red");
            tr.CharacterFormat.TextColor = Color.Red;

            //Apply bold & italic to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text in bold & italic");
            tr.CharacterFormat.Bold = true;
            tr.CharacterFormat.Italic = true;

            //Apply underline to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("underlined text");
            tr.CharacterFormat.UnderlineStyle = UnderlineStyle.Single;

            //Apply background color to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text with highlight color");
            tr.CharacterFormat.HighlightColor = Color.Green;

            //Apply border to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text with border");
            tr.CharacterFormat.Border.BorderType = Spire.Doc.Documents.BorderStyle.Single;
            tr.CharacterFormat.Border.Color = Color.Black;

            //Apply emphasis mark to text
            paragraph.AppendText(". This is ");
            tr = paragraph.AppendText("text with emphasis mark");
            tr.CharacterFormat.EmphasisMark = Emphasis.DotBelow;

            //Apply superscript to text
            paragraph.AppendText(". This is a math formula: a");
            tr = paragraph.AppendText("2");
            tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
            paragraph.AppendText(" + b");
            tr = paragraph.AppendText("2");
            tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
            paragraph.AppendText(" = c");
            tr = paragraph.AppendText("2");
            tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
            paragraph.AppendText(".");

            //Save to file
            document.SaveToFile("SetCharacterFormat.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Apply Formatting to Characters in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#: Word to Excel conversion

Word and Excel are designed for different types of content - Word focuses on documents, while Excel is better for structured data and analysis. Because of this, working with the same content across both formats isn't always straightforward.

If you have data in a Word document that you'd like to view or process in Excel, converting it manually can be tedious. With Spire.Doc for .NET, you can now convert Word directly to Excel, making it easier to reuse Word content in Excel.

In this tutorial, you'll learn how to convert Word to Excel in C#.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Basic Word to Excel Conversion in C#

Converting a Word document to Excel with Spire.Doc is straightforward:

  • Load a Word document using Document.LoadFromFile() method.

  • Save the document as an Excel file using Document.SaveToFile() method.

This works best when your Word document contains structured content, especially tables, which can be naturally mapped into spreadsheet cells.

using Spire.Doc;

namespace WordToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the Word document
            Document document = new Document();
            document.LoadFromFile("C:\\Users\\Tommy\\Desktop\\Sample.docx");

            // Save as Excel
            document.SaveToFile("C:\\Users\\Tommy\\Desktop\\Sample.xlsx", FileFormat.XLSX);

            document.Dispose();
        }
    }
}

Output Results:

Convert Word to Excel in C#

What Gets Converted Well?

When converting Word to Excel, it's important to understand how content is interpreted:

  • Tables in Word are converted into Excel worksheets with rows and columns preserved.
  • Paragraph text may be inserted into cells, but without strict structure.
  • Complex layouts (floating elements, multi-column sections) may not translate perfectly.
  • By default, each Section in a Word document is converted into a separate worksheet in Excel.

For best results, ensure your Word document uses clear table structures before conversion.

Advanced Word to Excel Conversion Scenarios

Once you understand the basic conversion process, you can handle more advanced scenarios depending on your needs.

Convert Only Tables from Word to Excel

If you only need structured data, extracting tables from a Word document is often more useful than converting the entire file. By default, all tables within the same section are placed into a single worksheet. To output each table into a separate worksheet, you can place each table into its own section before conversion.

To do this, you can work with the document structure and table objects:

  • Use section.Tables to access all tables within a section.
  • Use table.Clone() to create a copy of each table.
  • Create a new section for each table so that each one is mapped to a separate worksheet in Excel.

This approach gives you precise control over the output and ensures that only relevant data is included in the resulting Excel file.

using Spire.Doc;

class Program
{
    static void Main()
    {
        // Load the Word document
        Document doc = new Document();
        doc.LoadFromFile("G:/Documents/Sample84.docx");

        // Create a new document to store extracted tables
        Document tempDoc = new Document();

        // Iterate through all sections in the source document
        foreach (Section section in doc.Sections)
        {
            // Iterate through all tables in the current section
            foreach (Table table in section.Tables)
            {
                // Create a new section for each table (each section becomes a separate worksheet in Excel)
                Section tempSec = tempDoc.AddSection();
                
                // Clone the table and add it to the new section
                tempSec.Tables.Add(table.Clone());
            }
        }

        // Save as Excel file
        tempDoc.SaveToFile("Tables.xlsx", FileFormat.XLSX);
        
        // Close and release resources
        doc.Close();
        tempDoc.Close();
    }
}

C#: Convert only tables from Word to Excel

Note: Since each table is placed into its own section before conversion, each table will appear in a separate worksheet in the output Excel file.

Convert a Specific Page of a Word Document to Excel

In some cases, only a specific page contains the data you need — for example, a summary table on page 2 — use Document.ExtractPages() to isolate that page into a new Document object before converting. This avoids processing the entire file and gives you a cleaner, focused output. If you're only interested in structured data from that page, you can further extract tables from Word in C# before exporting.

using Spire.Doc;

namespace WordPageToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Load the Word document
            Document document = new Document();
            document.LoadFromFile("input.docx");

            // Extract the content of the specified page (e.g., page 1)
            Document pageDoc = document.ExtractPages(0, 1); // Retrieve page 1 (starting from index 0, retrieve page 1).

            // Save the extracted page as Excel
            pageDoc.SaveToFile("output.xlsx", FileFormat.XLSX); 

            document.Dispose();
            pageDoc.Dispose();
        }
    }
}

C#: Convert a specific page of a Word

Note: Page boundaries in Word are flow-based and can shift depending on font rendering. If the extracted page doesn't match what you see in Word, verify the page index by testing with a few values around your target.

Batch Convert Multiple Word Documents to Excel

To convert an entire folder of Word files, loop through each .docx file and apply the same conversion. This is useful for bulk migrations or scheduled processing pipelines.

This approach can be easily integrated into background jobs or automation workflows.

using Spire.Doc;
using System.IO;

namespace BatchWordToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get all Word files from the input folder
            string inputFolder = "inputDocs";
            string outputFolder = "outputExcels";
            Directory.CreateDirectory(outputFolder);

            string[] wordFiles = Directory.GetFiles(inputFolder, "*.docx");

            // Loop through each Word file and convert to Excel
            foreach (string filePath in wordFiles)
            {
                Document document = new Document();
                document.LoadFromFile(filePath);

                string fileName = Path.GetFileNameWithoutExtension(filePath);
                string outputPath = Path.Combine(outputFolder, fileName + ".xlsx");

                document.SaveToFile(outputPath, FileFormat.XLSX);
                document.Dispose();
            }
        }
    }
}

Tip: For large batches, consider wrapping the inner block in a try/catch so a single malformed file doesn't abort the entire run. If your workflow requires combining documents before conversion, learn how to merge Word documents in C#.

Notes and Best Practices

  • For best results, use well-structured tables in Word.
  • Avoid complex layouts like floating shapes or multi-column designs.
  • For large-scale processing, consider handling files in batches to optimize memory usage.

FAQs

Q1: Which Word file formats are supported for conversion?

A: Spire.Doc for .NET supports both .doc and .docx formats as input. You can load either format using Document.LoadFromFile() and the library will handle the rest automatically.

Q2: Will the original formatting be preserved after conversion?

A: The conversion focuses on exporting content into a spreadsheet format. Structured content like tables is usually preserved with good readability, while complex layouts may not be retained exactly as in Word.

Q3: Is this feature suitable for large documents?

A: Yes, but performance may vary depending on document size and complexity. For large files, it is recommended to optimize memory usage and process documents efficiently in your code.

Q4: Can I further customize the Excel output after conversion?

A: Yes. After saving the converted .xlsx file, you can open it with Spire.XLS for .NET to further customize the output, such as adjusting cell styles, fonts, colors, column widths, or adding formulas. The two libraries are designed to work together seamlessly.

Conclusion

In this article, you learned how to convert Word to Excel in C# using Spire.Doc for .NET, from basic document conversion to more advanced scenarios like page extraction and table-focused processing. For more control over the output, such as adjusting fonts, colors, or cell formatting - you can combine it with Spire.XLS for .NET.

You can also explore other conversion features, such as exporting Word documents to PDF, HTML, or images.

Get a Free License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Sometimes, you may need to perform specific operations on multiple shapes in Excel, such as adding styles, resizing, or moving them around. Grouping shapes can help you accomplish this task more easily and efficiently. Once shapes are grouped, they are treated as a single entity and can be manipulated at the same time. In this article, you will learn how to programmatically group or ungroup shapes in Excel in C# and VB.NET using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Group Shapes in Excel using C# and VB.NET

To group certain shapes in an Excel worksheet, you need to use the Worksheet.GroupShapeCollection property to return a GroupShapeCollection object, and then call the GroupShapeCollection.Group() method. The following are the detailed steps:

  • Initialize an instance of Workbook class.
  • Get the first worksheet by its index through Workbook.Worksheets[int] property.
  • Add several shapes to specific rows and columns in the worksheet using Worksheet.PrstGeomShapes.AddPrstGeomShape(int, int, int, int, PrstGeomShapeType) method.
  • Get the group shape collection of the worksheet through Worksheet.GroupShapeCollection property.
  • Group the shapes using GroupShapeCollection.Group(IShape[]) method.
  • Save the result document using Workbook.SaveToFile(string) method.
  • C#
  • VB.NET
using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.MergeSpreadsheet.Collections;
using System.Drawing;

namespace GroupShapes
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Add four shapes
            IPrstGeomShape shape1 = worksheet.PrstGeomShapes.AddPrstGeomShape(3, 3, 65, 50, PrstGeomShapeType.RoundRect);
            shape1.Fill.FillType = ShapeFillType.SolidColor;
            shape1.Fill.ForeColor = Color.Yellow;
            shape1.Line.Weight = 0.1;
            IPrstGeomShape shape2 = worksheet.PrstGeomShapes.AddPrstGeomShape(7, 3, 65, 50, PrstGeomShapeType.Ribbon);
            shape2.Fill.FillType = ShapeFillType.SolidColor;
            shape2.Fill.ForeColor = Color.Purple;
            shape2.Line.Weight = 0.1;
            IPrstGeomShape shape3 = worksheet.PrstGeomShapes.AddPrstGeomShape(3, 5, 65, 50, PrstGeomShapeType.Cloud);
            shape3.Fill.FillType = ShapeFillType.SolidColor;
            shape3.Fill.ForeColor = Color.LightGreen;
            shape3.Line.Weight = 0.1;
            IPrstGeomShape shape4 = worksheet.PrstGeomShapes.AddPrstGeomShape(7, 5, 65, 50, PrstGeomShapeType.Ellipse);
            shape4.Fill.FillType = ShapeFillType.SolidColor;
            shape4.Fill.ForeColor = Color.LightSkyBlue;
            shape4.Line.Weight = 0.1;

            //Group the shapes
            GroupShapeCollection groupShapeCollection = worksheet.GroupShapeCollection;
            groupShapeCollection.Group(new IShape[] { shape1, shape2, shape3, shape4});


            //Save the result file
            workbook.SaveToFile("GroupShapes.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Group or Ungroup Shapes in Excel

Ungroup Shapes in Excel using C# and VB.NET

To ungroup the grouped shapes in an Excel worksheet, you can use the GroupShapeCollection. UnGroupAll() method. After the shapes are ungrouped, you can manipulate them individually. The following are the detailed steps:

  • Initialize an instance of Workbook class.
  • Load an Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet by its index through Workbook.Worksheets[int] property.
  • Get the group shape collection of the worksheet through Worksheet.GroupShapeCollection property.
  • Ungroup all the grouped shapes using GroupShapeCollection.UnGroupAll() method.
  • Save the result document using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;
using Spire.Xls.Core.MergeSpreadsheet.Collections;

namespace UngroupShapes
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("GroupShapes.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];            

            //Ungroup the grouped shapes in the worksheet
            GroupShapeCollection groupShapeCollection = worksheet.GroupShapeCollection;
            groupShapeCollection.UnGroupAll();

            //Save the result file
            workbook.SaveToFile("UnGroupShapes.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Group or Ungroup Shapes in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

There are times when you need to create a PowerPoint document from a group of pre-created image files. As an example, you have been provided with some beautiful flyers by your company, and you need to combine them into a single PowerPoint document in order to display each picture in an orderly manner. In this article, you will learn how to convert image files (in any popular image format) to a PowerPoint document in C# and VB.NET using Spire.Presentation for .NET.

Install Spire.Presentation for .NET

To begin with, you need to add the DLL files included in the Spire.Presentation for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Presentation

Convert Image to Background in PowerPoint in C# and VB.NET

When images are converted as background of each slide in a PowerPoint document, they cannot be moved or scaled. The following are the steps to convert a set of images to a PowerPoint file as background images using Spire.Presentation for .NET.

  • Create a Presentation object.
  • Set the slide size type to Sreen16x9.
  • Get the image paths from a folder and save in a string array.
  • Traverse through the images.
  • Get a specific image and append it to the image collection of the document using Presentation.Images.Append() method.
  • Add a slide to the document using Presentation.Slides.Append() method.
  • Set the image as the background of the slide through the properties under ISlide.SlideBackground object.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
using System.IO;

namespace ConvertImageToBackground
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation object
            Presentation presentation = new Presentation();

            //Set slide size type
            presentation.SlideSize.Type = SlideSizeType.Screen16x9;

            //Remove the default slide
            presentation.Slides.RemoveAt(0);

            //Get file paths in a string array
            string[] picFiles = Directory.GetFiles(@"C:\Users\Administrator\Desktop\Images");

            //Loop through the images
            for (int i = 0; i < picFiles.Length; i++)
            {
                //Add a slide
                ISlide slide = presentation.Slides.Append();

                //Get a specific image
                string imageFile = picFiles[i];
                Image image = Image.FromFile(imageFile);

                //Append it to the image collection
                IImageData imageData = presentation.Images.Append(image);

                //Set the image as the background image of the slide
                slide.SlideBackground.Type = BackgroundType.Custom;
                slide.SlideBackground.Fill.FillType = FillFormatType.Picture;
                slide.SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch;
                slide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = imageData;
            }

            //Save to file
            presentation.SaveToFile("ImagesToBackground.pptx", FileFormat.Pptx2013);
        }
    }
}

C#/VB.NET: Convert Images (PNG, JPG, BMP, etc.) to PowerPoint

Convert Image to Shape in PowerPoint in C# and VB.NET

If you would like the images are moveable and resizable in the PowerPoint file, you can convert them as shapes. Below are the steps to convert images to shapes in a PowerPoint document using Spire.Presentation for .NET.

  • Create a Presentation object.
  • Set the slide size type to Sreen16x9.
  • Get the image paths from a folder and save in a string array.
  • Traverse through the images.
  • Get a specific image and append it to the image collection of the document using Presentation.Images.Append() method.
  • Add a slide to the document using Presentation.Slides.Append() method.
  • Add a shape with the size equal to the slide using ISlide.Shapes.AppendShape() method.
  • Fill the shape with the image through the properties under IAutoShape.Fill object.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
using System.IO;

namespace ConvertImageToShape
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation object
            Presentation presentation = new Presentation();

            //Set slide size type
            presentation.SlideSize.Type = SlideSizeType.Screen16x9;

            //Remove the default slide
            presentation.Slides.RemoveAt(0);

            //Get file paths in a string array
            string[] picFiles = Directory.GetFiles(@"C:\Users\Administrator\Desktop\Images");

            //Loop through the images
            for (int i = 0; i < picFiles.Length; i++)
            {
                //Add a slide
                ISlide slide = presentation.Slides.Append();

                //Get a specific image
                string imageFile = picFiles[i];
                Image image = Image.FromFile(imageFile);

                //Append it to the image collection
                IImageData imageData = presentation.Images.Append(image);

                //Add a shape with a size equal to the slide
                IAutoShape shape = slide.Shapes.AppendShape(ShapeType.Rectangle, new RectangleF(new PointF(0, 0), presentation.SlideSize.Size));

                //Fill the shape with image
                shape.Line.FillType = FillFormatType.None;
                shape.Fill.FillType = FillFormatType.Picture;
                shape.Fill.PictureFill.FillType = PictureFillType.Stretch;
                shape.Fill.PictureFill.Picture.EmbedImage = imageData;
            }

            //Save to file
            presentation.SaveToFile("ImageToShape.pptx", FileFormat.Pptx2013);
        }
    }
}

C#/VB.NET: Convert Images (PNG, JPG, BMP, etc.) to PowerPoint

Convert Image to PowerPoint with Customized Slide Size in C# and VB.NET

If the aspect ratio of your images is not 16:9, or they are not in a standard slide size, you can create slides based on the actual size of the pictures. This will prevent the image from being over stretched or compressed. The following are the steps to convert images to a PowerPoint document with customized slide size using Spire.Presentation for .NET.

  • Create a Presentation object.
  • Create a PdfUnitConvertor object, which is used to convert pixel to point.
  • Get the image paths from a folder and save in a string array.
  • Traverse through the images.
  • Get a specific image and append it to the image collection of the document using Presentation.Images.Append() method.
  • Get the image width and height, and convert them to point.
  • Set the slide size of the presentation based on the image size through Presentation.SlideSize.Size property.
  • Add a slide to the document using Presentation.Slides.Append() method.
  • Set the image as the background image of the slide through the properties under ISlide.SlideBackground object.
  • Save the document to a PowerPoint file using Presentation.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf.Graphics;
using Spire.Presentation;
using Spire.Presentation.Drawing;
using System.Drawing;
using System.IO;

namespace CustomSlideSize
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Presentation object
            Presentation presentation = new Presentation();

            //Remove the default slide
            presentation.Slides.RemoveAt(0);

            //Get file paths in a string array
            string[] picFiles = Directory.GetFiles(@""C:\Users\Administrator\Desktop\Images"");

            TextBox picBox = new TextBox();

            Graphics g = picBox.CreateGraphics();

            float dpiY = g.DpiY; 

            //Loop through the images 
            for (int i = 0; i < picFiles.Length; i++)
            {
                //Get a specific image 
                string imageFile = picFiles[i];
                Image image = Image.FromFile(imageFile);

                //Append it to the image collection 
                IImageData imageData = presentation.Images.Append(image);

                //Get image height and width in pixel
                int heightpixels = imageData.Height;
                int widthpixels = imageData.Width;

                //Convert pixel to point
                float widthPoint = widthpixels * 72.0f / dpiY;

                float heightPoint = heightpixels * 72.0f / dpiY;

                //Set slide size
                presentation.SlideSize.Size = new SizeF(widthPoint, heightPoint);

                //Add a slide
                ISlide slide = presentation.Slides.Append();

                //Set the image as the background image of the slide
                slide.SlideBackground.Type = BackgroundType.Custom;
                slide.SlideBackground.Fill.FillType = FillFormatType.Picture;
                slide.SlideBackground.Fill.PictureFill.FillType = PictureFillType.Stretch;
                slide.SlideBackground.Fill.PictureFill.Picture.EmbedImage = imageData;
            }

            //Save to file
            presentation.SaveToFile(""CustomizeSlideSize.pptx"", FileFormat.Pptx2013);
        }
    }
}

C#/VB.NET: Convert Images (PNG, JPG, BMP, etc.) to PowerPoint

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#/VB.NET: Create a Tagged PDF Document

2022-10-20 01:27:14 Written by Koohji

A tagged PDF (also known as PDF/UA) is a type of PDF that includes an underlying tag tree, similar to HTML, that defines the structure of the document. These tags can help screen readers to navigate throughout the document without any loss of information. This article introduces how to create a tagged PDF from scratch in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Create a Tagged PDF with Rich Elements

To add structure elements in a tagged PDF document, we must first create an object of PdfTaggedContent class. Then, add an element to the root using PdfTaggedContent.StructureTreeRoot.AppendChildElement() method. The following are the detailed steps to add a "heading" element to a tagged PDF using Spire.PDF for .NET.

  • Create a PdfDocument object and add a page to it using PdfDocument.Pages.Add() method.
  • Create an object of PdfTaggedContent class.
  • Make the document compliance to PDF/UA identification using PdfTaggedContent.SetPdfUA1Identification() method.
  • Add a "document" element to the root of the document using PdfTaggedContent.StructureTreeRoot.AppendChildElement() method.
  • Add a "heading" element under the "document" element using PdfStructureElement.AppendChildElement() method.
  • Add a start tag using PdfStructureElement.BeginMarkedContent() method, which indicates the beginning of the heading element.
  • Draw heading text on the page using PdfPageBase.Canvas.DrawString() method.
  • Add an end tag using PdfStructureElement.BeginMarkedContent() method, which implies the heading element ends here.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.

The following code snippet provides an example on how to create various elements including document, heading, paragraph, figure and table in a tagged PDF document in C# and VB.NET.

  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Interchange.TaggedPdf;
using Spire.Pdf.Tables;
using System.Data;
using System.Drawing;

namespace CreatePDFUA
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(20));          

            //Set tab order
            page.SetTabOrder(TabOrder.Structure);

            //Create an object of PdfTaggedContent class
            PdfTaggedContent taggedContent = new PdfTaggedContent(doc);

            //Set language and title for the document
            taggedContent.SetLanguage("en-US");
            taggedContent.SetTitle("test");

            //Set PDF/UA1 identification
            taggedContent.SetPdfUA1Identification();

            //Create font and brush
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", 14), true);
            PdfSolidBrush brush = new PdfSolidBrush(Color.Black);

            //Add a "document" element 
            PdfStructureElement document = taggedContent.StructureTreeRoot.AppendChildElement(PdfStandardStructTypes.Document);

            //Add a "heading" element
            PdfStructureElement heading1 = document.AppendChildElement(PdfStandardStructTypes.HeadingLevel1);
            heading1.BeginMarkedContent(page);      
            string headingText = "What Is a Tagged PDF?";
            page.Canvas.DrawString(headingText, font, brush, new PointF(0, 0));
            heading1.EndMarkedContent(page);

            //Add a "paragraph" element 
            PdfStructureElement paragraph = document.AppendChildElement(PdfStandardStructTypes.Paragraph);
            paragraph.BeginMarkedContent(page);
            string paragraphText = "“Tagged PDF” doesn’t seem like a life-changing term. But for some, it is. For people who are " +
                "blind or have low vision and use assistive technology (such as screen readers and connected Braille displays) to " +
                "access information, an untagged PDF means they are missing out on information contained in the document because assistive " +
                "technology cannot “read” untagged PDFs.  Digital accessibility has opened up so many avenues to information that were once " +
                "closed to people with visual disabilities, but PDFs often get left out of the equation.";
            RectangleF rect = new RectangleF(0, 30, page.Canvas.ClientSize.Width, page.Canvas.ClientSize.Height);
            page.Canvas.DrawString(paragraphText, font, brush, rect);
            paragraph.EndMarkedContent(page);

            //Add a "figure" element to 
            PdfStructureElement figure = document.AppendChildElement(PdfStandardStructTypes.Figure);
            figure.BeginMarkedContent(page);
            PdfImage image = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\pdfua.png");
            page.Canvas.DrawImage(image, new PointF(0, 150));
            figure.EndMarkedContent(page);

            //Add a "table" element
            PdfStructureElement table = document.AppendChildElement(PdfStandardStructTypes.Table);
            table.BeginMarkedContent(page);
            PdfTable pdfTable = new PdfTable();
            pdfTable.Style.DefaultStyle.Font = font;
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Name");
            dataTable.Columns.Add("Age");
            dataTable.Columns.Add("Sex");
            dataTable.Rows.Add(new string[] { "John", "22", "Male" });
            dataTable.Rows.Add(new string[] { "Katty", "25", "Female" });
            pdfTable.DataSource = dataTable;
            pdfTable.Style.ShowHeader = true;
            pdfTable.Draw(page.Canvas, new PointF(0, 280), 300f);
            table.EndMarkedContent(page);

            //Save the document to file
            doc.SaveToFile("CreatePDFUA.pdf");
        }
    }
}

C#/VB.NET: Create a Tagged PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#/VB.NET: Convert ODT to PDF

2022-09-20 01:05:19 Written by Koohji

ODT files are OpenDocument Text files created with word processing programs such as free OpenOffice Writer. Like DOCX files, ODT files can contain content like text, images, objects and styles, but they may not be readable by some people who don't have the appropriate application installed. If you plan to share an ODT file, it's best to convert it to pdf so everyone can access it. In this article, we will explain how to convert ODT to PDF in C# and VB.NET using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert ODT to PDF using C# and VB.NET

The following are the steps to convert an ODT file to PDF:

  • Create an instance of Document class.
  • Load an ODT file using Document.LoadFromFile() method.
  • Convert the ODT file to PDF using Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
  • VB.NET
using Spire.Doc;

namespace ConvertOdtToPdf
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document doc = new Document();
            //Load an ODT file
            doc.LoadFromFile("Sample.odt");

            //Save the ODT file to PDF
            doc.SaveToFile("OdtToPDF.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Convert ODT to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

C#/VB.NET: Rearrange Columns in Excel

2022-08-24 01:02:17 Written by Koohji

The proper adjustment of the columns' order in Excel can improve readability. For example, by setting the date data as the first column, we can quickly locate data based on a specific date. It is easy to move columns in MS Excel by using Shift and Drag. This article, however, focuses on how to rearrange columns in Excel in C# and VB.NET by using Spire.XLS for .NET.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Reorder Excel Columns in C# and VB.NET

The following are the steps to rearrange columns in Excel using Spire.XLS for .NET.

  • Create a Workbook object, and load a sample Excel file using Workbook.LoadFromFile() method.
  • Get the target worksheet using Workbook.Worksheets[index] property.
  • Specify the new column order in an int array.
  • Create a temporary sheet and copy the data from the target sheet into it.
  • Copy the columns from the temporary sheet to the target sheet and store them in the new order.
  • Remove the temporary sheet.
  • Save the workbook to another Excel file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using System.Linq;
using Spire.Xls;

namespace MoveColumn
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();

            //Load an Excel file
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");

            //Get the first worksheet
            Worksheet worksheet = workbook.Worksheets[0];

            //Set the new column order (the column index starts from 0)
            int[] newColumnOrder = new int[] { 3, 0, 1, 2, 4, 5 };

            //Add a temporary worksheet
            Worksheet newSheet = workbook.Worksheets.Add("temp");

            //Copy data from the first worksheet to the temporary sheet
            newSheet.CopyFrom(worksheet);

            //Loop through the newColumnOrder array
            for (int i = 0; i < newColumnOrder.Count(); i++)
            {
                //Copy the column from the temporary sheet to the first sheet
                newSheet.Columns[newColumnOrder[i]].Copy(worksheet.Columns[i], true, true);

                //Set the width of a certain column the first sheet to that of the temporary sheet
                worksheet.Columns[i].ColumnWidth = newSheet.Columns[newColumnOrder[i]].ColumnWidth;
            }

            //Remove temporary sheet
            workbook.Worksheets.Remove(newSheet);

            //Save the workbook to another Excel file
            workbook.SaveToFile("MoveColumn.xlsx", FileFormat.Version2016);
        }
    }
}

C#/VB.NET: Rearrange Columns in Excel

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 8 of 95
page 8