News Category

C#: Convert Word to PDF

2024-04-03 02:22:00 Written by  Administrator
Rate this item
(0 votes)

In today's digital era, the skill of converting Word documents to PDF has become indispensable for individuals and organizations alike. The ability to transform Word files into the PDF format has a wide range of applications, including submitting official reports, distributing e-books, and archiving important files. Through this conversion process, documents can be seamlessly shared, accessed, and preserved for the long term, ensuring convenience, compatibility, and enhanced document management.

In this article, you will learn how to convert Word to PDF in C# and how to set conversion options as well using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert Word to PDF in C#

Converting a Word document to a standard PDF using Spire.Doc is a simple task. To get started, you can utilize the LoadFromFile() or LoadFromStream() method from the Document object to load a Word document from a give file path or stream. Then, you can effortlessly convert it as a PDF file by employing the SaveToFile() method.

To convert Word to PDF in C#, follow these steps.

  • Create a Document object.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ConvertWordToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Save the document to PDF
            doc.SaveToFile("ToPDF.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert Word to PDF/A in C#

PDF/A is a specialized format that focuses on preserving electronic documents for long-term use, guaranteeing that the content remains accessible and unaltered as time goes on.

To specify the conformance level of the resulting PDF when converting a document, you can make use of the PdfConformanceLevel property found within the ToPdfParameterList object. By passing this object as an argument to the SaveToFile() method, you can indicate the desired conformance level during the conversion process.

The steps to convert Word to PDF/A in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Set the conformance level for the generated PDF using PdfConformanceLevel property of the ToPdfParameterList object.
  • Save the Word document to PDF/A using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace ConvertWordToPdfa
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters  = new ToPdfParameterList();

            // Set the conformance level for PDF
            parameters.PdfConformanceLevel = PdfConformanceLevel.Pdf_A1A;

            // Save the document to a PDF file
            doc.SaveToFile("ToPdfA.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert Word to Password-Protected PDF in C#

Transforming a Word document into a PDF that is protected by a password is a straightforward and efficient method to safeguard sensitive information and maintain its confidentiality and security.

To accomplish this, you can utilize the PdfSecurity.Encrypt() method, which is available within the ToPdfParameterList object. This method enables you to specify both an open password and a permission password for the resulting PDF file. By passing the ToPdfParameterList object as a parameter to the SaveToFile() method, these encryption settings will be implemented during the saving process.

The steps to convert Word to password-protected PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Set the open password and permission password for the generated PDF using ToPdfParameterList.PdfSecurity.Encrypt() method.
  • Save the Word document to a password protected PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace ConvertWordToPasswordProtectedPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Set open password and permission password for PDF
            parameters.PdfSecurity.Encrypt("openPsd", "permissionPsd", PdfPermissionsFlags.None, PdfEncryptionKeySize.Key128Bit);

            // Save the document to PDF
            doc.SaveToFile("PasswordProtected.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Convert a Specific Section in Word to PDF in C#

Being able to convert a specific section of a Microsoft Word document to a PDF can be highly advantageous when you want to extract a portion of a larger document for sharing or archiving purposes.

With the assistance of Spire.Doc, users can create a new Word document that contains the desired section from the source document by employing the Section.Clone() method and the Sections.Add() method. This new document can be then saved as a PDF file.

The following are the steps to convert a specific section of a Word document to PDF in C#.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create another Document object for holding one section from the source document.
  • Create a copy of a desired section of the source document using Section.Clone() method.
  • Add the copy to the new document using Sections.Add() method.
  • Save the new Word document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ConvertSectionToPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Get a specific section of the document
            Section section = doc.Sections[1];

            // Create a new document object
            Document newDoc = new Document();

            // Clone the default style to the new document
            doc.CloneDefaultStyleTo(newDoc);

            // Clone the section to the new document
            newDoc.Sections.Add(section.Clone());

            // Save the new document to stream
            MemoryStream ms = new MemoryStream();
            newDoc.SaveToStream(ms, FileFormat.Docx2019);

            // Load the new document from stream and save to PDF
            Document streamDoc = new Document(ms);
            streamDoc.SaveToFile("SectionToPDF.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
            newDoc.Dispose();
            stream.Dispose();
        }
    }
}

Change Page Size while Converting Word to PDF in C#

When converting a Word document to PDF, it may be necessary to modify the page size to align with standard paper sizes like Letter, Legal, Executive, A4, A5, B5, and others. Alternatively, you might need to customize the page dimensions to meet specific requirements.

By making use of the PageSetup.PageSize property, you can adjust the page size of the Word document to either a standard paper size or a custom paper size. This page configuration will be applied during the conversion process, ensuring that the resulting PDF file reflects the desired page dimensions.

The steps to change the page size while convert Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Iterate through the sections in the document, and change the page size of each section to a standard paper size or a custom size using PageSetup.PageSize property.
  • Save the Word document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace ChangePageSize
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Iterate through the sections in the document
            foreach (Section section in doc.Sections)
            {
                // Change the page size of each section to Letter
                section.PageSetup.PageSize = PageSize.Letter;

                // Change the page size of each section to a custom size
                // section.PageSetup.PageSize = new SizeF(500, 800);
            }

            // Save the document to PDF
            doc.SaveToFile("ChanegPageSize.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Set Image Quality while Converting Word to PDF in C#

When converting a Word document to PDF, it's essential to consider the quality of the images within the document. Balancing image integrity and file size is crucial to ensure an optimal viewing experience and efficient document handling.

Using Spire.Doc, you have the option to configure the image quality within the document by utilizing the JPEGQuality property of the Document object. For instance, by setting the value of JPEGQuality to 50, the image quality can be reduced to 50% of its original quality.

The steps to set image quality while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document for a given file path.
  • Set the image quality using Document.JPEGQuality property.
  • Save the document to PDF using Doucment.SaveToFile() method.
  • C#
using Spire.Doc;

namespace SetImageQuality
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Set the image quality to 50% of the original quality
            doc.JPEGQuality = 50;

            // Preserve original image quality
            // document.JPEGQuality = 100;

            // Save the document to PDF
            doc.SaveToFile("SetImageQuality.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Embed Fonts while Converting Word to PDF in C#

When fonts are embedded in a PDF, it ensures that viewers will see the exact font styles and types intended by the creator, regardless of whether they have the fonts installed on their system.

To include all the fonts used in a Word document in the resulting PDF, you can enable the embedding feature by setting the ToPdfParameterList.IsEmbeddedAllFonts property to true. Alternatively, if you prefer to specify a specific list of fonts to embed, you can make use of the EmbeddedFontNameList property.

The steps to embed fonts while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Embed all fonts in the generated PDF by settings IsEmbeddedAllFonts property to true.
  • Save the Word document to PDF with fonts embedded using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace EmbedFonts
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Embed all the fonts used in Word in the generated PDF
            parameters.IsEmbeddedAllFonts = true;

            // Save the document to PDF
            doc.SaveToFile("EmbedFonts.pdf", FileFormat.PDF);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Create Bookmarks while Converting Word to PDF in C#

Including bookmarks in a PDF document while converting from Microsoft Word can greatly enhance the navigation and readability of the resulting PDF, especially for long or complex documents.

When utilizing Spire.Doc to convert a Word document to PDF, you have the option to automatically generate bookmarks based on existing bookmarks or headings. You can accomplish this by enabling either the CreateWordsBookmarks property or the CreateWordBookmarksUsingHeadings property of the ToPdfParameterList object.

The steps to create bookmark while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Generate bookmarks in PDF based on the existing bookmarks of the Word document by settings CreateWordsBookmarks property to true.
  • Save the Word document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace CreateBookmarkWhenConverting
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Create bookmarks in PDF from existing bookmarks in Word
            parameters.CreateWordBookmarks = true;

            // Create bookmarks from Word headings
            // parameters.CreateWordBookmarksUsingHeadings= true;

            // Save the document to PDF
            doc.SaveToFile("CreateBookmarks.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Disable Hyperlinks while Converting Word to PDF in C#

While converting a Word document to PDF, there are instances where it may be necessary to deactivate hyperlinks. This can be done to prevent accidental clicks or to maintain a static view of the document without any navigation away from its pages.

To disable hyperlinks during the conversion process, simply set the DisableLink property of the ToPdfParameterList object to true. By doing so, the resulting PDF will not contain any active hyperlinks.

The steps to disable hyperlinks while converting Word to PDF in C# are as follows.

  • Create a Document object.
  • Load a sample Word document from a given file path.
  • Create a ToPdfParameterList object, which is used to set the conversion options.
  • Disable hyperlinks by settings DisableLink property to true.
  • Save the Word document to PDF using Doucment.SaveToFile(string fileName, ToPdfParameterList paramList) method.
  • C#
using Spire.Doc;

namespace DisableHyperlinks
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word document
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.docx");

            // Create a ToPdfParameterList object
            ToPdfParameterList parameters = new ToPdfParameterList();

            // Disable hyperlinks
            parameters.DisableLink = true;

            // Save the document to PDF
            doc.SaveToFile("DisableHyperlinks.pdf", parameters);

            // Dispose resources
            doc.Dispose();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 03 April 2024 01:14