Convertir correo electrónico a PDF: métodos universales y de programación
Tabla de contenidos
Instalar con Nuget
Install-Package Spire.Email Install-Package Spire.Doc

Los correos electrónicos a menudo contienen información crucial: contratos, recibos, itinerarios de viaje, actualizaciones de proyectos o mensajes emotivos que desea conservar para siempre. Pero depender únicamente de su bandeja de entrada para el almacenamiento a largo plazo es arriesgado. Las cuentas son hackeadas, los servicios cambian y los correos electrónicos pueden eliminarse accidentalmente. Convertir correos electrónicos a PDF resuelve esto creando documentos universalmente accesibles, perfectos para registros, pruebas legales o para compartir con clientes.
Esta guía explora enfoques tanto fáciles de usar como programáticos para guardar archivos de correo electrónico (MSG, EML) como archivos PDF.
- Cómo convertir un correo electrónico a PDF: Métodos universales
- Convertir correo electrónico a PDF en C#: Enfocado en desarrolladores
- ¿Qué método debería elegir?
- Conclusión
Cómo convertir un correo electrónico a PDF: Métodos universales
Los métodos universales son ideales para usuarios que no quieren escribir código. Aquí están los enfoques más comunes de conversión de correo electrónico a PDF:
Método 1: Función integrada "Imprimir"
Este es el método más fiable y ampliamente aplicable en computadoras de escritorio (Windows, macOS, Linux) y clientes de correo electrónico (Webmail, Outlook, Apple Mail).
1. Abra el correo electrónico
2. Encuentre la opción de Imprimir:
- Webmail (Gmail, Outlook.com, Yahoo): Busque el icono de la impresora o haga clic en el menú de tres puntos y seleccione "Imprimir".
- Clientes de escritorio (Outlook, Apple Mail): Vaya a “Archivo > Imprimir”, o use el atajo de teclado “Ctrl+P” (Windows) / “Cmd+P” (Mac).
3. Elija la impresora PDF:
- "Guardar como PDF" (común en Mac, navegador Chrome)
- "Microsoft Print to PDF" (predeterminado de Windows)
- "Adobe PDF" (si Adobe Acrobat está instalado)
4. Configure los ajustes (opcional):
- Establezca el tamaño de página, la orientación, los márgenes, etc.
- Desactive los encabezados/pies de página para una apariencia más limpia, que contenga solo el contenido del correo electrónico.
5. Guarde en PDF:
- Haga clic en "Imprimir", "Guardar" o similar.
- Nombre su archivo, elija una ubicación para guardarlo y haga clic en "Guardar".

Método 2: Convertidores en línea gratuitos (usar con precaución)
¿Necesita convertir correos electrónicos a PDF sin instalar software? Puede usar Zamzar, un convertidor gratuito que le permite convertir archivos .msg/.eml:
Pasos:
- Visite Zamzar.
- Cargue su archivo de correo electrónico.
- Seleccione PDF como formato de salida y haga clic en Convertir.
Nota de seguridad: Evite cargar correos electrónicos confidenciales en herramientas en línea. Utilice métodos sin conexión para datos sensibles.
Convertir correo electrónico a PDF en C#: Enfocado en desarrolladores
Para los desarrolladores que necesitan automatización, procesamiento por lotes o integración en flujos de trabajo de .NET, use Spire.Doc for .NET junto con la biblioteca Spire.Email for .NET para lograr sin esfuerzo la conversión de MSG o EML a PDF en C#.
Configuración:
Instale los paquetes de NuGet:
Install-Package Spire.Email
Install-Package Spire.Doc
A continuación se muestra el código C# para convertir un archivo msg de Outlook a PDF.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Email;
namespace EmailToPdf
{
class Program
{
static void Main(string[] args)
{
// Cargar un archivo de correo electrónico (.msg o .eml)
MailMessage mail = MailMessage.Load("sample.msg", MailMessageFormat.Msg);
// Analizar el contenido del correo electrónico y devolverlo en formato HTML
string htmlBody = mail.BodyHtml;
// Crear un documento de Word
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
// Agregar el contenido HTML al documento
paragraph.AppendHTML(htmlBody);
// Convertir al formato PDF
doc.SaveToFile("EmailToPdf.pdf", FileFormat.PDF);
}
}
}
Pasos clave:
- Cargar el correo electrónico: El método MailMessage.Load() lee un archivo de correo electrónico (.msg o .eml) en un objeto MailMessage.
- Extraer contenido HTML: El cuerpo HTML del correo electrónico se recupera a través de la propiedad MailMessage.BodyHtml.
- Crear un documento: Se crea una instancia de un documento de Word usando Spire.Doc.
- Agregar HTML al documento: El contenido HTML se agrega al documento usando Paragraph.AppendHTML().
- Guardar como PDF: El documento se guarda como PDF usando Document.SaveToFile().
Salida:

¿Qué método debería elegir?
| Escenario | Enfoque recomendado |
| Conversiones únicas | Función integrada Imprimir a PDF |
| Trabajos por lotes no sensibles | Herramientas en línea de confianza |
| Flujos de trabajo automatizados/ correos electrónicos sensibles | Bibliotecas Spire (C#/.NET) |
Conclusión
Ya sea que necesite una conversión manual rápida o una solución automatizada para su aplicación, convertir correos electrónicos a PDF es sencillo con las herramientas adecuadas. Los métodos universales son excelentes para conversiones únicas, mientras que la programación en C# proporciona escalabilidad y capacidades de integración para los desarrolladores. Elija el enfoque que mejor se adapte a sus necesidades para asegurarse de que sus correos electrónicos importantes se conserven de manera efectiva.
LEA TAMBIÉN:
E-Mail in PDF umwandeln – Universelle und programmatische Methoden
Inhaltsverzeichnis
Installation mit Nuget
Install-Package Spire.Email Install-Package Spire.Doc

E-Mails enthalten oft wichtige Informationen: Verträge, Quittungen, Reisepläne, Projektaktualisierungen oder herzliche Nachrichten, die Sie für immer aufbewahren möchten. Sich jedoch ausschließlich auf Ihren Posteingang für die langfristige Speicherung zu verlassen, ist riskant. Konten werden gehackt, Dienste ändern sich und E-Mails können versehentlich gelöscht werden. Das Konvertieren von E-Mails in PDF löst dieses Problem, indem universell zugängliche Dokumente erstellt werden, die sich perfekt für Aufzeichnungen, rechtliche Beweise oder die Weitergabe an Kunden eignen.
Diese Anleitung untersucht sowohl benutzerfreundliche als auch programmatische Ansätze zum Speichern von E-Mail-Dateien (MSG, EML) als PDF-Dateien.
- Wie man E-Mails in PDF konvertiert: Universelle Methoden
- E-Mail in PDF in C# konvertieren: Entwicklerfokus
- Welche Methode sollten Sie wählen?
- Fazit
Wie man E-Mails in PDF konvertiert: Universelle Methoden
Universelle Methoden sind ideal für Benutzer, die keinen Code schreiben möchten. Hier sind die gängigsten Ansätze zur Konvertierung von E-Mails in PDF:
Methode 1: Integrierte „Drucken“-Funktion
Dies ist die zuverlässigste und am weitesten verbreitete Methode auf Desktops (Windows, macOS, Linux) und in E-Mail-Clients (Webmail, Outlook, Apple Mail).
1. Öffnen Sie die E-Mail
2. Finden Sie die Druckoption:
- Webmail (Gmail, Outlook.com, Yahoo): Suchen Sie nach dem Druckersymbol oder klicken Sie auf das Drei-Punkte-Menü und wählen Sie „Drucken“.
- Desktop-Clients (Outlook, Apple Mail): Gehen Sie zu „Datei > Drucken“ oder verwenden Sie die Tastenkombination „Strg+P“ (Windows) / „Cmd+P“ (Mac).
3. Wählen Sie den PDF-Drucker:
- „Als PDF speichern“ (üblich auf Mac, Chrome-Browser)
- „Microsoft Print to PDF“ (Windows-Standard)
- „Adobe PDF“ (wenn Adobe Acrobat installiert ist)
4. Einstellungen konfigurieren (optional):
- Stellen Sie Seitengröße, Ausrichtung, Ränder usw. ein.
- Deaktivieren Sie Kopf-/Fußzeilen für ein saubereres Erscheinungsbild, das nur den E-Mail-Inhalt enthält.
5. Als PDF speichern:
- Klicken Sie auf „Drucken“, „Speichern“ oder Ähnliches.
- Benennen Sie Ihre Datei, wählen Sie einen Speicherort und klicken Sie auf „Speichern“.

Methode 2: Kostenlose Online-Konverter (mit Vorsicht verwenden)
Müssen Sie E-Mails in PDFs konvertieren, ohne Software zu installieren? Sie können Zamzar verwenden, einen kostenlosen Konverter, mit dem Sie .msg/.eml-Dateien konvertieren können:
Schritte:
- Besuchen Sie Zamzar.
- Laden Sie Ihre E-Mail-Datei hoch.
- Wählen Sie PDF als Ausgabeformat und klicken Sie auf Konvertieren.
Sicherheitshinweis: Vermeiden Sie das Hochladen vertraulicher E-Mails auf Online-Tools. Verwenden Sie Offline-Methoden für sensible Daten.
E-Mail in PDF in C# konvertieren: Entwicklerfokus
Für Entwickler, die Automatisierung, Stapelverarbeitung oder Integration in .NET-Workflows benötigen, verwenden Sie Spire.Doc for .NET in Verbindung mit der Bibliothek Spire.Email for .NET, um mühelos eine MSG- oder EML-zu-PDF-Konvertierung in C# zu erreichen.
Einrichtung:
Installieren Sie NuGet-Pakete:
Install-Package Spire.Email
Install-Package Spire.Doc
Unten finden Sie den C#-Code zum Konvertieren einer Outlook-MSG-Datei in PDF.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Email;
namespace EmailToPdf
{
class Program
{
static void Main(string[] args)
{
// Eine E-Mail-Datei laden (.msg oder .eml)
MailMessage mail = MailMessage.Load("sample.msg", MailMessageFormat.Msg);
// E-Mail-Inhalt analysieren und im HTML-Format zurückgeben
string htmlBody = mail.BodyHtml;
// Ein Word-Dokument erstellen
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
// Den HTML-Inhalt zum Dokument hinzufügen
paragraph.AppendHTML(htmlBody);
// In das PDF-Format konvertieren
doc.SaveToFile("EmailToPdf.pdf", FileFormat.PDF);
}
}
}
Wichtige Schritte:
- E-Mail laden: Die Methode MailMessage.Load() liest eine E-Mail-Datei (.msg oder .eml) in ein MailMessage-Objekt.
- HTML-Inhalt extrahieren: Der HTML-Body der E-Mail wird über die Eigenschaft MailMessage.BodyHtml abgerufen.
- Dokument erstellen: Ein Word-Dokument wird mit Spire.Doc instanziiert.
- HTML zum Dokument hinzufügen: Der HTML-Inhalt wird mit Paragraph.AppendHTML() an das Dokument angehängt.
- Als PDF speichern: Das Dokument wird mit Document.SaveToFile() als PDF gespeichert.
Ausgabe:

Welche Methode sollten Sie wählen?
| Szenario | Empfohlener Ansatz |
| Einzelne Konvertierungen | Integrierte Druck-zu-PDF-Funktion |
| Nicht sensible Stapelaufträge | Vertrauenswürdige Online-Tools |
| Automatisierte Workflows/ sensible E-Mails | Spire-Bibliotheken (C#/.NET) |
Fazit
Egal, ob Sie eine schnelle manuelle Konvertierung oder eine automatisierte Lösung für Ihre Anwendung benötigen, das Konvertieren von E-Mails in PDF ist mit den richtigen Werkzeugen unkompliziert. Universelle Methoden eignen sich hervorragend für einmalige Konvertierungen, während die C#-Programmierung Skalierbarkeits- und Integrationsmöglichkeiten für Entwickler bietet. Wählen Sie den Ansatz, der am besten zu Ihren Bedürfnissen passt, um sicherzustellen, dass Ihre wichtigen E-Mails effektiv erhalten bleiben.
AUCH LESEN:
Преобразование электронной почты в PDF — универсальные и программные методы
Оглавление
Установка через Nuget
Install-Package Spire.Email Install-Package Spire.Doc

Электронные письма часто содержат важную информацию: контракты, квитанции, маршруты путешествий, обновления проектов или душевные сообщения, которые вы хотите сохранить навсегда. Но полагаться исключительно на свой почтовый ящик для долгосрочного хранения рискованно. Учетные записи взламываются, сервисы меняются, а письма могут быть случайно удалены. Преобразование электронных писем в PDF решает эту проблему, создавая универсально доступные документы, идеально подходящие для записей, юридических доказательств или обмена с клиентами.
В этом руководстве рассматриваются как удобные для пользователя, так и программные подходы к сохранению файлов электронной почты (MSG, EML) в виде файлов PDF.
- Как преобразовать электронное письмо в PDF: универсальные методы
- Преобразование электронной почты в PDF на C#: для разработчиков
- Какой метод выбрать?
- Заключение
Как преобразовать электронное письмо в PDF: универсальные методы
Универсальные методы идеально подходят для пользователей, которые не хотят писать код. Вот наиболее распространенные подходы к преобразованию электронной почты в PDF:
Метод 1: Встроенная функция «Печать»
Это самый надежный и широко применимый метод на настольных компьютерах (Windows, macOS, Linux) и в почтовых клиентах (веб-почта, Outlook, Apple Mail).
1. Откройте электронное письмо
2. Найдите опцию печати:
- Веб-почта (Gmail, Outlook.com, Yahoo): Найдите значок принтера или нажмите меню с тремя точками и выберите «Печать».
- Клиенты для настольных компьютеров (Outlook, Apple Mail): Перейдите в «Файл > Печать» или используйте сочетание клавиш «Ctrl+P» (Windows) / «Cmd+P» (Mac).
3. Выберите PDF-принтер:
- «Сохранить как PDF» (распространено на Mac, в браузере Chrome)
- «Microsoft Print to PDF» (по умолчанию в Windows)
- «Adobe PDF» (если установлен Adobe Acrobat)
4. Настройте параметры (необязательно):
- Установите размер страницы, ориентацию, поля и т. д.
- Отключите верхние/нижние колонтитулы для более чистого вида, содержащего только содержимое письма.
5. Сохраните в PDF:
- Нажмите «Печать», «Сохранить» или аналогичную кнопку.
- Назовите файл, выберите место для сохранения и нажмите «Сохранить».

Метод 2: Бесплатные онлайн-конвертеры (использовать с осторожностью)
Нужно конвертировать электронные письма в PDF без установки программного обеспечения? Вы можете использовать Zamzar, бесплатный конвертер, который позволяет конвертировать файлы .msg/.eml:
Шаги:
- Посетите Zamzar.
- Загрузите свой файл электронной почты.
- Выберите PDF в качестве выходного формата и нажмите «Конвертировать».
Примечание по безопасности: избегайте загрузки конфиденциальных писем в онлайн-инструменты. Используйте офлайн-методы для конфиденциальных данных.
Преобразование электронной почты в PDF на C#: для разработчиков
Для разработчиков, нуждающихся в автоматизации, пакетной обработке или интеграции в рабочие процессы .NET, используйте Spire.Doc for .NET в сочетании с библиотекой Spire.Email for .NET, чтобы без труда выполнять преобразование MSG или EML в PDF на C#.
Настройка:
Установите пакеты NuGet:
Install-Package Spire.Email
Install-Package Spire.Doc
Ниже приведен код на C# для преобразования файла .msg Outlook в PDF.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Email;
namespace EmailToPdf
{
class Program
{
static void Main(string[] args)
{
// Загрузить файл электронной почты (.msg или .eml)
MailMessage mail = MailMessage.Load("sample.msg", MailMessageFormat.Msg);
// Проанализировать содержимое письма и вернуть его в формате HTML
string htmlBody = mail.BodyHtml;
// Создать документ Word
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
// Добавить содержимое HTML в документ
paragraph.AppendHTML(htmlBody);
// Преобразовать в формат PDF
doc.SaveToFile("EmailToPdf.pdf", FileFormat.PDF);
}
}
}
Ключевые шаги:
- Загрузить письмо: Метод MailMessage.Load() считывает файл электронной почты (.msg или .eml) в объект MailMessage.
- Извлечь содержимое HTML: HTML-тело письма извлекается через свойство MailMessage.BodyHtml.
- Создать документ: Документ Word создается с помощью Spire.Doc.
- Добавить HTML в документ: Содержимое HTML добавляется в документ с помощью Paragraph.AppendHTML().
- Сохранить как PDF: Документ сохраняется в формате PDF с помощью Document.SaveToFile().
Вывод:

Какой метод выбрать?
| Сценарий | Рекомендуемый подход |
| Единичные преобразования | Встроенная функция «Печать в PDF» |
| Пакетные задания с неконфиденциальными данными | Надежные онлайн-инструменты |
| Автоматизированные рабочие процессы/ конфиденциальные письма | Библиотеки Spire (C#/.NET) |
Заключение
Независимо от того, нужна ли вам быстрая ручная конвертация или автоматизированное решение для вашего приложения, преобразование электронных писем в PDF является простым с правильными инструментами. Универсальные методы отлично подходят для одноразовых преобразований, в то время как программирование на C# обеспечивает масштабируемость и возможности интеграции для разработчиков. Выберите подход, который наилучшим образом соответствует вашим потребностям, чтобы обеспечить эффективное сохранение ваших важных писем.
ТАКЖЕ ЧИТАЙТЕ:
Convert Email to PDF - Universal & Programming Methods
Table of Contents
Install with Nuget
Install-Package Spire.Email Install-Package Spire.Doc

Emails often contain crucial information: contracts, receipts, travel itineraries, project updates, or heartfelt messages you want to keep forever. But relying solely on your inbox for long-term storage is risky. Accounts get hacked, services change, and emails can accidentally be deleted. Converting emails to PDF solves this by creating universally accessible documents perfect for records, legal evidence, or client sharing.
This guide explores both user-friendly and programmatic approaches to save email files (MSG, EML) as PDF files.
- How to Convert Email to PDF: Universal Methods
- Convert Email to PDF in C#: Developer-Focused
- Which Method Should You Choose?
- Conclusion
How to Convert Email to PDF: Universal Methods
Universal methods are ideal for users who don’t want to write code. Here are the most common email-to-PDF conversion approaches:
Method 1: Built-in "Print" Function
This is the most reliable and widely applicable method across desktops (Windows, macOS, Linux) and email clients (Webmail, Outlook, Apple Mail).
1. Open the Email
2. Find the Print Option:
- Webmail (Gmail, Outlook.com, Yahoo): Look for the printer icon or click the three-dot menu and select "Print."
- Desktop Clients (Outlook, Apple Mail): Go to “File > Print”, or use the “Ctrl+P” (Windows) / “Cmd+P” (Mac) keyboard shortcut.
3. Choose the PDF Printer:
- "Save as PDF" (common on Mac, Chrome browser)
- "Microsoft Print to PDF" (Windows default)
- "Adobe PDF" (if Adobe Acrobat is installed)
4. Configure Settings (Optional):
- Set the page size, orientation, margins, etc.
- Disable headers/footers for a cleaner look, containing just the email content.
5. Save to PDF:
- Click "Print," "Save," or similar.
- Name your file, choose a save location, and click "Save."

Method 2: Free Online Converters (Use with Caution)
Need to convert emails to PDFs without installing software? You can use Zamzar, a free converter that allows you to convert .msg/.eml files:
Steps:
- Visit Zamzar.
- Upload your email file.
- Select PDF as the output format and click Convert.
Security Note: Avoid uploading confidential emails to online tools. Use offline methods for sensitive data.
Convert Email to PDF in C#: Developer-Focused
For developers needing automation, batch processing, or integration into .NET workflows, use Spire.Doc for .NET in conjunction with Spire.Email for .NET library to effortlessly achieve MSG or EML to PDF conversion in C#.
Setup:
Install NuGet packages:
Install-Package Spire.Email
Install-Package Spire.Doc
Below is the C# code to convert an Outlook msg file to PDF.
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Email;
namespace EmailToPdf
{
class Program
{
static void Main(string[] args)
{
// Load an email file (.msg or .eml)
MailMessage mail = MailMessage.Load("sample.msg", MailMessageFormat.Msg);
// Parse email content and return it in HTML format
string htmlBody = mail.BodyHtml;
// Create a Word document
Document doc = new Document();
Section section = doc.AddSection();
Paragraph paragraph = section.AddParagraph();
// Add the HTML content to the document
paragraph.AppendHTML(htmlBody);
// Convert to PDF format
doc.SaveToFile("EmailToPdf.pdf", FileFormat.PDF);
}
}
}
Key Steps:
- Load the Email: The MailMessage.Load() method reads an email file (.msg or .eml) into a MailMessage object.
- Extract HTML Content: The email’s HTML body is retrieved via MailMessage.BodyHtml property.
- Create a Document: A Word document is instantiated using Spire.Doc.
- Add HTML to Document: The HTML content is appended to the document using Paragraph.AppendHTML().
- Save as PDF: The document is saved as a PDF using Document.SaveToFile().
Output:

Which Method Should You Choose?
| Scenario | Recommended Approach |
| Single conversions | Built-in Print to PDF |
| Non-sensitive batch jobs | Trusted online tools |
| Automated workflows/ sensitive emails | Spire libraries (C#/.NET) |
Conclusion
Whether you need a quick manual conversion or an automated solution for your application, converting emails to PDF is straightforward with the right tools. Universal methods are great for one-off conversions, while C# programming provides scalability and integration capabilities for developers. Choose the approach that best fits your needs to ensure your important emails are preserved effectively.
ALSO READ:
How to Create PowerPoint Documents in Python

Creating PowerPoint presentations programmatically can save time and enhance efficiency in generating reports, slideshows, and other visual presentations. By automating the process, you can focus on content and design rather than manual formatting.
In this tutorial, we will explore how to create PowerPoint documents in Python using Spire.Presentation for Python. This powerful tool allows developers to manipulate and generate PPT and PPTX files seamlessly.
Table of Contents:
- Python Library to Work with PowerPoint Files
- Installing Spire.Presentation for Python
- Creating a PowerPoint Document from Scratch
- Creating PowerPoint Documents Based on a Template
- Best Practices for Python PowerPoint Generation
- Wrap Up
- FAQs
1. Python Library to Work with PowerPoint Files
Spire.Presentation is a robust library for creating, reading, and modifying PowerPoint files in Python , without requiring Microsoft Office. This library supports a wide range of features, including:
- Create PowerPoint documents from scratch or templates.
- Add text, images, lists, tables, charts, and shapes.
- Customize fonts, colors, backgrounds, and layouts.
- Save as or export to PPT, PPTX, PDF, or images.
In the following sections, we will walk through the steps to install the library, create presentations, and add various elements to your slides.
2. Installing Spire.Presentation for Python
To get started, you need to install the Spire.Presentation library. You can install it using pip:
pip install spire.presentation
Once installed, you can begin utilizing its features in your Python scripts to create PowerPoint documents.
3. Creating a PowerPoint Document from Scratch
3.1 Generate and Save a Blank Presentation
Let's start by creating a basic PowerPoint presentation from scratch. The following code snippet demonstrates how to generate and save a blank presentation:
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Set the slide size type
presentation.SlideSize.Type = SlideSizeType.Screen16x9
# Add a slide (there is one slide in the document by default)
presentation.Slides.Append()
# Save the document as a PPT or PPTX file
presentation.SaveToFile("BlankPowerPoint.pptx", FileFormat.Pptx2019)
presentation.Dispose()
In this code:
- Presentation : Root class representing the PowerPoint file.
- SlideSize.Type : Sets the slide dimensions (e.g., SlideSizeType.Screen16x9 for widescreen).
- Slides.Append() : Adds a new slide to the presentation. By default, a presentation starts with one slide.
- SaveToFile() : Saves the presentation to the specified file format (PPTX in this case).
3.2 Add Basic Elements to Your Slides
Now that we have a blank presentation, let's add some basic elements like text, images, lists, and tables.
Add Formatted Text
To add formatted text, we can use the following code:
# Get the first slide
first_slide = presentation.Slides[0]
# Add a shape to the slide
rect = RectangleF.FromLTRB (30, 60, 900, 150)
shape = first_slide.Shapes.AppendShape(ShapeType.Rectangle, rect)
shape.ShapeStyle.LineColor.Color = Color.get_Transparent()
shape.Fill.FillType = FillFormatType.none
# Add text to the shape
shape.AppendTextFrame("This guide demonstrates how to create a PowerPoint document using Python.")
# Get text of the shape as a text range
textRange = shape.TextFrame.TextRange
# Set font name, style (bold & italic), size and color
textRange.LatinFont = TextFont("Times New Roman")
textRange.IsBold = TriState.TTrue
textRange.FontHeight = 32
textRange.Fill.FillType = FillFormatType.Solid
textRange.Fill.SolidColor.Color = Color.get_Black()
# Set alignment
textRange.Paragraph.Alignment = TextAlignmentType.Left
In this code:
- AppendShape() : Adds a shape to the slide. We create a rectangle shape that will house our text.
- AppendTextFrame() : Adds a text frame to the shape, allowing us to insert text into it.
- TextFrame.TextRange : Accesses the text range of the shape, enabling further customization such as font style, size, and color.
- Paragraph.Alignment : Sets the alignment of the text within the shape.
Add an Image
To include an image in your presentation, use the following code snippet:
# Get the first slide
first_slide = presentation.Slides[0]
# Load an image file
imageFile = "C:\\Users\\Administrator\\Desktop\\logo.png"
stream = Stream(imageFile)
imageData = presentation.Images.AppendStream(stream)
# Reset size
width = imageData.Width * 0.6
height = imageData.Height * 0.6
# Append it to the slide
rect = RectangleF.FromLTRB (750, 50, 750 + width, 50 + height)
image = first_slide.Shapes.AppendEmbedImageByImageData(ShapeType.Rectangle, imageData, rect)
image.Line.FillType = FillFormatType.none
In this code:
- Stream() : Creates a stream from the specified image file path.
- AppendStream() : Appends the image data to the presentation's image collection.
- AppendEmbedImageByImageData() : Adds the image to the slide at the specified rectangle coordinates.
You may also like: Insert Shapes in PowerPoint in Python
Add a List
To add a bulleted list to your slide, we can use:
# Get the first slide
first_slide = presentation.Slides[0]
# Specify list bounds and content
listBounds = RectangleF.FromLTRB(30, 150, 500, 350)
listContent = [
" Step 1. Install Spire.Presentation for Python.",
" Step 2. Create a Presentation object.",
" Step 3. Add text, images, etc. to slides.",
" Step 5. Set a background image or color.",
" Step 6. Save the presentation to a PPT(X) file."
]
# Add a shape
autoShape = first_slide.Shapes.AppendShape(ShapeType.Rectangle, listBounds)
autoShape.TextFrame.Paragraphs.Clear()
autoShape.Fill.FillType = FillFormatType.none
autoShape.Line.FillType = FillFormatType.none
for content in listContent:
# Create paragraphs based on the list content and add them to the shape
paragraph = TextParagraph()
autoShape.TextFrame.Paragraphs.Append(paragraph)
paragraph.Text = content
paragraph.TextRanges[0].Fill.FillType = FillFormatType.Solid
paragraph.TextRanges[0].Fill.SolidColor.Color = Color.get_Black()
paragraph.TextRanges[0].FontHeight = 20
paragraph.TextRanges[0].LatinFont = TextFont("Arial")
# Set the bullet type for these paragraphs
paragraph.BulletType = TextBulletType.Symbol
# Set line spacing
paragraph.LineSpacing = 150
In this code:
- AppendShape() : Creates a rectangle shape for the list.
- TextFrame.Paragraphs.Append() : Adds paragraphs for each list item.
- BulletType : Sets the bullet style for the list items.
Add a Table
To include a table, you can use the following:
# Get the first slide
first_slide = presentation.Slides[0]
# Define table dimensions and data
widths = [200, 200, 200]
heights = [18, 18, 18, 18]
dataStr = [
["Slide Number", "Title", "Content Type"],
["1", "Introduction", "Text/Image"],
["2", "Project Overview", "Chart/Graph"],
["3", "Key Findings", "Text/List"]
]
# Add table to the slide
table = first_slide.Shapes.AppendTable(30, 360, widths, heights)
# Fill table with data and apply formatting
for rowNum, rowData in enumerate(dataStr):
for colNum, cellData in enumerate(rowData):
cell = table[colNum, rowNum]
cell.TextFrame.Text = cellData
textRange = cell.TextFrame.Paragraphs[0].TextRanges[0]
textRange.LatinFont = TextFont("Times New Roman")
textRange.FontHeight = 20
cell.TextFrame.Paragraphs[0].Alignment = TextAlignmentType.Center
# Apply a built-in table style
table.StylePreset = TableStylePreset.MediumStyle2Accent1
In this code:
- AppendTable() : Adds a table to the slide at specified coordinates with defined widths and heights for columns and rows.
- Cell.TextFrame.Text : Sets the text for each cell in the table.
- StylePreset : Applies a predefined style to the table for enhanced aesthetics.
3.3 Apply a Background Image or Color
To set a custom background for your slide, use the following code:
# Get the first slide
first_slide = presentation.Slides[0]
# Get the background of the first slide
background = first_slide.SlideBackground
# Create a stream from the specified image file
stream = Stream("C:\\Users\\Administrator\\Desktop\\background.jpg")
imageData = presentation.Images.AppendStream(stream)
# Set the image as the background
background.Type = BackgroundType.Custom
background.Fill.FillType = FillFormatType.Picture
background.Fill.PictureFill.FillType = PictureFillType.Stretch
background.Fill.PictureFill.Picture.EmbedImage = imageData
In this code:
- SlideBackground : Accesses the background properties of the slide.
- Fill.FillType : Specifies the type of fill (in this case, an image).
- PictureFill.FillType : Sets how the background image is displayed (stretched, in this case).
- Picture.EmbedImage : Sets image data for the background.
For additional background options, refer to this tutorial: Set Background Color or Picture for PowerPoint Slides in Python
Output:
Below is a screenshot of the PowerPoint document generated by the code snippets provided above.

4. Creating PowerPoint Documents Based on a Template
Using templates can simplify the process of creating presentations by allowing you to replace placeholders with actual data. Below is an example of how to create a PowerPoint document based on a template:
from spire.presentation.common import *
from spire.presentation import *
# Create a Presentation object
presentation = Presentation()
# Load a PowerPoint document from a specified file path
presentation.LoadFromFile("C:\\Users\\Administrator\\Desktop\\template.pptx")
# Get a specific slide from the presentation
slide = presentation.Slides[0]
# Define a list of replacements where each tuple consists of the placeholder and its corresponding replacement text
replacements = [
("{project_name}", "GreenCity Solar Initiative"),
("{budget}", "$1,250,000"),
("{status}", "In Progress (65% Completion)"),
("{start_date}", "March 15, 2023"),
("{end_date}", "November 30, 2024"),
("{manager}", "Emily Carter"),
("{client}", "GreenCity Municipal Government")
]
# Iterate through each replacement pair
for old_string, new_string in replacements:
# Replace the first occurrence of the old string in the slide with the new string
slide.ReplaceFirstText(old_string, new_string, False)
# Save the modified presentation to a new file
presentation.SaveToFile("Template-Based.pptx", FileFormat.Pptx2019)
presentation.Dispose()
In this code:
- LoadFromFile() : Loads an existing PowerPoint file that serves as the template.
- ReplaceFirstText() : Replaces placeholders within the slide with actual values. This is useful for dynamic content generation.
- SaveToFile() : Saves the modified presentation as a new file.
Output:

5. Best Practices for Python PowerPoint Generation
When creating PowerPoint presentations using Python, consider the following best practices:
- Maintain Consistency : Ensure that the formatting (fonts, colors, styles) is consistent across slides for a professional appearance.
- Modular Code: Break document generation into functions (e.g., add_list(), insert_image()) for reusability.
- Optimize Images : Resize and compress images before adding them to presentations to reduce file size and improve loading times.
- Use Templates : Whenever possible, use templates to save time and maintain a cohesive design.
- Test Your Code : Always test your presentation generation code to ensure that all elements are added correctly and appear as expected.
6. Wrap Up
In this tutorial, we explored how to create PowerPoint documents in Python using the Spire.Presentation library. We covered the installation, creation of presentations from scratch, adding various elements, and using templates for dynamic content generation. With these skills, you can automate the creation of presentations, making your workflow more efficient and effective.
7. FAQs
Q1. What is Spire.Presentation?
Spire.Presentation is a powerful library used for creating, reading, and modifying PowerPoint files in various programming languages, including Python.
Q2. Does this library require Microsoft Office to be installed?
No, Spire.Presentation operates independently and does not require Microsoft Office.
Q3. Can I customize the layout of slides in my presentation?
Yes, you can customize the layout of each slide by adjusting properties such as size, background, and the placement of shapes, text, and images.
Q4. Does Spire.Presentation support both PPT and PPTX format?
Yes, Spire.Presentation supports both PPT and PPTX formats, allowing you to create and manipulate presentations in either format.
Q5. Can I add charts to my presentations?
Yes, Spire.Presentation supports the addition of charts to your slides, allowing you to visualize data effectively. For detailed instruction, refer to: How to Create Column Charts in PowerPoint Using Python
Get a Free License
To fully experience the capabilities of Spire.Presentation for Python without any evaluation limitations, you can request a free 30-day trial license.
Spire.XLS for C++ 15.7.1 enhances the conversion from Excel to PDF
We're pleased to announce the release of Spire.XLS for C++ 15.7.1. This release fixes several issues that occurred when converting Excel to PDF and calculating the AGGREGATE formula. Details are shown below.
Here is a list of all changes made in this release
| Category | ID | Description |
| Bug | - | Fixes the issue of incorrect checkboxes when converting Excel to PDF. |
| Bug | - | Fixes the issue of incorrect calculation with the AGGREGATE formula. |
| Bug | - | Fixes the issue of overlapping content when converting Excel to PDF. |
| Bug | - | Fixes the issue of incorrect text wrapping when converting Excel to PDF. |
Spire.Presentation 10.7.7 supports loading Markdown files
We're excited to announce the release of Spire.Presentation 10.7.7. The latest version supports loading Markdown files. Besides, the issue that files were corrupted when opening presentations containing copied slides is fixed. Check below for the details.
Here is a list of changes made in this release
| Category | ID | Description |
| New feature | - | Supports loading Markdown files.
Presentation pt = new Presentation();
pt.LoadFromFile(inputFilePath, FileFormat.Markdown);
pt.SaveToFile("out.pptx", FileFormat.Pptx2013);
|
| Bug | SPIREPPT-2849 | Fixes the issue that files were corrupted when opening presentations containing copied slides. |
OCR Tutorial: Extract Text from Images in C#

Optical Character Recognition (OCR) technology bridges the physical and digital worlds by converting text within images into machine-readable data. For .NET developers, the ability to extract text from images in C# is essential for building intelligent document processing, automated data entry, and accessibility solutions.
In this article, we’ll explore how to implement OCR in C# using the Spire.OCR for .NET library, covering basic extraction, advanced features like coordinate tracking, and best practices to ensure accuracy and efficiency.
Table of Contents:
- Understanding OCR and Spire.OCR
- Setting Up Your OCR Environment
- Basic Recognition: Extract Text from Images in C#
- Advanced Extraction: Extract Text with Coordinates in C#
- Tips to Optimize OCR Accuracy
- FAQs (Supported Languages and Image Formats)
- Conclusion & Free License
Understanding OCR and Spire.OCR
What is OCR?
OCR technology analyzes images of text - such as scanned documents, screenshots, or photos - and converts them into text strings that can be edited, searched, or processed programmatically.
Why Spire.OCR Stands Out?
Spire.OCR for .NET is a powerful, developer-friendly library that enables highly accurate text recognition from images in C# applications. Key features include:
- Support for multiple languages (English, Chinese, Japanese, etc.).
- High accuracy recognition algorithms optimized for various fonts and styles.
- Text coordinate extraction for precise positioning.
- Batch processing capabilities.
- Compatibility with .NET Framework and .NET Core.
Setting Up Your OCR Environment
Before diving into the C# code for image to text OCR operations, configure your development environment first:
1. Install via NuGet:
Open the NuGet Package Manager in Visual Studio. Search for "Spire.OCR" and install the latest version in your project. Alternatively, use the Package Manager Console:
Install-Package Spire.OCR
2. Download OCR Models:
Spire.OCR relies on pre-trained models to recognize image text. Download the model files for your operating system:
After downloading, extract to a directory (e.g., F:\OCR Model\win-x64)
Important Note: Remember to change the platform target of your solution to x64 as Spire.OCR only supports 64-bit platforms.

Basic Recognition: Extract Text from Images in C#
Let’s start with a simple example that demonstrates how to read text from an image using Spire.OCR.
C# code to get text from an image:
using Spire.OCR;
using System.IO;
namespace OCRTextFromImage
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Create an instance of the ConfigureOptions class
ConfigureOptions configureOptions = new ConfigureOptions();
// Set the path to the OCR model
configureOptions.ModelPath = "F:\\OCR Model\\win-x64";
// Set the language for text recognition. (The default is English.)
configureOptions.Language = "English";
// Apply the configuration options to the scanner
scanner.ConfigureDependencies(configureOptions);
// Scan image and extract text
scanner.Scan("sample.png");
// Save the extracted text to a txt file
string text = scanner.Text.ToString();
File.WriteAllText("output.txt", text);
}
}
}
Code Explanation:
- OcrScanner: Core class for text recognition.
- ConfigureOptions: Sets OCR parameters:
- ModelPath: Specifies the path to the OCR model files.
- Language: Defines the recognition language (e.g., "English", "Chinese").
- Scan(): Processes image and extracts text using the configured settings.
Output:
This C# code processes an image file (sample.png) and saves the extracted text to a text file (output.txt) using File.WriteAllText().

Advanced Extraction: Extract Text with Coordinates in C#
In many cases, knowing the position of extracted text within an image is as important as the text itself - for example, when processing invoices, forms, or structured documents. Spire.OCR allows you to extract not just text but also the coordinates of the text blocks, enabling precise analysis.
C# code to extract text with coordinates from an Image:
using Spire.OCR;
using System.Collections.Generic;
using System.IO;
namespace OCRWithCoordinates
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the OcrScanner class
OcrScanner scanner = new OcrScanner();
// Create an instance of the ConfigureOptions class
ConfigureOptions configureOptions = new ConfigureOptions();
// Set the path to the OCR model
configureOptions.ModelPath = "F:\\OCR Model\\win-x64";
// Set the language for text recognition. (The default is English.)
configureOptions.Language = "English";
// Apply the configuration options to the scanner
scanner.ConfigureDependencies(configureOptions);
// Extract text from an image
scanner.Scan("invoice.png");
// Get the OCR result text
IOCRText text = scanner.Text;
// Create a list to store information
List<string> results = new List<string>();
// Iterate through each block of the OCR result text
foreach (IOCRTextBlock block in text.Blocks)
{
// Add the text of each block and its location information to the list
results.Add($"Block Text: {block.Text}");
results.Add($"Coordinates: {block.Box}");
results.Add("---------");
}
// Save the extracted text with coordinates to a txt file
File.WriteAllLines("ExtractWithCoordinates.txt", results);
}
}
}
Critical Details
- IOCRText: Represents the entire OCR result.
- IOCRTextBlock: Represents a block of contiguous text (e.g., a paragraph, line, or word).
- IOCRTextBlock.Box: Contains the rectangular coordinates of the text block:
- X (horizontal position)
- Y (vertical position)
- Width
- Height
Output:
This C# code performs OCR on an image file (invoice.png), extracting both the recognized text and its position coordinates in the image, then saves this information to a text file (ExtractWithCoordinates.txt).

Tips to Optimize OCR Accuracy
To ensure reliable results when using C# to recognize text from images, consider these best practices:
- Use high-resolution images (300 DPI or higher).
- Preprocess images (e.g., resize, deskew) for better results.
- Ensure correct language settings correspond to the text in image.
- Store OCR models in a secure, accessible location.
FAQs (Supported Languages and Image Formats)
Q1: What image formats does Spire.OCR support?
A: Spire.OCR supports all common formats:
- PNG
- JPEG/JPG
- BMP
- TIFF
- GIF
Q2: What languages does Spire.OCR support?
A: Multiple languages are supported:
- English (default)
- Chinese (Simplified and Traditional)
- Japanese
- Korean
- German
- French
Q3: Can I use Spire.OCR in ASP.NET Core applications?
A: Yes. Supported environments:
- .NET Framework 2.0+
- .NET Standard 2.0+
- .NET Core 2.0+
- .NET 5
Q4: Can Spire.OCR extract text from scanned PDFs in C#?
A: The task requires the Spire.PDF integration to convert PDFs to images or extract images from scanned PDFs first, and then use the above C# examples to get text from the images.
Conclusion & Free License
Spire.OCR for .NET provides a powerful yet straightforward solution for extracting text from images in C# applications. Whether you’re building a simple tool to convert images to text or a complex system for processing thousands of invoices, by following the techniques and best practices outlined in this guide, you can integrate OCR functionality into your C# applications with ease.
Request a 30-day trial license here to get unlimited OCR capabilities and unlock valuable information trapped in visual format.
Spire.Presentation for Python 10.7.1 supports adding SVG to PowerPoint presentations
We are pleased to announce the release of Spire.Presentation for Python 10.7.1. This version adds support for inserting SVG images into PowerPoint presentations and enhances the namespace structure. Detailed information is provided below.
Here are the changes included in this release.
| Category | ID | Description |
| Optimization | - | Optimizes and modularizes the namespace structure. |
| New Feature | SPIREPPT-2925 | Supports adding SVG to PowerPoint presentations.
#Load a PowerPoint document presentation = Presentation() #Insert svg to PPT presentation.Slides[0].Shapes.AddFromSVGAsShapes(SvgFile); #Save the document presentation.SaveToFile(outputFile, FileFormat.Pptx2010) presentation.Dispose() |
Spire.PDF for Java 11.7.5 supports converting PDF to Markdown
We’re glad the announce the release of Spire.PDF for Java 11.7.5. This version introduces support for converting PDFs to Markdown and resolves several known issues, including garbled text during PDF-to-image conversions and content rotation problems when converting OFD to PDF. For more details, please see the information below.
Here is a list of changes made in this release:
| Category | ID | Description |
| New feature | SPIREPDF-5995 | Added support for converting PDF files to Markdown format.
PdfDocument doc = new PdfDocument("input.pdf");
doc.saveToFile("output.md", FileFormat.Markdown);
|
| Adjustment | SPIREPDF-7597 | Internal adjustments were made to references of "sun.misc.BASE64Decoder". |
| Bug | SPIREPDF-7405 | Fixed the issue where text became garbled when converting PDF to images. |
| Bug | SPIREPDF-7546 | Fixed the issue that caused the program to throw a "NegativeArraySizeException" when converting PDF to images. |
| Bug | SPIREPDF-7563 | Fixed the issue where the CSS directory name was incorrect when converting PDF to HTML on Linux systems. |
| Bug | SPIREPDF-7564 | Fixed the issue where content was rotated when converting OFD to PDF. |
| Bug | SPIREPDF-7596 | Fixed the issue that caused the program to throw a "NegativeArraySizeException" when using pdfGrayConverter.toGrayPdf. |
| Bug | SPIREPDF-7599 | Fixed the issue where bookmark navigation positions were incorrect when merging PDFs. |
| Bug | SPIREPDF-7622 | Fixed the issue where LicenseProvider.setLicense(path) would throw an error if the path contained backslashes (""). |