Cómo convertir DOCX a PDF usando C#

How to Convert Microsoft Word to PDF in C#

This article was translated from English: Does it need improvement?
Translated
View the article in English

A DOCX file is a document created in Microsoft Word, a word processing program within the Microsoft office suited provided by Microsoft. It uses the Office Open XML (OOXML) standard, making it efficient and compatible with various software. It's the default format for Word documents since Word 2007, replacing the older DOC format when its was originally published.

IronPDF has the ability to convert word documents to PDF files in an instance, along with providing a Mail Merge feature for generating personalized batches of documents for individual recipients. Converting from DOCX to PDF ensures universal compatibility, preserves formatting, and adds a layer of security.

Quickstart: Convert DOCX to PDF Using IronPDF

Effortlessly convert DOCX files to PDF in C# with IronPDF. This quick guide demonstrates how to use the DocxToPdfRenderer class and the RenderDocxAsPdf method for a seamless conversion in just one line of code. Perfect for developers looking to streamline document processing, ensuring that the resulting PDF retains all original formatting and compatibility.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    new IronPdf.DocxToPdfRenderer()
        .RenderDocxAsPdf("document.docx")
        .SaveAs("output.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Convert DOCX file to PDF Example

IronPDF allows for developers to convert word documents to pdf programmatically, streamlining efficiency and allowing them to integrate into existing .NET applications or any cross platform .NET framework applications they might have.

The conversion process to convert a Microsoft Word file to PDF format is simple. We first instantiate the DocxToPdfRenderer class. Utilize the RenderDocxAsPdf method of the DocxToPdfRenderer object by providing the filepath of the DOCX file. This method returns a PdfDocument object, allowing you to customize the PDF further. You can download the Modern Chronological Resume DOCX example file.

Microsoft Word Preview

Microsoft Word Preview

Code Sample

Additionally, the RenderDocxAsPdf method also accepts DOCX data as bytes and streams.

:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-from-file.cs
using IronPdf;

// Instantiate Renderer
DocxToPdfRenderer renderer = new DocxToPdfRenderer();

// Render from DOCX file
PdfDocument pdf = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx");

// Save the PDF
pdf.SaveAs("pdfFromDocx.pdf");
Imports IronPdf

' Instantiate Renderer
Private renderer As New DocxToPdfRenderer()

' Render from DOCX file
Private pdf As PdfDocument = renderer.RenderDocxAsPdf("Modern-chronological-resume.docx")

' Save the PDF
pdf.SaveAs("pdfFromDocx.pdf")
$vbLabelText   $csharpLabel

Output PDF


Mail Merge Example

Mail Merge, located on the "Mailings" tab in Microsoft Word, allows you to create a batch of documents with personalized information for each recipient or data entry. It's often used to generate personalized letters, envelopes, labels, or email messages, such as invitations, newsletters, or form letters, where much of the content is the same, but certain details vary for each recipient.

Model

First, let's create a model to store the information that will be mail-merged into its corresponding placeholder.

:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-mail-merge-model.cs
internal class RecipientsDataModel
{
    public string Date { get; set; }
    public string Location{ get; set; }
    public string Recipients_Name { get; set; }
    public string Contact_Us { get; set; }
}
Friend Class RecipientsDataModel
	Public Property [Date]() As String
	Public Property Location() As String
	Public Property Recipients_Name() As String
	Public Property Contact_Us() As String
End Class
$vbLabelText   $csharpLabel

I have modified a template provided by Microsoft Word for our purposes. Please download the Party Invitation DOTX example file. For our use case, let's set the MailMergePrintAllInOnePdfDocument property to true, which combines the PDFs into a single PdfDocument object. The merge fields that we are going to use are Date, Location, Recipient's Name, and Contact Us.

Microsoft Word Preview

Microsoft Word Preview

Code Sample

:path=/static-assets/pdf/content-code-examples/how-to/docx-to-pdf-mail-merge.cs
using IronPdf;
using System.Collections.Generic;
using System.Linq;

var recipients = new List<RecipientsDataModel>()
    {
        new RecipientsDataModel()
        {
            Date ="Saturday, October 15th, 2023",
            Location="Iron Software Cafe, Chiang Mai",
            Recipients_Name="Olivia Smith",
            Contact_Us = "support@ironsoftware.com"
        },
        new RecipientsDataModel()
        {
            Date ="Saturday, October 15th, 2023",
            Location="Iron Software Cafe, Chiang Mai",
            Recipients_Name="Ethan Davis",
            Contact_Us = "support@ironsoftware.com"
        },
    };

DocxToPdfRenderer docxToPdfRenderer = new DocxToPdfRenderer();

// Apply render options
DocxPdfRenderOptions options = new DocxPdfRenderOptions();

// Configure the output PDF to be combined into a single PDF document
options.MailMergePrintAllInOnePdfDocument = true;

// Convert DOTX to PDF
var pdfs = docxToPdfRenderer.RenderDocxMailMergeAsPdf<RecipientsDataModel>(
     recipients,
     "Party-invitation.dotx",
     options);

pdfs.First().SaveAs("mailMerge.pdf");
Imports IronPdf
Imports System.Collections.Generic
Imports System.Linq

Private recipients = New List(Of RecipientsDataModel)() From {
	New RecipientsDataModel() With {
		.Date ="Saturday, October 15th, 2023",
		.Location="Iron Software Cafe, Chiang Mai",
		.Recipients_Name="Olivia Smith",
		.Contact_Us = "support@ironsoftware.com"
	},
	New RecipientsDataModel() With {
		.Date ="Saturday, October 15th, 2023",
		.Location="Iron Software Cafe, Chiang Mai",
		.Recipients_Name="Ethan Davis",
		.Contact_Us = "support@ironsoftware.com"
	}
}

Private docxToPdfRenderer As New DocxToPdfRenderer()

' Apply render options
Private options As New DocxPdfRenderOptions()

' Configure the output PDF to be combined into a single PDF document
options.MailMergePrintAllInOnePdfDocument = True

' Convert DOTX to PDF
Dim pdfs = docxToPdfRenderer.RenderDocxMailMergeAsPdf(Of RecipientsDataModel)(recipients, "Party-invitation.dotx", options)

pdfs.First().SaveAs("mailMerge.pdf")
$vbLabelText   $csharpLabel

Output PDF

Once the PDF document is created, you have the flexibility to make additional changes. These include exporting it as PDF/A or PDF/UA, as well as adding a digital certificate. You can also manipulate individual pages by merging or splitting PDFs, rotating them, and you have the option to apply annotations and bookmarks.

Aside from those features, IronPDF also supports converting to other document formats. For additional information regarding the other functionality that IronPDF has to offer, please refer to this tutorial.

Preguntas Frecuentes

¿Cómo convierto un archivo DOCX a PDF en C#?

Para convertir un archivo DOCX a PDF en C#, puedes usar la clase `DocxToPdfRenderer` de la biblioteca IronPDF. Simplemente instancia la clase y llama el método `RenderDocxAsPdf`, pasando tu archivo DOCX para producir un PDF.

¿Por qué debería convertir archivos DOCX a formato PDF?

Convertir archivos DOCX a formato PDF asegura que tu documento mantenga su formato a través de diferentes plataformas y dispositivos, mejora la seguridad y proporciona un formato universalmente compatible.

¿Puedo usar IronPDF para realizar una combinación de correspondencia con archivos DOCX?

Sí, IronPDF admite la función de combinar correspondencia, lo que te permite crear documentos personalizados combinando datos en tus plantillas DOCX y luego convirtiéndolos a PDF.

¿Cuáles son las ventajas de usar IronPDF para la conversión de DOCX a PDF?

IronPDF proporciona un proceso optimizado para convertir DOCX a PDF, admite funciones avanzadas como la combinación de correspondencia, y permite una personalización adicional del PDF, como la adición de certificados digitales y anotaciones.

¿Es posible convertir datos DOCX desde un flujo a PDF usando IronPDF?

Sí, el método `RenderDocxAsPdf` de IronPDF puede manejar datos DOCX desde flujos o matrices de bytes, lo que lo hace versátil para diferentes fuentes de entrada.

¿Puedo personalizar más el PDF después de la conversión desde DOCX?

Después de convertir un DOCX a PDF con IronPDF, puedes personalizar el PDF exportándolo a estándares como PDF/A o PDF/UA, añadiendo anotaciones, marcadores o firmas digitales.

¿Dónde puedo encontrar archivos DOCX de ejemplo para probar la conversión a PDF?

Puedes descargar archivos DOCX de ejemplo, como el 'Currículum Cronológico Moderno', desde los enlaces proporcionados en el sitio web de IronPDF para practicar la conversión a PDF.

¿Cómo puedo descargar IronPDF para la conversión de DOCX a PDF en C#?

IronPDF se puede descargar desde el gestor de paquetes NuGet, permitiendo una fácil integración en tus proyectos .NET para la conversión de DOCX a PDF.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
Revisado por
Jeff Fritz
Jeffrey T. Fritz
Gerente Principal de Programas - Equipo de la Comunidad .NET
Jeff también es Gerente Principal de Programas para los equipos de .NET y Visual Studio. Es el productor ejecutivo de la serie de conferencias virtuales .NET Conf y anfitrión de 'Fritz and Friends', una transmisión en vivo para desarrolladores que se emite dos veces a la semana donde habla sobre tecnología y escribe código junto con la audiencia. Jeff escribe talleres, presentaciones, y planifica contenido para los eventos de desarrolladores más importantes de Microsoft, incluyendo Microsoft Build, Microsoft Ignite, .NET Conf y la Cumbre de Microsoft MVP.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado