View Word, Excel, and PowerPoint Files in Angular Application
Tags: fileformats, angular, webdev, microsoft
Published: 2023-05-12 05:30:29

---
title: View Word, Excel, and PowerPoint Files in Angular Application
published: true
date: 2023-05-11 11:15:00 UTC
tags: fileformats, angular, webdev, microsoft
canonical_url: https://www.syncfusion.com/blogs/post/view-word-excel-powerpoint-in-angular.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zwsrcpl5e41wkkc3mg9r.png
---
This blog explains how to view Microsoft Office files (Word, Excel, and PowerPoint) in an Angular application using the Syncfusion PDF Viewer. This is achieved by converting Microsoft Office files into PDFs and loading them into the PDF Viewer.

The [Syncfusion PDF Viewer](https://www.syncfusion.com/angular-components/angular-pdf-viewer "Angular PDF Viewer") for Angular is a client-server-based component that allows you to view and interact with PDF files in your Angular applications. This component lets you view Microsoft Office files such as Word, Excel, and PowerPoint in the PDF Viewer. To learn more about the Syncfusion Angular PDF Viewer, you can go through the [getting started with Angular PDF Viewer](https://ej2.syncfusion.com/angular/documentation/pdfviewer/getting-started/ "Getting started with Angular PDF Viewer component") documentation.

In this blog, we will create an Angular application to load Word, Excel, PowerPoint, image, and PDF files.

## File upload option

To load and view a file in the Angular PDF Viewer, the file must be uploaded, processed, and displayed.

Following is the screenshot of the upload options we provide in this application.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/File-upload-option.png" alt="File upload option" style="width:100%">

  <figcaption>File upload option</figcaption>

</figure>

The code snippet used to upload files into the PDF Viewer on the client-side is shown.

```xml
<div class="control_wrapper">
  <!-- Initialize Uploader -->
  <div id="dropArea" style="height: auto; overflow: auto">
    <span id="drop">Drop files (Word, Excel, PowerPoint, Image) <a href="" id="browse"><u>Browse</u></a></span>
    <input type="file" name="UploadFiles" id="fileupload" />
  </div>
</div>

<script>
  var dropElement = document.getElementById('dropArea');
  var uploadObj = new ej.inputs.Uploader({
    asyncSettings: {
      saveUrl: 'https://ej2.syncfusion.com/services/api/uploadbox/Save',
      removeUrl: 'https://ej2.syncfusion.com/services/api/uploadbox/Remove',
    },
    dropArea: dropElement,
    selected: onSelect,
    progress: onFileUpload,
    removing: onFileRemove,
    allowedExtensions: '.doc, .docx, .rtf, .docm, .dotm, .dotx, .dot, .xls, .xlsx, .pptx, .pptm, .potx, .potm .jpeg, .png, .bmp',
    template: 'template',
  });

  function uploadFile(args) {
    uploadObj.upload([
       this.filesData[this.fileList.indexOf(args.currentTarget.parentElement)
    ]]);
  }

  function onFileUpload(args) {
    var li = document.getElementById('dropArea')
                     .querySelector('[data-file-name="' + args.file.name + '"]');
    var iconEle = li.querySelector('#iconUpload');
    iconEle.style.cursor = 'not-allowed';
    iconEle.classList.add('e-uploaded');
    ej.base.EventHandler.remove(li.querySelector('#iconUpload'), 'click', uploadFile);
    
    var progressValue = Math.round((args.e.loaded / args.e.total) * 100);
    if (!isNaN(progressValue) && li.querySelector('.progressbar')) {
      li.getElementsByTagName('progress')[0].value = progressValue;
    }
  }
</script>
```

**Note:** Refer to the complete code with the executable [example.](https://github.com/SyncfusionExamples/angular-pdf-viewer-examples/tree/master/Common/View%20Microsoft%20Office%20files%20in%20Angular%20PDF%20Viewer "View Microsoft Office files in Angular PDF Viewer GitHub demo")

The file chosen with the previous code will be converted to PDF format using Syncfusion [document processing libraries](https://www.syncfusion.com/document-processing-libraries "Syncfusion Document Processing Libraries"). Then, the converted PDF file will be loaded into the PDF Viewer. Let’s see how to convert Microsoft Office documents into PDF.

- [Word-to-PDF conversion](#_Word_to_PDF)
- [Excel-to-PDF conversion](#_Excel_to_PDF)
- [PowerPoint-to-PDF conversion](#_PowerPoint_to_PDF)
- [Image-to-PDF conversion](#_Image_to_PDF)

##<a name="_Word_to_PDF">Word-to-PDF conversion</a>

Following are the namespaces required to load a Word document and convert it into a PDF file.

```js
using Syncfusion.DocIO;
Using Syncfusion.DocIO.DLS;
using Syncfusion.DocIORenderer;
Using Syncfusion.Pdf;

```

The following code gets the Word document as a stream and converts it to a PDF document.

```js
//Open the file as a stream.
FileStream inputStream = new FileStream(“Template.docx”, FileMode.Open, FileAccess.Read);

// Loads the Word document from a stream.
WordDocument document = new WordDocument(inputStream, GetWFormatType(type));

//Initialize DocIORenderer for Word to PDF conversion.
DocIORenderer render = new DocIORenderer();

//Converts the Word document into a PDF document.
PdfDocument pdfDocument = render.ConvertToPDF(doc);

inputStream.Dispose();
render.Dispose();
document.Dispose();
PdfDocument.Close();
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Word-document-converted-to-PDF-and-loaded-in-the-PDF-Viewer.png" alt="Word document converted to PDF and loaded in the PDF Viewer" style="width:100%">

  <figcaption>Word document converted to PDF and loaded in the PDF Viewer</figcaption>

</figure>

##<a name="_Excel_to_PDF">Excel-to-PDF conversion</a>

Following are the namespaces required to load and convert an Excel spreadsheet into a PDF file.

```js
using Syncfusion.XlsIO;
using Syncfusion.XlsIORenderer;
using Syncfusion.Pdf;
```

The following code gets the Excel spreadsheet as a stream and converts it to a PDF document.

```js
//Open the file as a stream.
FileStream inputStream = new FileStream(“Template.xlsx”, FileMode.Open, FileAccess.Read);

//Initialize Excel engine.
ExcelEngine excelEngine = new ExcelEngine();

//Loads the workbook from the stream.
Iworkbook workbook = excelEngine.Excel.Workbooks.Open(inputStream);

//Initialize XlsIO renderer.
XlsIORenderer renderer = new XlsIORenderer();

//Convert Excel document into PDF document.
PdfDocument pdfDocument = renderer.ConvertToPDF(workbook);

//Save the workbook.
FileStream outputStream = new FileStream(“Workbook.pdf”, FileMode.Create, FileAccess.Write);
pdfDocument.Save(outputStream);

inputStream.Dispose();
outputStream.Dispose();
PdfDocument.Close();
renderer.Dispose();
workbook.Close();
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Excel-spreadsheet-converted-to-PDF-and-loaded-in-the-PDF-Viewer.png" alt="Excel spreadsheet converted to PDF and loaded in the PDF Viewer" style="width:100%">

  <figcaption>Excel spreadsheet converted to PDF and loaded in the PDF Viewer</figcaption>

</figure>

##<a name="_PowerPoint_to_PDF">PowerPoint-to-PDF conversion</a>

Following are the namespaces required to load and convert PowerPoint presentations into PDF files.

```js
using Syncfusion.Presentation;
using Syncfusion.PresentationToPdfConverter;
using Syncfusion.Pdf;
```

The following code gets the PowerPoint document as a stream and converts it to a PDF file

```js
//Open the file as a stream.
FileStream inputStream = new FileStream(“Template.pptx”, FileMode.Open, FileAccess.Read);

//Loads or opens an existing PowerPoint file as a stream through the Open method.
IPresentation pptxDoc = Presentation.Open(inputStream);

//Convert the PowerPoint document into a PDF document.
PdfDocument pdfDocument = PresentationToPdfConverter.Convert(pptxDoc);

//Save the converted document.
FileStream outputStream = new FileStream(“Presentation.pdf”, FileMode.Create, FileAccess.Write);
pdfDocument.Save(outputStream);

inputStream.Dispose();
outputStream.Dispose();
pdfDocument.Close(true);
pptxDoc.Close();
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/PowerPoint-document-converted-to-PDF-and-loaded-in-the-PDF-Viewer.png" alt="PowerPoint document converted to PDF and loaded in the PDF Viewer" style="width:100%">

  <figcaption>PowerPoint document converted to PDF and loaded in the PDF Viewer</figcaption>

</figure>

##<a name="_Image_to_PDF">Image-to-PDF conversion</a>

Following are the namespaces required to load an image file and convert it into a PDF file.

```js
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
```

The following code gets the image as a stream and converts it to a PDF document.

```js
//Open the file as a stream.
FileStream inputStream = new FileStream(“Image.jpg”, FileMode.Open, FileAccess.Read);

//Create a new PDF document.
PdfDocument pdfDocument = new PdfDocument();

//Add a page to the PDF document.
PdfPage page = pdfDocument.Pages.Add();

//Create PDF graphics for the page.
PdfGraphics graphics = page.Graphics;

//Add an image stream to the graphics.
PdfBitmap image = new PdfBitmap(inputStream);
graphics.DrawImage(image, 0, 0);

//Save the PDF document.
pdfDocument.Save(“ImageToPdf.pdf”);

inputStream.Dispose();
pdfDocument.Close();
```
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/05/Image-file-converted-to-PDF-and-loaded-in-the-PDF-Viewer-1.png" alt="Image file converted to PDF and loaded in the PDF Viewer" style="width:100%">

  <figcaption>Image file converted to PDF and loaded in the PDF Viewer</figcaption>

</figure>

Following is the standard code that converts Word, Excel, PowerPoint, and image files into PDF files in the server and returns the PDF stream to the client to load the PDFs into the Syncfusion PDF Viewer. The code snippets show how to achieve this.

## Client-side code

In the **index.html** file, this code snippet loads the input document (Word, Excel, PowerPoint, or image). It passes the file to the server. Here, a request is made to the **LoadFile** method to pass the file as an object.

```js
Function readURL(li, args) {
  var file = args.rawFile;
  var reader = new FileReader();
  debugger
  var type = args.type;
  reader.addEventListener(‘load’, function () {
     let post = JSON.stringify({
        ‘data’: reader.result,
        ‘type’: type
     })
     const url = “https://localhost:44327/pdfviewer/LoadFile”
     let xhr = new XMLHttpRequest()
     xhr.open(‘Post’, url, true)
     xhr.setRequestHeader(‘Content-type’, ‘application/json; charset=UTF-8’)
     xhr.send(post);
     xhr.onload = function (args) {
       viewer = document.getElementById(‘pdfViewer’).ej2_instances[0];
       viewer.documentPath = this.responseText;
     }
  },
  false
 );
 if (file) {
   reader.readAsDataURL(file);
 }
}
```

## Code at the server-side

The input file is further processed at the server in the **PdfViewerController.cs** file with the following code. The PDF conversions are made, and the converted PDF document is loaded in the PDF Viewer.

```js
Public IactionResult LoadFile ([FromBody] Dictionary<string, string> jsonObject)
{
   if (jsonObject.ContainsKey(“data”))
   {       
        string base64 = jsonObject[“data”];
        //string fileName = args.FileData[0].Name;
        string type = jsonObject[“type”];
        string data = base64.Split(‘,’)[1];
        byte[] bytes = Convert.FromBase64String(data);
        var outputStream = new MemoryStream();
        Syncfusion.Pdf.PdfDocument pdfDocument = new Syncfusion.Pdf.PdfDocument();
        using (Stream stream = new MemoryStream(bytes))
        {
           switch (type)
           {
              case “docx”:
              case “dot”:
              case “doc”:
              case “dotx”:
              case “docm”:
              case “dotm”:
              case “rtf”:
                 WordDocument doc = new WordDocument(stream, GetWFormatType(type));
                 //Initialization of DocIORenderer for Word to PDF conversion.
                 DocIORenderer render = new DocIORenderer();
                 //Converts Word document into PDF document
                 pdfDocument = render.ConvertToPDF(doc);
                 doc.Close();
                 break;
              case “pptx”:
              case “pptm”:
              case “potx”:
              case “potm”:
                 //Loads or opens a PowerPoint presentation.
                 Ipresentation pptxDoc = Presentation.Open(stream);
                 pdfDocument = PresentationToPdfConverter.Convert(pptxDoc);
                 pptxDoc.Close();
                 break;
              case “xlsx”:
              case “xls”:
                 ExcelEngine excelEngine = new ExcelEngine();
                 //Loads or opens an existing workbook through the Open method of Iworkbooks.
                 Iworkbook workbook = excelEngine.Excel.Workbooks.Open(stream);
                 //Initialize XlsIO renderer.
                 XlsIORenderer renderer = new XlsIORenderer();
                 //Convert Excel document into PDF document.
                 pdfDocument = renderer.ConvertToPDF(workbook);
                 workbook.Close();
                 break;
              case “jpeg”:
              case “jpg”:
              case “png”:
              case “bmp”:
                  //Add a page to the document.
                  PdfPage page = pdfDocument.Pages.Add();
                  //Create PDF graphics for the page.
                  PdfGraphics graphics = page.Graphics;
                  PdfBitmap image = new PdfBitmap(stream);
                  //Draw the image.
                  graphics.DrawImage(image, 0, 0);
                  break;
             case “pdf”:
                  string pdfBase64String = Convert.ToBase64String(bytes);
                  return Content(“data:application/pdf;base64,” + pdfBase64String);
                  break;
           }
        }
        pdfDocument.Save(outputStream); 
        outputStream.Position = 0;
        byte[] byteArray= outputStream.ToArray();
        pdfDocument.Close();
        outputStream.Close();
                
        string base64String = Convert.ToBase64String(byteArray); 
        return Content(“data:application/pdf;base64,” + base64String);                
   }
   return Content(“data:application/pdf;base64,” + “”);
}
```

**Note:** Syncfusion provides individual components to view and edit Microsoft Word, Microsoft Excel, and image files. We recommend using these components if you want to use their native, file-specific functionalities:

- [Word Processor](https://www.syncfusion.com/angular-components/angular-word-processor "Angular Word Processor Component"): Used for composing, editing, viewing, and printing Word documents. It provides all the standard word-processing features: editing text, formatting content, resizing images and tables, finding and replacing text, adding bookmarks and tables, printing, and importing and exporting Word documents. 
- [Spreadsheet](https://www.syncfusion.com/angular-components/angular-spreadsheet "Angular Spreadsheet Component"): Used to organize and analyze data in a tabular format. It provides all the standard Excel features, including data binding, selection, editing, formatting, resizing, sorting, and importing and exporting Excel documents. 
- [Image Editor](https://www.syncfusion.com/angular-components/angular-image-editor "Angular Image Editor Component"): Used for editing and enhancing images. It has built-in support for cropping, rotating, flipping, zooming, annotating, and applying filters.

## GitHub sample

You can [download the example](https://github.com/SyncfusionExamples/angular-pdf-viewer-examples/tree/master/Common/View%20Microsoft%20Office%20files%20in%20Angular%20PDF%20Viewer "View Microsoft Office files in Angular PDF Viewer GitHub demo") and use it for your reference. To run it, first, you must run the web service project and copy the published URL into the **app.component.ts** file of the Angular application, as shown in the following.

```js
Public service = ‘https://localhost:44327/pdfviewer’;
```

## Conclusion

Thank you for reading! I hope you enjoyed learning about how to view Microsoft Office files (Word, Excel, and PowerPoint) in your Angular application using the [Syncfusion PDF Viewer](https://www.syncfusion.com/angular-components/angular-pdf-viewer "Angular PDF Viewer"). Please try it out and share your feedback in the comments section below.

The new version of Essential Studio is available for current customers from the [License and Downloads page](https://www.syncfusion.com/account/downloads "Essential Studio license and downloads page"). If you are not a Syncfusion customer, try our 30-day [free trial](https://www.syncfusion.com/downloads "Free evaluation of the Essential Studio products") to check out our newest features.

For questions, you can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Convert Word to PDF programmatically](https://www.syncfusion.com/blogs/post/converting-word-docs-to-pdfs.aspx "Blog: Converting Word to PDF programmatically [C#]")
- [Seamlessly Import and Export CSV Data in Excel Using C#](https://www.syncfusion.com/blogs/post/import-export-csv-data-in-excel-csharp.aspx "Blog: Seamlessly Import and Export CSV Data in Excel Using C#")
- [Creating an ASP.NET Minimal Web API to Generate PDF Documents from HTML Template Dynamically](https://www.syncfusion.com/blogs/post/asp-net-minimal-web-api-to-generate-pdf-documents-from-html-template.aspx "Blog: Creating an ASP.NET Minimal Web API to Generate PDF Documents from HTML Template Dynamically")
- [Restrict Editing of Word Documents Based on User in a Web Application](https://www.syncfusion.com/blogs/post/restrict-editing-of-word-documents-based-on-user-in-a-web-application.aspx "Blog: Restrict Editing of Word Documents Based on User in a Web Application")