This article offers you to understand how to convert any file to PDF format using Spire.PDF.

Introduction

This article offers you to understand how to convert any file to PDF format using Spire.Office. As a programmer, you have got chance to write the code to convert a file into other format or PDF. There is not any in-build library available in .Net which helps you in conversion of files in one format to other format. If you will try to convert, you have to write complex code that will take time.

Spire Office

What is Spire Office Library?

As per E-ICEBLUE, “Spire.Office for .NET is a combination of Enterprise-Level Office .NET components offered by E-iceblue. It includes Spire.Doc,  Spire.XLSSpire.Spreadsheet,  Spire.PresentationSpire.PDF,  Spire.DataExport,  Spire.OfficeViewerSpire.PDFViewerSpire.DocViewerSpire.Barcode and Spire.Email. Spire.Office contains the most up-to-date versions of the above .NET components.

https://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html#.WjFpmI-CzIU

 

Why is it good to use for C# Programmer?

This library is fully written in C# and also support VB.NET as well and designed in that way so that it can be implemented in Windows and Web both type applications. As written in C#, it provides you more flexibility so that you can also integrated it with your C# code easily.

To use all featuers of Spire.Office, you have to use License version of it and its paid. If you would like to use it free with your project, then you can do. Because Spire.Office is also available as a free version in NuGet.

But as it's free. It has some limitation like you cannot process more than 10 page. If you will try to do that will get error as below which says "Free edition only supports 10 slides".

Spire Limit

and PDF document will print Spire.Office at the end of the document which defines that you have used Spire.Office for this conversion. But yes if your requirement is going to be completed with free version than you should use it otherwise go with license version.

Spire PDF Limit

 

Spire.Office has different components for different purpose.

1. Spire.Doc : For Microsoft Office Word Document

2. Spire.XLX:  For Microsoft Office Excel Document

3. Spire.PDF:  For PDF document

and many more.
 

Best about Spire.Office

It is fully independent. It means, you don’t need any third party libraries or any prerequisites required or don’t need to be installed Adobe Reader on system.

Spire.PDF supports multiple versions of the PDF. So, here you can easily use it with old project which use lower version of the PDF.

It supports both 32-bit OS as well as 64-bit OS.

 

What we can do with Spire.Office

Several tasks can be completed with Spire.Office. Here we are describing some of them as following.

Convert Document to PDF

  1. Image to PDF
  2. Word to PDF
  3. PowerPoint to PDF
  4. Excel to PDF
  5. HTML to PDF
  6. Txt to PDF

Convert PDF to any other format

Merge multiple documents

Split Documents

Protect Document using passwords or digital signature

Decrypt Documents

and much more

 

Using the code

It's time to practical implementation of the Spire.Office in Asp.Net MVC project where we will see how we can convert differents types of files like DOCX, XLSX, PPT, TXT, HTML to PDF. So, lets start with coding.

First create a new project in Visual Studio, to create new project follow steps as following.

1. Open Visual Studio 2013/2015/2017.

2. Go to File Menu > New > Project.

3.  Choose Visual C# > From the right pane choose "Asp.Net Web Application" and provide name of the project and click to OK.

4.  From next windows choose MVC as a template and OK.

Project is ready for run.

In this demonstration, we will create a View from where we can browse multiple files at a time and when click to Convert To PDF button; it will perform conversion operation based on files "Content-Type". It is because, different content type of the files might be same code for conversion from one format to other format.

 

Install Free Spire.Office

To install Spire.Office, open NuGet Package Manager and search for Spire. Here you will 

Free Spire.Office and Spire.PDF

After installing Spire.Office, all the possible components will be added in reference section as shown below.

Spire.PDF Reference

 

Before moving to convert files to PDF format, we have to find the Content-Type of the file than, basis of Content-Type we can perform operation to convert it to PDF.

Convert DOCX to PDF

First we are going to convert DOCX file into PDF, so do that first need to check target location where PDF will save after conversion as well as file name. If both are available than we have to create a new Spire documnet and load the file which need to be converted into PDF. Once doc file will load than we have to save it at desired location as well as desired format, here we are saving it into PDF format. Find the whole code which will convert your DOCX file into PDF format.

case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
case "application/msword":
case "application/docx":
case "application/doc":
if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
{
    string file = Path.Combine(targetLocation, fileName + ".pdf");

    Spire.Doc.Document document = new Spire.Doc.Document();
    document.LoadFromFile(sourcePath, Spire.Doc.FileFormat.Auto);
    document.SaveToFile(file, Spire.Doc.FileFormat.PDF);
}
break;

Convert XLSX to PDF

Here converting excel file (.xlsx) into PDF, first create instance of Spire workbook and load the file from your local computer path, once file will be loaded than you can save it in PDF format as we have done with Microsoft Word document with above snippet.

case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
case "application/vnd.ms-excel":
case "application/xlsx":
case "application/xls":
case "application/vnd.ms-excel.sheet.macroEnabled.12":
case "application/XLSM":
if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
{
    string file = Path.Combine(targetLocation, fileName + ".pdf");

    Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
    workbook.LoadFromFile(sourcePath, true);
    workbook.SaveToFile(file, Spire.Xls.FileFormat.PDF);
}
break;

Convert PPT to PDF

Now move to convert PPT or Presentation file into PDF, first create instance of Spire Presentation and load the file from your local computer path, once file will be loaded than you can save it in PDF format.

case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
case "application/vnd.ms-powerpoint":
case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
case "application/pptx":
if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
{
    string file = Path.Combine(targetLocation, fileName + ".pdf");

    Presentation presentation = new Presentation();
    presentation.LoadFromFile(sourcePath, Spire.Presentation.FileFormat.PPT);
    presentation.SaveToFile(file, Spire.Presentation.FileFormat.PDF);
}
break;

Convert IMAGE to PDF

Converting images to PDF is little different from others, here first we create a blank PDF document using PdfDocument and create section for it. Inside the section, you have drawn image which has read from file. We can set width and height also if we would like to make change and then it can be saved inside the target location.

case "image/gif":
case "image/jpg":
case "image/png":
case "image/jpeg":
case "application/BMP":
case "image/bmp":
case "image/tiff":
if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
{
    string file = Path.Combine(targetLocation, fileName + ".pdf");

    PdfDocument doc = new PdfDocument();
    PdfSection section = doc.Sections.Add();
    PdfPageBase page = doc.Pages.Add();
    PdfImage image = PdfImage.FromFile(sourcePath);
    float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
    float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
    float fitRate = Math.Max(widthFitRate, heightFitRate);
    float fitWidth = image.PhysicalDimension.Width / fitRate;
    float fitHeight = image.PhysicalDimension.Height / fitRate;
    page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);
    doc.SaveToFile(file);
    doc.Close();
}
break;

Convert HTML or TXT to PDF

Converting Html and Txt, we have to execute same line of codes as shown below. Here we don't load file using "LoadFromFile" method but use "LoadFromHtml". Saving the file into PDF will be same as for above.

case "application/html":
case "application/txt":
case "application/htm":
case "text/html":
case "application/xml":
case "text/plain":
if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
{
    string file = Path.Combine(targetLocation, fileName + ".pdf");

    PdfDocument pdf = new PdfDocument();
    PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat
    {
        Layout = PdfLayoutType.Paginate,
        FitToPage = Clip.Width,
        LoadHtmlTimeout = 60 * 1000
    };
    htmlLayoutFormat.IsWaiting = true;
    PdfPageSettings setting = new PdfPageSettings();
    setting.Size = PdfPageSize.A4;
    Thread thread = new Thread(() => { pdf.LoadFromHTML(sourcePath, true, true, true); });
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    thread.Join();                           
    pdf.SaveToFile(file, Spire.Pdf.FileFormat.PDF);
}
break;

Now move to controller, to perfrom convert operation, we have added new Controller as "FileConvertController" which contains two overloaded action method. 

You can see with below code that here I have defined sourcePath and targetPath manually. You can define it in config as well. 

First we will browse the number of files from client and click to Convert To PDF button than it will perform [HttpPost] action result as defined below. Here we can get all selected files through "HttpPostedFileBase" and call FileHelper.ConvertToPDF method which will take four parameters as below.

Source Path: From where files are selected.

Content Type: Selected file's content type

File Name: Selected file's name

Target Location: Loaction where need to save PDF files after conversion

using ConvertToPDF.Helper;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace ConvertToPDF.Controllers
{
    public class FileConvertController : Controller
    {
        private string sourcePath = @"C:\source";
        private string targetLocation = @"C:\temp";

        FileHelper fileHelper = new FileHelper();

        public ActionResult PDF()
        {
            return View();
        }

        [HttpPost]
        public ActionResult PDF(HttpPostedFileBase[] files)
        {

            if (ModelState.IsValid)
            {
                foreach (var file in files)
                {
                    var fileName = Path.GetFileNameWithoutExtension(file.FileName);
                    var sourceFilePath = Path.Combine(sourcePath, file.FileName);                    

                    fileHelper.ConvertToPDF(sourceFilePath, file.ContentType, fileName, targetLocation);
                }
            }
            return View();
        }
    }
}

Below is the code for PDF view, which will give the User Interface so that we can select multiple files and submit it for conversion into PDF files.

@{
    ViewBag.Title = "PDF";
}

<br />
@using (Html.BeginForm("PDF", "FileConvert", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="container">
      <div class="panel panel-default">
        <div class="panel-heading"><small>Spire PDF Example</small></div>
        <div class="panel-body">
          <h4>Browse any files to convert into PDF format</h4>

          <div class="form-inline">
            <div class="form-group">
              <input type="file" name="files" id="js-upload-files" multiple />
            </div>
            <button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Convert To PDF</button>
          </div>
        </div>
      </div>
    </div>
}

 

Just for reference, following is the whole code for "FileHelper" class.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.HtmlConverter;
using Spire.Presentation;
using System;
using System.IO;
using System.Threading;

namespace ConvertToPDF.Helper
{
    public class FileHelper
    {
        public void ConvertToPDF(string sourcePath, string contentType, string fileName, string targetLocation)
        {
            if (!string.IsNullOrEmpty(sourcePath))
            {
                switch (contentType.ToLower())
                {
                    case "application/vnd.openxmlformats-officedocument.presentationml.presentation":
                    case "application/vnd.ms-powerpoint":
                    case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
                    case "application/pptx":
                        if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
                        {
                            string file = Path.Combine(targetLocation, fileName + ".pdf");

                            Presentation presentation = new Presentation();
                            presentation.LoadFromFile(sourcePath, Spire.Presentation.FileFormat.PPT);
                            presentation.SaveToFile(file, Spire.Presentation.FileFormat.PDF);
                        }
                        break;
                    case "image/gif":
                    case "image/jpg":
                    case "image/png":
                    case "image/jpeg":
                    case "application/BMP":
                    case "image/bmp":
                    case "image/tiff":
                        if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
                        {
                            string file = Path.Combine(targetLocation, fileName + ".pdf");

                            PdfDocument doc = new PdfDocument();
                            PdfSection section = doc.Sections.Add();
                            PdfPageBase page = doc.Pages.Add();
                            PdfImage image = PdfImage.FromFile(sourcePath);
                            float widthFitRate = image.PhysicalDimension.Width / page.Canvas.ClientSize.Width;
                            float heightFitRate = image.PhysicalDimension.Height / page.Canvas.ClientSize.Height;
                            float fitRate = Math.Max(widthFitRate, heightFitRate);
                            float fitWidth = image.PhysicalDimension.Width / fitRate;
                            float fitHeight = image.PhysicalDimension.Height / fitRate;
                            page.Canvas.DrawImage(image, 30, 30, fitWidth, fitHeight);
                            doc.SaveToFile(file);
                            doc.Close();
                        }

                        break;
                    case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                    case "application/vnd.ms-excel":
                    case "application/xlsx":
                    case "application/xls":
                    case "application/vnd.ms-excel.sheet.macroEnabled.12":
                    case "application/XLSM":
                        if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
                        {
                            string file = Path.Combine(targetLocation, fileName + ".pdf");

                            Spire.Xls.Workbook workbook = new Spire.Xls.Workbook();
                            workbook.LoadFromFile(sourcePath, true);
                            workbook.SaveToFile(file, Spire.Xls.FileFormat.PDF);
                        }

                        break;
                    case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                    case "application/msword":
                    case "application/docx":
                    case "application/doc":
                        if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
                        {
                            string file = Path.Combine(targetLocation, fileName + ".pdf");

                            Spire.Doc.Document document = new Spire.Doc.Document();
                            document.LoadFromFile(sourcePath, Spire.Doc.FileFormat.Auto);
                            document.SaveToFile(file, Spire.Doc.FileFormat.PDF);
                        }

                        break;
                    case "application/html":
                    case "application/txt":
                    case "application/htm":
                    case "text/html":
                    case "application/xml":
                    case "text/plain":
                        if (!string.IsNullOrEmpty(targetLocation) && !string.IsNullOrEmpty(fileName))
                        {
                            string file = Path.Combine(targetLocation, fileName + ".pdf");

                            PdfDocument pdf = new PdfDocument();
                            PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat
                            {
                                Layout = PdfLayoutType.Paginate,
                                FitToPage = Clip.Width,
                                LoadHtmlTimeout = 60 * 1000
                            };
                            htmlLayoutFormat.IsWaiting = true;
                            PdfPageSettings setting = new PdfPageSettings();
                            setting.Size = PdfPageSize.A4;
                            Thread thread = new Thread(() => { pdf.LoadFromHTML(sourcePath, true, true, true); });
                            thread.SetApartmentState(ApartmentState.STA);
                            thread.Start();
                            thread.Join();                           
                            pdf.SaveToFile(file, Spire.Pdf.FileFormat.PDF);
                        }
                        break;
                    case "application/msg":
                    case "application/octet-stream":
                    case "multipart/related":
                    case "application/ZIP":
                    case "application/VCF":
                    default:
                        break;
                }

            }
        }
    }
}

So, now everything has setted up and time to run the application and move to following path:

localhost:port/FileConvert/PDF

Once you will move on above URL, you will get following screen. You can see here that there is browse button here, I have already selected 5 files, that is why It shown "5 files" and a button which says "Convert To PDF".

Browse Files for Spire

As we have created two folder for this demonstration "source" and "temp". Source is basically from where we will select files and Temp is basically where files will be saved after conversion. 

You can see clearliy here that we are selecting five different types of files to convert into PDF.

Source Files

 

After selecting above files from Browse windows, when we clicked on "Convert To PDF" button it converted all the files into PDF. You can see as shown below image.

Target PDF files

Conclusion

So, we have seen how we can use free version of Spire.Office and its components to convert files into PDF in one go.

I hope this post helps you. Please put your feedback using comments which will help me improve for the next post. If you have any doubts, please ask your doubts or query in the comments section.