Thursday, 10 March 2022 06:15

C#/VB.NET: Convert HTML to Images

A common use of HTML is to display data and information on websites, web applications, and a variety of platforms. It is sometimes necessary to convert HTML to images like JPG, PNG, TIFF, BMP etc. since images are difficult to modify and can be accessed by virtually anyone. This article will show you how to perform the HTML to images conversion programmatically in C# and VB.NET 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 HTML to Images

Spire.Doc for .NET offers the Document.SaveToImages() method to convert HTML to Images. Here are detailed steps.

  • Create a Document instance.
  • Load an HTML sample document using Document.LoadFromFile() method.
  • Save the document as an image using Document.SaveToImages() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing.Imaging;

namespace HTMLToImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document mydoc = new Document();
           
            //Load an HTML sample document
            mydoc.LoadFromFile(@"sample.html", FileFormat.Html, XHTMLValidationType.None);
           
            //Save to image. You can convert HTML to BMP, JPEG, PNG, GIF, Tiff etc
            Image image = mydoc.SaveToImages(0, ImageType.Bitmap);
            image.Save("HTMLToImage.png", ImageFormat.Png);
        }
    }
}

C#/VB.NET: Convert HTML to Images

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.

Published in Conversion
Friday, 23 March 2012 02:30

How to Convert Word to Tiff

TIFF (Tagged Image File Format) is a flexible file format that is used to store images, including photos and art images. It’s popular and widely supported by image-manipulation applications, publishing and page layout applications, and scanning, faxing, word processing applications, etc. It can be a container holding compressed (lossy) JPEG and (lossless) PackBits compressed images. The ability to store image data in a lossless format makes a TIFF file to be a useful image archive. Therefore, sometimes developers need to convert documents in other formats (such as word) to TIFF format.

Spire.Doc, a powerful .NET word component which enables developers to convert files from word to TIFF easily. This article is going to introduce you the solution of converting word to TIFF by using Spire.Doc.

Note: before start, please download the latest version of Spire.Doc, then add the .dll in the bin folder as the reference of Visual Studio.

The sample word file:

How to Convert Word to Tiff

Follow the detail steps below:

Step 1: create a new document instance and load a word document from file.

Document document = new Document(@"E:\Program Files\testing.docx");

Step 2: use document.SaveToImages() method to save the word document as Image array.

private static Image[] SaveAsImage(Document document)
{     
    Image[] images = document.SaveToImages(ImageType.Bitmap);    
    return images;
}

Step 3: use JoinTiffImages() method to save the images from word pages to tiff image type, with the specified encoder and image-encoder parameters.

public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
{
    //use the save encoder
    System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
    EncoderParameters ep = new EncoderParameters(2);
    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
    ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);
    Image pages = images[0];
    int frame = 0;
    ImageCodecInfo info = GetEncoderInfo("image/tiff");
    foreach (Image img in images)
    {
        if (frame == 0)
        {
            pages = img;
            //save the first frame
            pages.Save(outFile, info, ep);
        }
        else
        {
            //save the intermediate frames
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
            pages.SaveAdd(img, ep);
        }
        if (frame == images.Length - 1)
        {
            //flush and close.
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
            pages.SaveAdd(ep);
        }
        frame++;
    }
}

The result TIFF file:

How to Convert Word to Tiff

Full codes:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Drawing;
using System.Drawing.Imaging;

namespace convert_word_to_tiff
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document(@"E:\Program Files\testing.docx");
            JoinTiffImages(SaveAsImage(document),"6056result.tiff",EncoderValue.CompressionLZW);
            System.Diagnostics.Process.Start("6056result.tiff");
        }
        private static Image[] SaveAsImage(Document document)
        {     
            Image[] images = document.SaveToImages(ImageType.Bitmap);    
            return images;
        }

        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
            for (int j = 0; j < encoders.Length; j++)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            throw new Exception(mimeType + " mime type not found in ImageCodecInfo");
        }

        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            //use the save encoder
            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
            EncoderParameters ep = new EncoderParameters(2);
            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);
            Image pages = images[0];
            int frame = 0;
            ImageCodecInfo info = GetEncoderInfo("image/tiff");
            foreach (Image img in images)
            {
                if (frame == 0)
                {
                    pages = img;
                    //save the first frame
                    pages.Save(outFile, info, ep);
                }

                else
                {
                    //save the intermediate frames
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    pages.SaveAdd(img, ep);
                }
                if (frame == images.Length - 1)
                {
                    //flush and close.
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports System.Drawing.Imaging

Namespace convert_word_to_tiff
	Class Program
		Private Shared Sub Main(args As String())
			Dim document As New Document("E:\Program Files\testing.docx")
			JoinTiffImages(SaveAsImage(document), "6056result.tiff", EncoderValue.CompressionLZW)
			System.Diagnostics.Process.Start("6056result.tiff")
		End Sub
		Private Shared Function SaveAsImage(document As Document) As Image()
			Dim images As Image() = document.SaveToImages(ImageType.Bitmap)
			Return images
		End Function

		Private Shared Function GetEncoderInfo(mimeType As String) As ImageCodecInfo
			Dim encoders As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
			For j As Integer = 0 To encoders.Length - 1
				If encoders(j).MimeType = mimeType Then
					Return encoders(j)
				End If
			Next
			Throw New Exception(mimeType & Convert.ToString(" mime type not found in ImageCodecInfo"))
		End Function

		Public Shared Sub JoinTiffImages(images As Image(), outFile As String, compressEncoder As EncoderValue)
			'use the save encoder
			Dim enc As System.Drawing.Imaging.Encoder = System.Drawing.Imaging.Encoder.SaveFlag
			Dim ep As New EncoderParameters(2)
			ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.MultiFrame))
			ep.Param(1) = New EncoderParameter(System.Drawing.Imaging.Encoder.Compression, CLng(compressEncoder))
			Dim pages As Image = images(0)
			Dim frame As Integer = 0
			Dim info As ImageCodecInfo = GetEncoderInfo("image/tiff")
			For Each img As Image In images
				If frame = 0 Then
					pages = img
					'save the first frame
					pages.Save(outFile, info, ep)
				Else

					'save the intermediate frames
					ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.FrameDimensionPage))

					pages.SaveAdd(img, ep)
				End If
				If frame = images.Length - 1 Then
					'flush and close.
					ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.Flush))
					pages.SaveAdd(ep)
				End If
				frame += 1
			Next
		End Sub
	End Class
End Namespace

Spire.Doc can convert Word to most of popular file formats. It can convert Word to PDF, HTML, XML, RTF, Text, ePub, etc. Click to learn more

Published in Conversion
Thursday, 09 February 2012 02:49

How to Convert RTF to HTML in C#, VB.NET

Spire.Doc allows users to use C#/VB.NET to convert RTF to HTML. And it's the same easy as conversion from Word to HTML. Now, follow the simple steps to use C#/VB.NET to convert RTF to HTML.

Note: Please make sure Spire.Doc and Visual Studio (Version 2008 or later) are correctly installed on your system.

Step 1: Create Project

Create a windows forms application project in your visual studio and add Spire.Doc dll as reference. Generate a button and double click to go to step 2.

Step 2: C#/VB.NET RTF to HTML Conversion

Spire.Doc offers an easy solution to convert RTF to HTML. Copy and paste the simple C# and VB.NET code into the project.

[C#]
            Document document = new Document();
            document.LoadFromFile(@"D:\Work\Stephen\2012.02.09\C# Create Excel.rtf");
            document.SaveToFile("sample.html", FileFormat.Html);
            WordDocViewer("sample.html");
[VB.NET]
Dim document As New Document()
document.LoadFromFile("D:\Work\Stephen\2012.02.09\C# Create Excel.rtf")
document.SaveToFile("sample.html", FileFormat.Html)
WordDocViewer("sample.html")

Step 3: Save and Preview

To fast preview the effect of RTF to HTML conversion, we can use the code below to save and start project.

[C#]
        private void WordDocViewer(string fileName)
        {
            try
            {
                System.Diagnostics.Process.Start(fileName);
            }
            catch { }
        }
[VB.NET]
Private Sub WordDocViewer(fileName As String)
	Try
		System.Diagnostics.Process.Start(fileName)
	Catch
	End Try
End Sub

Effective Screeshot:

Spire.Doc is a professional word component which enables developers/programmers to fast generate, read, write and modify Word document for .NET and Silverlight. It supports C#, VB.NET, ASP.NET, ASP.NET MVC and Silverlight.

Published in Conversion

Rich Text Format (RTF) is a proprietary text file format which can serve as an exchange format between word processing programs from different manufacturers on different operating systems. Rich text documents include page formatting options, such as custom page margins, line spacing, and tab widths. With rich text, it's easy to create columns, add tables, and format your documents in a way that makes them easier to read. This article will demonstrate how to convert Word Doc/Docx to RTF files and convert RTF to Word Doc/Docx with the help of 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 DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Convert Word Doc/Docx to RTF

The following steps show you how to convert Word to RTF using Spire.Doc for .NET.

  • Create a Document instance.
  • Load a Word sample document using Document.LoadFromFile() method.
  • Save the document as an RTF file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace ConvertToRtf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Word document instance
            Document document = new Document();

            //Load a Word sample document
            document.LoadFromFile("sample.docx");

            // Save the document to RTF
            document.SaveToFile("Result.rtf", FileFormat.Rtf);
        }

    }
}

C#/VB.NET: Convert RTF to Word Doc/Docx and Vice Versa

Convert RTF to Word Doc/Docx

The steps to convert an RTF document to Word Doc/Docx is very similar with that of the above example:

  • Create a Document instance.
  • Load an RTF document using Document.LoadFromFile() method.
  • Save the RTF document to Doc/Docx format using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using System;

public class RtfToDocDocx
{

    public static void Main(String[] args)
    {
        // Create a Document instance
        Document document = new Document();
        // Load an RTF document
        document.LoadFromFile("input.rtf", FileFormat.Rtf);
        // Save the document to Doc
        document.SaveToFile("toDoc.doc", FileFormat.Doc);
        // Save the document to Docx
        document.SaveToFile("toDocx.docx", FileFormat.Docx2013);
    }
}

C#/VB.NET: Convert RTF to Word Doc/Docx and Vice Versa

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.

Published in Conversion

OpenXML is an XML-based file format for MS Office documents. OpenXML is popular among developers as it allows creating and editing Office documents, such Word documents, with no need for MS Office. But when presented to ordinary users, OpenXML files usually need to be converted to Word documents to facilitate reading and editing. In this article, you can learn how to convert XML files to Word documents or Word documents to XML files with the help of 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 an OpenXML File to a Word Document

The detailed steps of the conversion are as follows:

  • Create an object of Document class.
  • Load an OpenXML file from disk using Document.LoadFromFile() method.
  • Convert the OpenXML file to a Word document and save it using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using System;

namespace DocExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a Document class instance
            Document document = new Document();

            //Load an OpenXML file from disk
            document.LoadFromFile(@"C:\Samples\Sample.xml", FileFormat.Xml);

            //Convert the OpenXML file to a Word document and save it
            document.SaveToFile("OpenXMLToWord.docx", FileFormat.Docx2013);
        }
    }
}

C#/VB.NET: Convert OpenXML to Word or Word to OpenXML

Convert a Word Document to an OpenXML File

The detailed steps of the conversion are as follows:

  • Create an object of Document class.
  • Load a Word document from disk using Document.LoadFromFile() method.
  • Convert the Word document to an OpenXML file and save it using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using System;

namespace DocExample
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create a Document class instance
            Document document = new Document();

            //Load a Word document from disk
            document.LoadFromFile(@"C:\Samples\Sample.docx");

            //Convert the Word document to an OpenXML file and save it
            //Change WordXML to WordML to convert to ML file
            document.SaveToFile("WordToOpenXMl.xml", FileFormat.WordXml);
        }
    }
}

C#/VB.NET: Convert OpenXML to Word or Word to OpenXML

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.

Published in Conversion
Wednesday, 25 May 2022 05:49

C#/VB.NET: Convert HTML to Word

HTML is the standard file format of webpage files that are designed to be displayed in web browsers. Due to the lack of full support for HTML elements in Word, most HTML files cannot be rendered properly in Word. If you do want to maintain the HTML layout while exporting it to Word, you need to change the HTML code and avoid using the elements, attributes, and cascading style sheet properties that are not supported. This article will show you how to convert simple HTML files to Word 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 HTML to Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load an HTML file from disk using Document.LoadFromFile().
  • Convert the HTML file to Word and save it using Document.SaveToFile().
  • C#
  • VB.NET
using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace ConvertHTMLtoWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Create an instance of Document
            Document document = new Document();

            //Load an HTML file form disk
            document.LoadFromFile(@"D:\testp\test.html");
            

            //Save the HTML file as Word
            String result = "HtmltoWord.docx";
            document.SaveToFile(result, FileFormat.Docx2013);
        }
   }
}

C#/VB.NET: Convert HTML to Word

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.

Published in Conversion
Friday, 11 March 2022 06:14

C#/VB.NET: Convert Word to HTML

When you'd like to put a Word document on the web, it's recommended that you should convert the document to HTML in order to make it accessible via a web page. This article will demonstrate how to convert Word to HTML programmatically in C# and VB.NET 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 HTML

The following steps show you how to convert Word to HTML using Spire.Doc for .NET.

  • Create a Document instance.
  • Load a Word sample document using Document.LoadFromFile() method.
  • Save the document as an HTML file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace WordToHTML
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document mydoc = new Document();

            //Load a Word document
            mydoc.LoadFromFile("sample.docx");

            //Save to HTML
            mydoc.SaveToFile("WordToHTML.html", FileFormat.Html);
        }
    }
}

C#/VB.NET: Convert Word to HTML

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.

Published in Conversion

Text files are simple and versatile, but they don't support formatting options and advanced features like headers, footers, page numbers, and styles, and cannot include multimedia content like images or tables. Additionally, spell-checking and grammar-checking features are also not available in plain text editors.

If you need to add formatting, multimedia content, or advanced features to a text document, you'll need to convert it to a more advanced format like Word. Similarly, if you need to simplify the formatting of a Word document, reduce its file size, or work with its content using basic tools, you might need to convert it to a plain text format. In this article, we will explain how to convert text files to Word format and convert Word files to text format in C# and VB.NET using Spire.Doc for .NET library.

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 a Text File to Word Format in C# and VB.NET

Spire.Doc for .NET offers the Document.LoadText(string fileName) method which enables you to load a text file. After the text file is loaded, you can easily save it in Word format by using the Document.SaveToFile(string fileName, FileFormat fileFormat) method. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a text file using the Document.LoadText(string fileName) method.
  • Save the text file in Word format using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
  • VB.NET
using Spire.Doc;

namespace ConvertTextToWord
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
            //Load a text file
            doc.LoadText("Sample.txt");

            //Save the text file in Word format
            doc.SaveToFile("TextToWord.docx", FileFormat.Docx2016);
            doc.Close();
        }
    }
}

C#/VB.NET: Convert Text to Word or Word to Text

Convert a Word File to Text Format in C# and VB.NET

To convert a Word file to text format, you just need to load the Word file using the Document.LoadFromFile(string fileName) method, and then call the Document.SaveToFile(string fileName, FileFormat fileFormat) method to save it in text format. The detailed steps are as follows:

  • Initialize an instance of the Document class.
  • Load a Word file using the Document.LoadFromFile(string fileName) method.
  • Save the Word file in text format using the Document.SaveToFile(string fileName, FileFormat fileFormat) method.
  • C#
  • VB.NET
using Spire.Doc;

namespace ConvertWordToText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();
            //Load a Word file
            doc.LoadFromFile(@"Sample.docx");

            //Save the Word file in text format
            doc.SaveToFile("WordToText.txt", FileFormat.Txt);
            doc.Close();
        }
    }
}

C#/VB.NET: Convert Text to Word or Word to Text

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.

Published in Conversion
Friday, 04 March 2022 06:05

C#/VB.NET: Convert XML to PDF

An Extensible Markup Language (XML) file is a standard text file that utilizes customized tags to describe the structure and other features of a document. By converting XML to PDF, you make it easier to share with others since PDF is a more common and ease-to-access file format. This article will demonstrate how to convert XML to PDF in C# and VB.NET 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 XML to PDF

The following are steps to convert XML to PDF using Spire.Doc for .NET.

  • Create a Document instance.
  • Load an XML sample document using Document.LoadFromFile() method.
  • Save the document as a PDF file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;

namespace XMLToPDF
{
   class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document mydoc = new Document();
            //Load an XML sample document
            mydoc.LoadFromFile(@"XML Sample.xml", FileFormat.Xml);
            //Save it to PDF
            mydoc.SaveToFile("XMLToPDF.pdf", FileFormat.PDF);
            
        }
    }
}

C#/VB.NET: Convert XML to PDF

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.

Published in Conversion
Wednesday, 03 April 2024 02:22

C#: Convert Word to PDF

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.

Published in Conversion
Page 3 of 4