ASP.NET PDF Viewer Control
How to read, view Microsoft Excel with page size setting using C# in ASP.NET


Easy to upload, open, view, display, markup Microsoft Excel document online, and open Excel file with page size settings using ASP.NET C# in web browser











About this tutorial



This tutorial page will setup an ASP.NET web site which allows users to open, view, markup, redate Microsoft Office Excel files content in web browser. You can also apply page size setting before view the Excel file.

Supported page size options:

  • Actual Size
  • Fit to page width
  • Fit Worksheet to a single page






How to read, open, view Microsoft Excel file online with page size settings applied using C#, asp.net



Using EdgePDF, you can allow your web user to open, view, markup Excel documents online in web browser with specified page size settings.

The following steps and code snippet shows you how to load, display Excel file with page size setting.


  1. Setup EdgePDF demo project in IIS
  2. In demo project UserCommandProcessHandler.ashx, load Excel document with page size settings in EdgePDF


The following source code shows how to read, open Microsoft Excel document with required page size settings in UserCommandProcessHandler.ashx



    public byte[] ApplyAddonExcelInOpenFunction(String srcFilePath)
    {
        //  Load source .xlsx file.
        XLSXDocument doc = new XLSXDocument(srcFilePath);
        //  Convert to PDF file with one page for each sheet by actual size.
        using (MemoryStream ms = new MemoryStream())
        {
            doc.ConvertToDocument(DocumentType.PDF, ms);

            using (MemoryStream oStream = new MemoryStream())
            {
                //  Expected page size: width = 8.5 inches; height 11 inches.
                SizeF size = new SizeF(8.5F, 11F);
                //  Fill mode for the sheet content: Fit Width
                PageArrangeOptions.PageFitMode fillMode = PageArrangeOptions.PageFitMode.FitWidth;
                //  Change PDF pages to the specified size.
                PDFDocument.ChangePageSize(ms, oStream, size, fillMode);
                return oStream.ToArray();
            }
        }
    }








Complete source code of UserCommandProcessHandler.ashx



You can find the complete source code for opening, viewing Excel document with required page size settings in the downloaded package /DemoProjects/EdgePDF Demo Project/RasterEdge_Resource_Files/Tutorials/UserCommandProcessHandler-addon-excel.ashx

To use the above tutorial, you need copy the UserCommandProcessHandler-addon-excel.ashx to the EdgePDF project location /RasterEdge_Resource_Files/, and change file name to UserCommandProcessHandler.ashx



<%@ WebHandler Language="C#" Class="UserCommandProcessHandler" %>

using System;
using System.IO;
using System.Drawing;
using System.Web;
using RasterEdge.Imaging.Basic;
using RasterEdge.XDoc.PDF;
using RasterEdge.XDoc.Excel;
using RasterEdge.WDP;
using RasterEdge.XDoc.PDF.HTML5Editor;

public class UserCommandProcessHandler : ProcessHandler
{

    /*
         The SDK will use the following url parameter names, please do not use them
          RECommand, src, filepath, restful
    */
    public override PDFWebDocument FileProcess()
    {
        HttpRequest request = this.Context.Request;

        if (!String.IsNullOrEmpty(request.QueryString["yourtarget"]))
        {
            // load file
            String docid = request.QueryString["yourtarget"];
            try
            {
                if (String.IsNullOrEmpty(docid) || !docid.EndsWith(".xlsx"))
                    throw new Exception("Source file must be a .xlsx file.");

                byte[] dataBytes = ApplyAddonExcelInOpenFunction(@"C:\\temp\" + docid);
                String fileName = docid.Replace(".xlsx", ".pdf");
                return REProcessControl.PageLoadFile(request, this.Manager, dataBytes, fileName);
            }
            catch (Exception ex)
            {
                Logger.Log("FileProcess: fail to open file " + docid + ". " + ex.Message, LogType.ERROR);
                return null;
            }
        }
        else
        {
            Logger.Log(">>> Unknown load file mode. Load default file defined in Web.config.", LogType.DEBUG);

            // load default file. defined in Web.config
            return REProcessControl.PageLoadFile(request, this.Manager, "", LoadType.Server);
        }
    }

    //  fid: Task ID.
    //  savePath: The abosolute path of the saved PDF file in the task's output folder.
    //  responseMsg: The response message for saving the current document to the task's output folder.
    //               The string value is the relative path of the output file. "Error" means that the saving process is failed.
    public override void SaveFile_OnServer(String fid, String savePath, String responseMsg)
    {
        //  You can process saved pdf document here, like add watermark, ...
        var documentPath = savePath;
        if (!String.IsNullOrEmpty(documentPath))
        {
            Logger.LogFile(fid, "SaveFileOnServer: output file path " + documentPath, LogType.DEBUG);

            //  To verify the output file.
            RasterEdge.Imaging.Basic.BaseDocument document = null;
            if (documentPath.EndsWith(".pdf"))
            {
                // document object includes user modified content
                document = new RasterEdge.XDoc.PDF.PDFDocument(documentPath);
            }
            if (document != null)
            {
                RasterEdge.XDoc.PDF.PDFDocument pdfDoc = document as RasterEdge.XDoc.PDF.PDFDocument;
                try
                {
                    //  Post-process
                    RasterEdge.XDoc.PDF.PDFMetadata metadata = pdfDoc.GetDescription();
                    metadata.Producer = "RasterEdge EdgePDF";
                    pdfDoc.SetDescription(metadata);
                }
                catch (Exception ex)
                {
                    //  Process error code, and return error information here
                    Logger.LogFile(fid, ex.Message + ". fail to do post-process.", LogType.ERROR);
                }

                //  Get the upload information of the file
                RasterEdge.WDP.DocUploadInfo docinfo = RasterEdge.WDP.Manager.FileManager.getUploadinfoByFid(fid);
                //  Get your file open url parameters value, if needed.
                String paraFilepathValue = docinfo.GetRequestParameters("yourtarget");
                if (!String.IsNullOrEmpty(paraFilepathValue))
                {
                    try
                    {
                        //  Replace file extension (".xlsx") to ".pdf".
                        int index = paraFilepathValue.LastIndexOf('.');
                        if (index > 0)
                            paraFilepathValue = paraFilepathValue.Substring(0, index);
                        pdfDoc.Save(@"C:\temp\" + paraFilepathValue + ".pdf");
                    }
                    catch (Exception ex)
                    {
                        //  Process error code, and return error information here
                        Logger.LogFile(fid, ex.Message + ". fail to save file to server.", LogType.ERROR);
                    }
                }
                else
                {
                    Logger.LogFile(fid, "no 'yourtarget' in the HTTPRequest.", LogType.INFO);
                }
            }
            else
            {
                Logger.LogFile(fid, "output PDF file is invalid.", LogType.ERROR);
            }
        }
        else
        {
            Logger.LogFile(fid, "fail to save file to server. output file path is null or empty.", LogType.ERROR);
        }
    }

    public byte[] ApplyAddonExcelInOpenFunction(String srcFilePath)
    {
        //  Load source .xlsx file.
        XLSXDocument doc = new XLSXDocument(srcFilePath);
        //  Convert to PDF file with one page for each sheet by actual size.
        using (MemoryStream ms = new MemoryStream())
        {
            doc.ConvertToDocument(DocumentType.PDF, ms);

            using (MemoryStream oStream = new MemoryStream())
            {
                //  Expected page size: width = 8.5 inches; height 11 inches.
                SizeF size = new SizeF(8.5F, 11F);
                //  Fill mode for the sheet content: Fit Width
                PageArrangeOptions.PageFitMode fillMode = PageArrangeOptions.PageFitMode.FitWidth;
                //  Change PDF pages to the specified size.
                PDFDocument.ChangePageSize(ms, oStream, size, fillMode);
                return oStream.ToArray();
            }
        }
    }
}