13 December 2024

Top 5 .NET Projects Wrapped for Python Using Cs2Python

CodePorting.Wrapper Cs2Python is a tool that enables wrapping ready-made .NET projects written in C# into modules compatible with Python. This simplifies the use of existing .NET projects in Python without the need to rewrite them from scratch or translate their source code. Using this tool saves developers time and effort, ensuring high performance of the product in Python. In this article, we will look at the five most popular .NET projects wrapped for use in Python using the CodePorting.Wrapper Cs2Python tool.

Adapting Aspose Libraries for Python

Aspose is a leading company specializing in the development of high-quality libraries for working with various file formats. Their products are widely recognized among developers for their reliability and rich functionality. Initially, all these libraries were created in C# and over time they have become indispensable tools for .NET developers worldwide.

To support Python, it was decided to automatically generate wrapper code that allows the existing .NET assembly to be used within the Python environment. To achieve this, the CodePorting.Wrapper Cs2Python tool was developed, which makes it easy to adapt .NET projects for use in Python.

We will review the five most popular Aspose products for Python based on the number of downloads from PyPI:

Product Number of Downloads
1 Aspose.Words 1,287,268
2 Aspose.Slides 488,062
3 Aspose.Cells 286,120
4 Aspose.PDF 177,246
5 Aspose.Email 136,465

1. Aspose.Words

Number of lines of C# source code
4,100,000

Aspose.Words is a powerful library for working with Word documents, providing a wide range of features for creating, editing, converting, and rendering documents. It supports many formats, including DOC, DOCX, PDF, HTML, and more. Aspose.Words enables developers to automate document processing without the need to use Microsoft Word or other third-party applications.

The first version of the Python-wrapped library was released in 2021. Since then, it has continued to evolve alongside the increasing capabilities of the Cs2Python wrapping tool. The entire Python API is automatically generated based on the C# API of the library.

Comparison of C# and Python APIs

  1. Creating a New Document and Adding Text

Example in C#:

using Aspose.Words;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Hello, World!");
doc.Save("HelloWorld.docx");

Example in Python:

import aspose.words as aw

doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.writeln("Hello, World!")
doc.save("HelloWorld.docx")
  1. Converting a Document from DOCX to PDF

Example in C#:

using Aspose.Words;

Document doc = new Document("Document.docx");
doc.Save("Document.pdf");

In Python:

import aspose.words as aw

doc = aw.Document("Document.docx")
doc.save("Document.pdf")
  1. Merging Two Documents

Example in C#:

using Aspose.Words;

Document doc1 = new Document("Document1.docx");
Document doc2 = new Document("Document2.docx");

DocumentBuilder builder = new DocumentBuilder(doc1);
builder.MoveToDocumentEnd();
builder.InsertDocument(doc2, ImportFormatMode.KeepSourceFormatting);

doc1.Save("MergedDocument.docx");

In Python:

import aspose.words as aw

doc1 = aw.Document("Document1.docx")
doc2 = aw.Document("Document2.docx")

builder = aw.DocumentBuilder(doc1)
builder.move_to_document_end()
builder.insert_document(doc2, aw.ImportFormatMode.KEEP_SOURCE_FORMATTING)

doc1.save("MergedDocument.docx")

As we can see, the APIs in both languages are very similar, which makes it easier for developers to transition between C# and Python. Additionally, it simplifies the documentation and maintenance of Aspose libraries. Now, thanks to the CodePorting.Wrapper Cs2Python tool, developers can utilize the powerful capabilities of Aspose.Words in their Python projects.

2. Aspose.Slides

Number of lines of C# source code
2,860,000

Aspose.Slides is a powerful library for working with presentations, allowing developers to create, modify, convert, and render presentations without the need for applications like Microsoft PowerPoint. It supports a wide range of formats, including PPT, PPTX, PDF, HTML, and more.

The first version of the Python-wrapped library was released in 2021 and was immediately well-received by users. Let's compare the original C# API and the automatically generated Python API.

Code Examples: Comparing C# and Python APIs

  1. Creating a New Presentation

In C#:

using Aspose.Slides;

Presentation pres = new Presentation();
pres.Save("NewPresentation.pptx", SaveFormat.Pptx);

In Python:

import aspose.slides as slides

pres = slides.Presentation()
pres.save("NewPresentation.pptx", slides.SaveFormat.Pptx)
  1. Adding a Slide

In C#:

using Aspose.Slides;

Presentation pres = new Presentation("ExistingPresentation.pptx");

ISlide slide = pres.Slides.AddEmptySlide(pres.LayoutSlides[0]);
IAutoShape textbox = slide.Shapes.AddAutoShape(ShapeType.Rectangle, 50, 50, 500, 200);
textbox.TextFrame.Text = "Hello, Aspose.Slides!";

pres.Save("UpdatedPresentation.pptx", SaveFormat.Pptx);

In Python:

import aspose.slides as slides

pres = slides.Presentation("ExistingPresentation.pptx")

slide = pres.slides.add_empty_slide(pres.layout_slides[0])
textbox = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 50, 500, 200)
textbox.text_frame.text = "Hello, Aspose.Slides!"

pres.save("UpdatedPresentation.pptx", slides.SaveFormat.Pptx)
  1. Converting to PDF

In C#:

using Aspose.Slides;

Presentation pres = new Presentation("ExistingPresentation.pptx");
pres.Save("ConvertedPresentation.pdf", SaveFormat.Pdf);

In Python:

import aspose.slides as slides

pres = slides.Presentation("ExistingPresentation.pptx")
pres.save("ConvertedPresentation.pdf", slides.SaveFormat.Pdf)

As we can see, the difference lies only in the coding style unique to each programming language.

3. Aspose.Cells

Number of lines of C# source code
600,000

Aspose.Cells is a powerful API for working with Excel files, enabling developers to create, edit, format, and convert spreadsheets in their applications, supporting a wide range of formats including XLS, XLSX, CSV, PDF, and more.

Aspose.Cells can handle large volumes of data in spreadsheets, which places high demands on its performance. By wrapping the high-performance compiled C# code, this performance is maintained when using the library in Python. Translating its code to Python could significantly reduce the speed of operations.

Example in C#:

using Aspose.Cells;
using System;

Workbook workbook = new Workbook("HugeDataWithComplexFormulas.xlsx");
workbook.CalculateFormula();

Worksheet sheet = workbook.Worksheets[0];
Cell resultCell = sheet.Cells["A1"];
Console.WriteLine("Calculation result: " + resultCell.Value);

Example in Python:

import aspose.cells as cells

workbook = cells.Workbook("HugeDataWithComplexFormulas.xlsx")
workbook.calculate_formula()

sheet = workbook.worksheets[0]
result_cell = sheet.cells.get("A1")
print("Calculation result: ", result_cell.value)

This code illustrates the use of Aspose.Cells for processing large volumes of data and calculating formulas in both C# and Python. The calculate_formula method performs significant work, ensuring the correct calculation of all formulas in the spreadsheet without loss of performance in Python.

4. Aspose.PDF

Number of lines of C# source code
3,655,000

Aspose.PDF is a powerful library for working with PDF documents, enabling developers to programmatically create, read, edit, and convert PDF documents.

As we can see, Aspose.PDF is a large and complex project with an extensive codebase in C#. The library methods can return not only simple data types but also complex structures such as collections and objects. One of the strong points of the CodePorting.Wrapper Cs2Python tool is its ability to support such data types in Python.

Example in C#:

using Aspose.Pdf;
using Aspose.Pdf.Text;
using System;
using System.Collections.Generic;

Document document = new Document("Sample.pdf");
Page page = document.Pages[1];

ImagePlacementAbsorber imageAbsorber = new ImagePlacementAbsorber();
page.Accept(imageAbsorber);

// Retrieve the first three images from the current page
List<ImagePlacement> images = imageAbsorber.ImagePlacements.Take(3).ToList();

foreach (ImagePlacement image in images)
{
    Console.WriteLine("Image found at: " + image.Rectangle);
}

In Python:

import aspose.pdf as pdf

document = pdf.Document("Sample.pdf")
page = document.pages[1]

image_placement_absorber = pdf.ImagePlacementAbsorber()
page.accept(image_placement_absorber)

# Retrieve the first three images from the current page
images = image_placement_absorber.image_placements[:3]

for image in images:
    print("Image found at:", image.rectangle)

Collections passed between the wrapped library and Python code support all standard Python methods and operations for sequences. This includes methods such as pop, index, count, sort, reverse, copy, append, remove, clear, contains, as well as support for iteration using __iter__ and accessing elements via square brackets ([]). This makes interacting with collections from the wrapped libraries as convenient and intuitive as working with any other standard collections in the language.

5. Aspose.Email

Number of lines of C# source code
397,000

Aspose.Email is a library for working with email, supporting a wide range of usage scenarios and protocols such as SMTP, POP3, IMAP, Exchange Web Services (EWS), WebDav, and others.

Comparison of C# and Python APIs

  1. Creating and Sending an Email

In C#:

using Aspose.Email;
using Aspose.Email.Clients.Smtp;

var message = new MailMessage();
message.From = new MailAddress("sender@example.com");
message.To.Add(new MailAddress("receiver@example.com"));
message.Subject = "Test Email";
message.Body = "This is a test email sent using Aspose.Email.";

var client = new SmtpClient("smtp.server.com", 25, "username", "password");
client.Send(message);

In Python:

import aspose.email as ae

message = ae.MailMessage()
message.from_address = ae.MailAddress("sender@example.com")
message.to.append(ae.MailAddress("receiver@example.com"))
message.subject = "Test Email"
message.body = "This is a test email sent using Aspose.Email."

client = ae.SmtpClient("smtp.server.com", 25, "username", "password")
client.send(message)
  1. Reading a PST File

In C#:

using Aspose.Email;
using Aspose.Email.Storage.Pst;
using System;

void PrintFolderInfo(FolderInfo folder)
{
    Console.WriteLine($"Folder: {folder.DisplayName}, Message Count: {folder.ContentCount}");
    foreach (var subFolder in folder.GetSubFolders())
    {
        PrintFolderInfo(subFolder);
    }
}

var personalStorage = PersonalStorage.FromFile("path/to/file.pst");
PrintFolderInfo(personalStorage.RootFolder);

In Python:

import aspose.email as ae
import aspose.email.storage.pst as pst

def print_folder_info(folder):
    print(f"Folder: {folder.display_name}, Message Count: {folder.content_count}")
    for sub_folder in folder.get_sub_folders():
        print_folder_info(sub_folder)

personal_storage = pst.PersonalStorage.from_file("path/to/file.pst")
print_folder_info(personal_storage.root_folder)

In this example, we recursively traverse all folders in the PST file and output the number of messages in each folder using the FolderInfo.ContentCount property (FolderInfo.content_count in Python).

As we can see, the Python API interface is once again identical to the C# API interface. This is achieved through the automatic creation of an intermediate layer of code that implements wrappers or bindings for classes, methods, and properties in Python. These bindings allow access to the functionality written in C# from the Python environment.

Conclusion

In conclusion, we would like to highlight the key advantages provided by wrapping .NET libraries for Python using the CodePorting.Wrapper Cs2Python tool:

  1. Preservation of Functionality: Wrapping allows the use of all features and functions of the original .NET library in Python without losing performance and functionality.
  2. Time and Resource Savings: Instead of rewriting code from scratch, developers can quickly wrap existing .NET libraries for use in Python, significantly reducing development time.
  3. Wide Compatibility: Wrapped libraries can run on various platforms such as Windows, Linux, and macOS.
  4. Automatic API Generation: The entire Python API is automatically generated based on the C# API of the library, simplifying the integration process and ensuring functional consistency.

If you would like to successfully wrap your enterprise-level .NET project for use in Python, please contact us, and we will be happy to help you achieve your goals!

Related News

Related Articles