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.
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.
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.
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();
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();
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();
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();
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.
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); } }
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:
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’;
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!