Saltar al pie de página
USANDO IRONPRINT

Cómo imprimir documentos de Word en C

To print Word documents in C#, use IronWord to create documents, IronPDF to convert them to PDF format, and IronPrint to handle the printing process with customizable settings across multiple platforms.

When building C# applications, you'll often need to generate and print Word documents programmatically. Whether you're creating reports, processing documents, or producing professional outputs, having reliable tools makes all the difference. That's where Iron Software's IronWord, IronPDF, and IronPrint come in - these libraries work together to simplify document creation, conversion, and printing in your C# applications.

This article guides you through using IronPrint for printing, creating Word documents with IronWord, and converting them to PDFs with IronPDF. Whether you're building enterprise reporting systems or automating document workflows, these tools provide everything you need for document processing.

How to Print a Word Document in C#?

  1. Crear un Proyecto de Visual Studio
  2. Instalar las bibliotecas IronWord, IronPDF e IronPrint
  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

What is IronPrint?

IronPrint is an effective print library for .NET that gives you complete control over printing in C#. Built by Iron Software, it offers dedicated classes and methods specifically designed for printing tasks, letting you fine-tune every aspect of the printing process. The library works smoothly with both .NET Framework and .NET Core, so you can use it in any type of application.

What are the Key Features of IronPrint?

How Does IronPrint Handle Print Settings?

IronPrint lets you customize every aspect of your print jobs:

  • Paper size (Letter, Legal, A4, A3, custom)
  • Orientation (Portrait or Environment)
  • DPI for quality control
  • Number of copies with collation
  • Printer selection and validation
  • Margins with precise measurements
  • Grayscale printing for cost savings
// Example: Advanced print settings configuration
using IronPrint;

// Create complete print settings
PrintSettings advancedSettings = new PrintSettings()
{
    PrinterName = "HP LaserJet Pro",
    PaperSize = PaperSize.A4,
    PrintOrientation = PrintOrientation.Portrait,
    Dpi = 600, // High quality print
    NumberOfCopies = 3,
    Grayscale = true,
    PaperMargins = new Margins(50, 50, 40, 40) // Left, Right, Top, Bottom
};

// Apply settings to print job
Printer.Print("document.pdf", advancedSettings);
// Example: Advanced print settings configuration
using IronPrint;

// Create complete print settings
PrintSettings advancedSettings = new PrintSettings()
{
    PrinterName = "HP LaserJet Pro",
    PaperSize = PaperSize.A4,
    PrintOrientation = PrintOrientation.Portrait,
    Dpi = 600, // High quality print
    NumberOfCopies = 3,
    Grayscale = true,
    PaperMargins = new Margins(50, 50, 40, 40) // Left, Right, Top, Bottom
};

// Apply settings to print job
Printer.Print("document.pdf", advancedSettings);
$vbLabelText   $csharpLabel

How Does the Printer Class Work?

The Printer class is the heart of IronPrint. It provides methods for printing various file types including images and PDFs. You can integrate it into any printing scenario, and it even supports print dialogs for real-time applications. The ShowPrintDialog method gives users familiar print configuration options when they need them.

Which Platforms Does IronPrint Support?

IronPrint works across Windows, macOS, Android, and iOS - ensuring consistent printing functionality wherever you deploy. This cross-platform support extends to WPF, Windows Forms, and ASP.NET applications.

What Prerequisites Are Needed?

Before starting, make sure you have:

  1. Visual Studio: Download and install from the official website.
  2. IronWord Library: For creating and manipulating Word files. Install via NuGet or from IronWord.
  3. IronPDF Library: For Word to PDF conversion. Get it from IronPDF.
  4. IronPrint Library: For printing functionality. Available at IronPrint.

How Do I Create, Convert, and Print Word Documents?

Let's build a C# console application that creates a Word document, converts it to PDF, and prints it using all three libraries.

Paso 1: Crear una aplicación de consola C# en Visual Studio

  1. Abre Visual Studio y crea una nueva aplicación de consola C#.
  2. Configure the Project and click "Next."
  3. From Additional Information, choose your .NET Framework and click "Create."

Paso 2: Instale las bibliotecas necesarias a través del Administrador de paquetes NuGet

  1. Open the NuGet Package Manager Console from the Tools menu.
  2. In the browse tab, search for each library and click install.
  3. Install IronPrint using this command:

    Install-Package IronPrint
  4. Install IronWord and IronPDF the same way. For the console, use:

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

Paso 3: Crea un documento de Word con IronWord

Let's start by creating a simple Word document with IronWord:

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");
$vbLabelText   $csharpLabel

Here's what's happening:

  • We create a TextRun with our text
  • Add it to a Paragraph
  • Create a WordDocument and save it

For more complex documents, add formatting, multiple paragraphs, and tables:

using IronWord;
using IronWord.Models;

// Create a more complex Word document
WordDocument complexDoc = new WordDocument();

// Add a title paragraph with formatting
TextRun titleRun = new TextRun("Quarterly Sales Report")
{
    FontSize = 24,
    Bold = true,
    FontFamily = "Arial"
};
Paragraph titleParagraph = new Paragraph();
titleParagraph.AddTextRun(titleRun);

// Add body content
TextRun bodyRun = new TextRun("This report contains sales data for Q4 2023.");
Paragraph bodyParagraph = new Paragraph();
bodyParagraph.AddTextRun(bodyRun);

// Add paragraphs to document
complexDoc.AddParagraph(titleParagraph);
complexDoc.AddParagraph(bodyParagraph);

// Save the document
complexDoc.SaveAs("assets/sales_report.docx");
using IronWord;
using IronWord.Models;

// Create a more complex Word document
WordDocument complexDoc = new WordDocument();

// Add a title paragraph with formatting
TextRun titleRun = new TextRun("Quarterly Sales Report")
{
    FontSize = 24,
    Bold = true,
    FontFamily = "Arial"
};
Paragraph titleParagraph = new Paragraph();
titleParagraph.AddTextRun(titleRun);

// Add body content
TextRun bodyRun = new TextRun("This report contains sales data for Q4 2023.");
Paragraph bodyParagraph = new Paragraph();
bodyParagraph.AddTextRun(bodyRun);

// Add paragraphs to document
complexDoc.AddParagraph(titleParagraph);
complexDoc.AddParagraph(bodyParagraph);

// Save the document
complexDoc.SaveAs("assets/sales_report.docx");
$vbLabelText   $csharpLabel

Documento de Word de salida

Output Word document created with IronWord showing formatted text content - document.docx file displayed in Microsoft Word with sample text paragraph

Paso 4: Convierte un documento de Word a PDF con IronPDF

Now let's convert our Word document to PDF with IronPDF:

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");
$vbLabelText   $csharpLabel

The process is straightforward:

  • Create a DocxToPdfRenderer
  • Render the Word document as PDF
  • Save the result

Paso 5: Imprima el PDF con IronPrint

Finally, let's print our PDF with IronPrint:

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);
$vbLabelText   $csharpLabel

Este código:

  • Gets available printers with Printer.GetPrinterNames()
  • Selects a specific printer
  • Configures paper size and margins
  • Prints the PDF

Print preview showing the converted PDF document ready for printing - IronPrint output displaying word.pdf with proper formatting and margins

For more control over copies, multiple pages, grayscale, and DPI, check out these code examples. You can also enable printer dialogs for user interaction.

What Are the Advantages of Using IronPrint for Printing?

Here's why IronPrint excels for C# printing tasks:

¿Por qué es importante la impresión asíncrona?

IronPrint offers asynchronous functions that prevent print operations from blocking your application. Your UI stays responsive during long print jobs:

// Asynchronous printing example
using IronPrint;
using System.Threading.Tasks;

public async Task PrintDocumentAsync(string filePath)
{
    PrintSettings settings = new PrintSettings
    {
        PrinterName = "Default Printer",
        NumberOfCopies = 2
    };

    // Non-blocking print operation
    await Printer.PrintAsync(filePath, settings);
    Console.WriteLine("Print job completed!");
}
// Asynchronous printing example
using IronPrint;
using System.Threading.Tasks;

public async Task PrintDocumentAsync(string filePath)
{
    PrintSettings settings = new PrintSettings
    {
        PrinterName = "Default Printer",
        NumberOfCopies = 2
    };

    // Non-blocking print operation
    await Printer.PrintAsync(filePath, settings);
    Console.WriteLine("Print job completed!");
}
$vbLabelText   $csharpLabel

How Do the Printing Options Improve Functionality?

The Printer class handles various file types including PDF, PNG, JPG, TIFF, and BMP. This versatility means you can print different content types without changing your approach.

Which Platforms Can I Deploy To?

IronPrint runs on Windows, Android, iOS, and macOS. Your printing code works consistently across all platforms, making deployment straightforward.

What Print Settings Can Be Customized?

Through the PrintSettings class, you control:

  • Paper size and orientation
  • DPI and print quality
  • Copies and collation
  • Margins and layout
  • Duplex printing
  • Custom page ranges

How Does IronPrint Integrate with Other Libraries?

IronPrint works smoothly with other Iron Software products like IronBarcode and IronPDF. The consistent API design makes it easy to create, convert, and print documents in one workflow.

Why Is the API Considered User-Friendly?

IronPrint's intuitive method names and complete IntelliSense support make it accessible to all developers. You can add printing functionality quickly without a steep learning curve.

What Support Resources Are Available?

Iron Software provides complete documentation, examples, API references, and best practices. Their support team helps you implement printing features effectively.

How Does IronPrint Improve Control Over Printing?

IronPrint gives you precise control over every aspect of printing. Set exact paper sizes, margins, and parameters to ensure your output meets specific requirements. Monitor printer status and handle errors for reliable print job management.

¿Cuáles son los próximos pasos?

You now have everything needed to create Word documents, convert them to PDFs, and print them in your C# applications. IronWord, IronPDF, and IronPrint work together to provide a complete document handling solution. Whether you're building web, mobile, desktop, or console applications, these tools simplify your document workflows.

For more printing techniques, visit the documentation page. Explore features like batch printing and custom print processors to improve your application's capabilities.

IronPrint licenses start from $799. Download the library and add professional printing to your C# application today.

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

Equipo de soporte de Iron

Estamos disponibles online las 24 horas, 5 días a la semana.
Chat
Email
Llámame