View Word, Excel, and PowerPoint Files in Angular Application
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (217)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (917)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (148)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (629)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (593)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
View Microsoft Office Files in the PDF Viewer for Angular

View Word, Excel, and PowerPoint Files in Angular Application

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 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 documentation.

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

Create eye-catching presentations with the user-friendly features of the Syncfusion PowerPoint Framework!

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.

File upload option
File upload option

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

<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.

The file chosen with the previous code will be converted to PDF format using 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.

Everything you need to know about Syncfusion’s PowerPoint Framework is well-documented.

Word-to-PDF conversion

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

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.

//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();
Word document converted to PDF and loaded in the PDF Viewer
Word document converted to PDF and loaded in the PDF Viewer

Excel-to-PDF conversion

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

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.

//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();
Excel spreadsheet converted to PDF and loaded in the PDF Viewer
Excel spreadsheet converted to PDF and loaded in the PDF Viewer

Create presentations that stand out. Visit our website to explore our demos and unlock the power of Syncfusion PowerPoint Library today!

PowerPoint-to-PDF conversion

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

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

//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();
PowerPoint document converted to PDF and loaded in the PDF Viewer
PowerPoint document converted to PDF and loaded in the PDF Viewer

Image-to-PDF conversion

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

using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;

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

//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();
Image file converted to PDF and loaded in the PDF Viewer
Image file converted to PDF and loaded in the PDF Viewer

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.

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);
 }
}

Syncfusion’s PowerPoint Framework is cross-platform compatible. Explore its features by platform with interactive demos.

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.

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: 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: 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: 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 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.

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

Are your presentations lacking that wow-factor? Explore the power of Syncfusion’s C# PowerPoint Library, the ultimate solution for creating dynamic and engaging presentations.

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. 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. If you are not a Syncfusion customer, try our 30-day free trial to check out our newest features.

For questions, you can contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed