Saltar al pie de página
USANDO IRONPRINT

Cómo imprimir un documento Word en C#

In the ever-evolving landscape of software development, the ability to generate and print Word documents programmatically is a fundamental requirement. C# developers often encounter scenarios where generating and printing Word documents becomes essential for tasks such as report generation, document processing, or creating professional-looking outputs. To address this need, Iron Software presents IronWord, IronPDF, and IronPrint, powerful libraries designed to streamline the creation, manipulation, and printing of Word and PDF documents within C# applications.

This article will explore the features and advantages of IronPrint for printing, creating a Word document object sender using IronWord, and converting it to PDF using IronPDF for printing.

How to print a Word document in C#

  1. Create a Visual Studio Project
  2. Install IronWord, IronPDF, and IronPrint libraries
  3. Create a Word Document using IronWord WordDocument class
  4. Save the Word document using SaveAs method
  5. Create a PDF document using IronPDF's DocxToPdfRenderer method
  6. Adjust PrinterSettings using IronPrint
  7. Print using IronPrint Printer.Print method

IronPrint

IronPrint, developed by Iron Software, is a robust and versatile print library for .NET, offering a wide array of tools for handling printing tasks in C#. It stands out with dedicated classes and methods tailored for print-related functionalities, providing developers with fine-grained control over the printing process and printer settings.

Key Features of IronPrint

1. Comprehensive Print Settings

IronPrint empowers developers to customize various aspects of the printing process. This includes:

  • Paper size
  • Orientation (Portrait or Landscape)
  • DPI (Dots Per Inch)
  • Number of copies
  • Printer name
  • Margins (Top, Bottom, Left, Right)
  • Grayscale printing

2. Versatile Printing with Printer Class

One of the standout features of IronPrint is the introduction of the Printer class. This class provides a comprehensive set of methods for printing various file types, encompassing images and PDF documents. The versatility of the Printer class allows for seamless integration into diverse printing scenarios. It also allows displaying a print dialog while printing in real-time applications, giving more granular control for printing Word documents.

3. Cross-Platform Support

IronPrint boasts cross-platform compatibility, making it suitable for deployment across multiple environments. Whether your application runs on Windows, macOS, Android, or iOS, IronPrint ensures consistent and reliable printing functionality.

Prerequisites

Before diving into the implementation, ensure you have the following prerequisites:

  1. Visual Studio: Install Microsoft Visual Studio, a powerful integrated development environment for C#. Download it from the official website.
  2. IronWord Library: This library is essential for creating and manipulating Excel files. Install it using the NuGet Package Manager Console or directly from the official IronWord NuGet website.
  3. IronPDF Library: IronPDF will be used to convert the Excel file to PDF. Install it using the same NuGet installation method.
  4. IronPrint Library: Finally, install the IronPrint library to facilitate seamless printing in your C# application.

Steps to Create, Convert, and Print Word Documents

Follow these steps to set up a C# console application, create a Word document object, convert it to PDF, and finally print it using IronWord, IronPDF, and IronPrint respectively.

Step 1: Create a C# Console Application in Visual Studio

  1. Open Visual Studio and create a new C# Console Application.
  2. Configure the Project as follows and then click "Next."
  3. From Additional Information, choose the .NET Framework and click "Create."

Step 2: Install Necessary Libraries via NuGet Package Manager

  1. Open the NuGet Package Manager Console or NuGet Package Manager for Solutions using the Tools menu or Solution Explorer in the Visual Studio project.
  2. In the browse tab of NuGet, search for the libraries and click install.
  3. Install IronPrint Printing Library:

    • Using the NuGet Package Manager Console, use the following command:

      Install-Package IronPrint
  4. Do the same for installing IronWord and IronPDF library using the Manage NuGet Packages for Solutions. To install IronWord and IronPDF using the NuGet Package Manager Console, use the following commands:

    Install-Package IronWord
    Install-Package IronPdf
    Install-Package IronWord
    Install-Package IronPdf
    SHELL

Step 3: Create a Word Document using IronWord

Let's begin by creating a simple Word document using IronWord. The following code snippet illustrates how to create a Word document with sample text and save it:

using IronWord;
using IronWord.Models;

// Code to Create Word File

// Create a TextRun object with sample text
TextRun textRun = new TextRun("Sample text");

// Create a paragraph and add the TextRun to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a Word document object with the paragraph and save it as a .docx file
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("assets/document.docx");
using IronWord;
using IronWord.Models;

// Code to Create Word File

// Create a TextRun object with sample text
TextRun textRun = new TextRun("Sample text");

// Create a paragraph and add the TextRun to it
Paragraph paragraph = new Paragraph();
paragraph.AddTextRun(textRun);

// Create a Word document object with the paragraph and save it as a .docx file
WordDocument doc = new WordDocument(paragraph);
doc.SaveAs("assets/document.docx");
Imports IronWord
Imports IronWord.Models

' Code to Create Word File

' Create a TextRun object with sample text
Private textRun As New TextRun("Sample text")

' Create a paragraph and add the TextRun to it
Private paragraph As New Paragraph()
paragraph.AddTextRun(textRun)

' Create a Word document object with the paragraph and save it as a .docx file
Dim doc As New WordDocument(paragraph)
doc.SaveAs("assets/document.docx")
$vbLabelText   $csharpLabel

In this code:

  • We create a TextRun containing the sample text.
  • A Paragraph is created, and the TextRun is added to it.
  • Finally, a WordDocument is created with the paragraph, and the new document is saved as "document.docx".

Output Word Document

How to print a Word document in C#: Figure 2 - Output DOCX file generated using IronWord: document.docx

Step 4: Convert Word Document to PDF using IronPDF

Once we have our Word document, we may need to convert it to a PDF format. IronPDF simplifies this process, allowing for seamless conversion. Here's the code snippet:

using IronPdf;

// Code to convert DOCX file to PDF using IronPDF

// Create a DocxToPdfRenderer instance
var renderer = new DocxToPdfRenderer();

// Render the DOCX document as a PDF
var pdf = renderer.RenderDocxAsPdf("assets/document.docx");

// Save the resulting PDF
pdf.SaveAs("assets/word.pdf");
using IronPdf;

// Code to convert DOCX file to PDF using IronPDF

// Create a DocxToPdfRenderer instance
var renderer = new DocxToPdfRenderer();

// Render the DOCX document as a PDF
var pdf = renderer.RenderDocxAsPdf("assets/document.docx");

// Save the resulting PDF
pdf.SaveAs("assets/word.pdf");
Imports IronPdf

' Code to convert DOCX file to PDF using IronPDF

' Create a DocxToPdfRenderer instance
Private renderer = New DocxToPdfRenderer()

' Render the DOCX document as a PDF
Private pdf = renderer.RenderDocxAsPdf("assets/document.docx")

' Save the resulting PDF
pdf.SaveAs("assets/word.pdf")
$vbLabelText   $csharpLabel

In this code:

  • We use the DocxToPdfRenderer() method to render the Word document as a PDF.
  • The resulting PDF is saved as "word.pdf".

Step 5: Print the PDF using IronPrint

Printing the PDF can be achieved using IronPrint, providing flexibility and control over the print settings. If print settings are not set, then default settings are used to print. The following code demonstrates how to print the generated PDF:

using IronPrint;
using System.Collections.Generic;

// Code for Printing using IronPrint

// Fetch printer names available in the system
List<string> printerNames = Printer.GetPrinterNames();

// Configure print settings
PrintSettings printerSettings = new PrintSettings();
foreach(string printerName in printerNames)
{
    if(printerName.Equals("Microsoft Print to PDF"))
    {
        printerSettings.PrinterName = printerName;
    }
}

// Set paper size to A4 and configure margins
printerSettings.PaperSize = PaperSize.A4;
Margins margins = new Margins(30, 10);
printerSettings.PaperMargins = margins;

// Print the PDF with the specified settings
Printer.Print("assets/word.pdf", printerSettings);
using IronPrint;
using System.Collections.Generic;

// Code for Printing using IronPrint

// Fetch printer names available in the system
List<string> printerNames = Printer.GetPrinterNames();

// Configure print settings
PrintSettings printerSettings = new PrintSettings();
foreach(string printerName in printerNames)
{
    if(printerName.Equals("Microsoft Print to PDF"))
    {
        printerSettings.PrinterName = printerName;
    }
}

// Set paper size to A4 and configure margins
printerSettings.PaperSize = PaperSize.A4;
Margins margins = new Margins(30, 10);
printerSettings.PaperMargins = margins;

// Print the PDF with the specified settings
Printer.Print("assets/word.pdf", printerSettings);
Imports IronPrint
Imports System.Collections.Generic

' Code for Printing using IronPrint

' Fetch printer names available in the system
Private printerNames As List(Of String) = Printer.GetPrinterNames()

' Configure print settings
Private printerSettings As New PrintSettings()
For Each printerName As String In printerNames
	If printerName.Equals("Microsoft Print to PDF") Then
		printerSettings.PrinterName = printerName
	End If
Next printerName

' Set paper size to A4 and configure margins
printerSettings.PaperSize = PaperSize.A4
Dim margins As New Margins(30, 10)
printerSettings.PaperMargins = margins

' Print the PDF with the specified settings
Printer.Print("assets/word.pdf", printerSettings)
$vbLabelText   $csharpLabel

In this code:

  • We fetch available printer names using Printer.GetPrinterNames().
  • Set the specific printer name (in this case, "Microsoft Print to PDF"). If the physical printer is not available, then by default IronPrint takes this as the default printer.
  • Configure print settings, specifying paper size as A4 and setting margins.
  • Finally, print the PDF using Printer.Print() method.

How to print a Word document in C#: Figure 3 - Printable output PDF document using IronPrint: word.pdf

If you want to get control over NumberOfCopies, Print multiple pages, Grayscale, and DPI please visit this code examples page. You can also enable a printer dialog and prevent silent printing of documents.

Advantages of IronPrint for Printing in C#

Here are some key advantages of using IronPrint for printing jobs in C# console or Windows forms applications:

1. Asynchronous Printing

IronPrint provides asynchronous functions, allowing print operations to be performed asynchronously. This prevents print operations from blocking threads, leading to enhanced performance and responsiveness in your application.

2. Versatile Printing Options

The dedicated Printer class in IronPrint offers a comprehensive set of methods for printing various file types, including images and PDF documents. This versatility provides flexibility beyond standard printing, allowing developers to handle different types of content with ease.

3. Cross-Platform Support

IronPrint supports printing across multiple platforms, including Windows, Android, iOS, and macOS. This cross-platform compatibility makes it suitable for a variety of application environments, ensuring that your printing functionality can be deployed across diverse operating systems.

4. Customizable Print Settings

IronPrint allows developers to finely control print settings, providing a high degree of customization. Developers can specify various aspects of the printing process, such as paper size, orientation, DPI, number of copies, printer name, margins, and grayscale printing, through the PrintSettings class.

5. Seamless Integration with IronQR and IronPDF

IronPrint integrates seamlessly with other Iron Software libraries, such as IronQR and IronPDF. This integration allows developers to create, convert, and print QR codes, PDFs, and other documents within a unified and efficient workflow.

6. User-Friendly API

IronPrint features a user-friendly API that simplifies the implementation of printing functionality in C# applications. Developers can quickly add barcode and printing capabilities to their projects, reducing development time and effort.

7. Comprehensive Documentation and Support

IronPrint is backed by comprehensive documentation and support from Iron Software. This ensures that developers have access to resources and assistance when implementing printing features, making it easier to troubleshoot issues and optimize the printing process.

8. Enhanced Control Over Printing Process

With IronPrint, developers have enhanced control over the printing process. Features such as the ability to set paper size, margins, and other print parameters allow for precise control, ensuring that the printed output meets specific requirements and standards.

Conclusion

By following these steps, you can seamlessly integrate Word document handling, conversion to PDF, and printing functionality into your C# applications. IronWord, IronPDF, and IronPrint collectively provide a powerful toolkit for developers looking to enhance their document-related tasks. Whether you're working on web, mobile, desktop, or console applications, this guide serves as a comprehensive resource for leveraging these libraries effectively in your .NET projects.

For more information on how to print efficiently, please visit this documentation page.

IronPrint options are available for various needs, starting from $799. Download the library and enhance your C# application with printing capabilities.

Preguntas Frecuentes

¿Cómo puedo imprimir un documento de Word sin perder el formato en C#?

Para imprimir un documento de Word manteniendo su formato en C#, utilice IronWord para crear el documento, conviértalo a PDF usando IronPDF y luego imprímalo con IronPrint. Esto asegura que el formato del documento se conserve a lo largo del proceso.

¿Cuáles son los beneficios de usar IronPrint para la impresión de documentos en C#?

IronPrint ofrece impresión asincrónica, ajustes personalizables como tamaño y orientación del papel, compatibilidad multiplataforma e integración perfecta con otras bibliotecas de Iron Software, proporcionando una solución robusta para tareas de impresión en un entorno C#.

¿Cómo se integran IronWord, IronPDF e IronPrint en un proyecto de C#?

Para integrar estas bibliotecas en un proyecto de C#, instálelas a través de la Consola del Administrador de paquetes NuGet en Visual Studio. Use Install-Package IronWord, Install-Package IronPDF, y Install-Package IronPrint para agregar las funcionalidades necesarias para la creación de Word, conversión a PDF e impresión.

¿Puedo personalizar los ajustes de impresión al usar IronPrint?

Sí, IronPrint le permite personalizar una variedad de ajustes de impresión, incluyendo tamaño de papel, orientación, DPI, número de copias, nombre de impresora, márgenes e impresión en escala de grises, brindándole un control total sobre el proceso de impresión.

¿Es IronPrint adecuado para tareas de impresión multiplataforma?

IronPrint está diseñado para soporte multiplataforma, lo que le permite desplegarse en Windows, macOS, Android e iOS, haciéndolo versátil para varios entornos de desarrollo.

¿Qué pasos están involucrados en la creación e impresión de un documento de Word en C#?

Primero, use IronWord para crear el documento de Word. Luego, conviértalo a un PDF usando DocxToPdfRenderer de IronPDF. Finalmente, imprima el PDF usando IronPrint, asegurándose de que el formato del documento se mantenga.

¿Cómo mejora IronPrint la gestión de documentos en aplicaciones C#?

IronPrint mejora la gestión de documentos al proporcionar configuraciones de impresión completas, impresión asincrónica e integración perfecta con otras bibliotecas de Iron Software, facilitando el procesamiento eficiente e impresión de documentos en aplicaciones C#.

¿Qué herramientas se recomiendan para generar e imprimir documentos en C#?

Iron Software recomienda usar IronWord para la creación de documentos, IronPDF para la conversión a PDF e IronPrint para el proceso de impresión final. Esta combinación asegura resultados de alta calidad y facilidad de uso.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más