(C# Version ) PDF Viewer Control Without Acrobat Reader Installed

by Julian Joseph - India, 17 Apr 2015

Introduction

This Article shows how we can display PDF on Web without having to install any third party pdf tool on either client or server. 

Background

The Article is original written by Ron Schuler in VB.NET. I have converted it in C#.   His article discusses how to create a .NET PDF Viewer control that is not dependent on Acrobat software being installed

Ron Schuler Article Link : http://www.codeproject.com/Articles/37458/PDF-Viewer-Control-Without-Acrobat-Reader-Installe

Using the code 

  1. Create a web site project in Visual Studio
  2. Add the folder images , pdf and render
  3. Copy all imaged for the toolbar in Images folder
  4. Copy all .dll files into bin folder
  5. Create a default.aspx and copy code from below
  6. Create a PDFView.ascx UserControl and copy the code from below
  7. Execute the project (The target Framework should be .NET 3.5 or else the project wont run)

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default"%>
<!-- Add the User Control Reference-->
<%@ Register src="~/PDFViewer.ascx" tagname="PDFViewer" tagprefix="uc1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>PDF Viewer</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="height: 509px; width: 100%; margin-left: 0px; background-color: #FFFFFF;">
    <asp:FileUpload runat="server" ID="FileUpload1" />
     <asp:Button ID="Button1" runat="server" Text="View PDF" 
            onclick="Button1_Click" />
        &nbsp;&nbsp;<asp:Label ID="ErrorLabel" runat="server" Text="" ForeColor="#CC0000" Visible="False"></asp:Label>
        <uc1:PDFViewer ID="PDFViewer1" runat="server"  /> <!-- Add the User Control-->
    </div>
    </form>
</body>
</html>


Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PDFViewASP;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.HasFile)
        {
            if (ImageUtil.IsPDF(FileUpload1.FileName))
            {
                ErrorLabel.Visible = false;
                String savePath = Request.MapPath("PDF") + "\\" + FileUpload1.FileName;
                FileUpload1.SaveAs(savePath);
                PDFViewer1.FileName = savePath;
            }
            else
            {
                ErrorLabel.Text = "Only PDF files (*.pdf) are allowed to be uploaded.";
                ErrorLabel.Visible = true;
            }
        }
    }
}

 

PDFView.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="PDFViewer.ascx.cs" Inherits="PDFViewer"%>
<%@ Register Assembly="StatefullScrollPanel" Namespace="CustomControls" TagPrefix="cc1"%>
<asp:Panel ID="MainPanel" runat="server" Height="100%" Width="100%" 
    Wrap="False" Enabled="False">
   
        <asp:Table ID="ToolStripTable" runat="server" CellPadding="5">
            <asp:TableRow ID="TableRow1" runat="server" VerticalAlign="Middle" HorizontalAlign="Left">
                <asp:TableCell ID="TableCell1" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:Label ID="PageLabel" runat="server" Text="Page 001 of 001" ></asp:Label>
                </asp:TableCell>
                <asp:TableCell ID="TableCell2" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="PreviousPageButton" runat="server" ImageUrl="images/Previous_24x24.png" ToolTip="Previous Page"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell3" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="NextPageButton" runat="server" ImageUrl="images/Next_24x24.png" ToolTip="Next Page"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell4" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:Label ID="GoToLabel" runat="server" Text="Go to page" ></asp:Label>
                </asp:TableCell>
                <asp:TableCell ID="TableCell5" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:TextBox ID="PageNumberTextBox" runat="server" MaxLength="5" Width="35px" ToolTip="Page number to go to"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="TableCell6" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="ZoomOutButton" runat="server" ImageUrl="images/Zoom Out_24x24.png" ToolTip="Zoom Out"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell7" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="ZoomInButton" runat="server" ImageUrl="images/Zoom In_24x24.png" ToolTip="Zoom In"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell8" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="RotateCCButton" runat="server" ImageUrl="images/Undo_24x24.png" ToolTip="Rotate the page counter-clockwise"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell9" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="RotateCButton" runat="server" ImageUrl="images/Redo_24x24.png" ToolTip="Rotate the page clockwise"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell10" runat="server" VerticalAlign="Middle" HorizontalAlign="Center" Width="24px">
                    <asp:ImageButton ID="FitToScreenButton" runat="server" ImageUrl="images/FitToScreen.png" ToolTip="View document where the entire page fits in the window"/>      
                </asp:TableCell>
                <asp:TableCell ID="TableCell11" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="FitToWidthButton" runat="server" ImageUrl="images/FitToWidth.png" ToolTip="View document where the page's width fits in the window"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell12" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="ActualSizeButton" runat="server" ImageUrl="images/ActualSize.png" ToolTip="View document at 150 DPI"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell13" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="SearchButton" runat="server" ImageUrl="images/Search_24x24.png" ToolTip="Search from the beginning of the document"/>                   
                </asp:TableCell>
                <asp:TableCell ID="TableCell14" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:TextBox ID="SearchTextBox" runat="server" MaxLength="100" Width="100px" ToolTip="Text to search for"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="TableCell15" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="SearchPreviousButton" runat="server" ImageUrl="images/SearchPrevious.png" ToolTip="Search for previous match"/>
                </asp:TableCell>
                <asp:TableCell ID="TableCell16" runat="server" VerticalAlign="Middle" HorizontalAlign="Center">
                    <asp:ImageButton ID="SearchNextButton" runat="server" ImageUrl="images/SearchNext.png" ToolTip="Search for next match"/>
                </asp:TableCell>                
            </asp:TableRow>
        </asp:Table>
  
    <asp:Panel ID="PicPanel" runat="server" Height="100%" Width ="100%">
        <asp:Table ID="Table1" runat="server" GridLines="Both" Height="100%" style="margin-right: 0px" Width="100%">
            <asp:TableRow ID="TableRow2" runat="server" VerticalAlign="Top" HorizontalAlign="Left">
                <asp:TableCell ID="BookmarkCell" runat="server" Width="15%" Height="100%" VerticalAlign="Top" HorizontalAlign="Left" >                       
                   <cc1:StatefullScrollPanel ID="BookmarkPanel" runat="server" ScrollBars="Auto" Width="150px" Height="700px">
                        <asp:Table ID="BookmarkTable" runat="server" Width="100%" Height="100%">
                            <asp:TableRow ID="BookmarkRow" runat="server" VerticalAlign="Top" HorizontalAlign="Left" Width="100%" Height="100%" >
                                <asp:TableCell ID="BookmarkContentCell"  runat="server" Width="100%" Height="100%" VerticalAlign="Top" HorizontalAlign="Left"></asp:TableCell>
                            </asp:TableRow>
                        </asp:Table>
                    </cc1:StatefullScrollPanel>
                </asp:TableCell>
                <asp:TableCell ID="PicCell" runat="server"  Width="85%" Height="100%" VerticalAlign="Top" HorizontalAlign="Center">
                <cc1:StatefullScrollPanel ID="ImagePanel" runat="server" ScrollBars="Auto" BackColor="Silver" Width="700px" Height="700px" HorizontalAlign="Center">
                      <asp:Image ID="CurrentPageImage" runat="server" ImageAlign="Middle" />
                </cc1:StatefullScrollPanel></asp:TableCell>
            </asp:TableRow>
        </asp:Table>
    </asp:Panel>
</asp:Panel>
<asp:HiddenField ID="HiddenPageNumber" runat="server" />
<asp:HiddenField ID="HiddenBrowserWidth" runat="server" value ="700"/>
<asp:HiddenField ID="HiddenBrowserHeight" runat="server" value ="700" />
<asp:Button ID="HiddenPageNav" runat="server" Height="0px" Width="16px" 
    BorderStyle="None" BackColor="Transparent" />
<script type="text/javascript">
    function changePage(pageNum) {
        getBrowserDimensions();
        document.getElementById("<%=HiddenPageNumber.ClientID%>").value = pageNum;
        document.getElementById("<%=HiddenPageNav.ClientID%>").click();
    }

    function getElement(aID) {
        return (document.getElementById) ?
   document.getElementById(aID) : document.all[aID];
    }

    function getBrowserDimensions() {
        if (typeof (window.innerWidth) == 'number') {
            //Non-IE
            browserWidth = window.innerWidth;
            browserHeight = window.innerHeight;
        } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
            //IE 6+ in 'standards compliant mode'
            browserWidth = document.documentElement.clientWidth;
            browserHeight = document.documentElement.clientHeight;
        } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
            //IE 4 compatible
            browserWidth = document.body.clientWidth;
            browserHeight = document.body.clientHeight;
        }
        document.getElementById("<%=HiddenBrowserWidth.ClientID%>").value = browserWidth;
        document.getElementById("<%=HiddenBrowserHeight.ClientID%>").value = browserHeight;
    }

</script>
<body onload="getBrowserDimensions();" />

 

PDFView.ascx.cs 

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
using System.Drawing;
using PDFLibNet;
using System.ComponentModel;
using PDFViewASP;
using System.Web.Caching;

public partial class PDFViewer : System.Web.UI.UserControl
{

   
    public Hashtable parameterHash;
    private float panelHeightFactor = 0.9f;
    private float panelWidthFactor = 0.73f;
    private float panelBookWidthFactor = 0.24f;
    private float zoomFactor = 1.25f;
    private int minDPI = 20;
    private int maxDPI = 400;
   
    private int baseDPI = 150;

   

    public string FileName
    {
        get { return parameterHash["PDFFileName"].ToString(); }
        set
        {
            if (null == value | string.IsNullOrEmpty(value))
            {
                this.Enabled = false;
                return;
            }
            if (ImageUtil.IsPDF(value))
            {
                this.Enabled = true;
                InitUserVariables();
                parameterHash["PDFFileName"] = value;
                InitPageRange();
                InitRotation();
                parameterHash["PagesOnly"] = false;
                InitBookmarks();
                FitToWidthButton_Click(null, null);
            }
        }
    }

    public bool Enabled
    {
        set { MainPanel.Enabled = value; }
    }

   

    #region "Control based events"

    //Need to delete the last image of the page viewed
      
    private void Page_Init(object sender, System.EventArgs e)
    {
        
        //Persist User control state
        Page.RegisterRequiresControlState(this);
    }
     private void Page_Load(object sender, System.EventArgs e)
    {
        
        //Persist User control state
        Control_load();
    }
    protected override object SaveControlState()
    {
        return parameterHash;
    }

    protected override void LoadControlState(object savedState)
    {
        parameterHash = (Hashtable)savedState;
    }

    protected void Control_load()
    {
        ResizePanels();
        if ((null != parameterHash))
        {
            parameterHash["SearchText"] = SearchTextBox.Text;
        }
        PreviousPageButton.Attributes.Add("onclick", "getBrowserDimensions()");
        NextPageButton.Attributes.Add("onclick", "getBrowserDimensions()");
        ZoomInButton.Attributes.Add("onclick", "getBrowserDimensions()");
        ZoomOutButton.Attributes.Add("onclick", "getBrowserDimensions()");
        RotateCCButton.Attributes.Add("onclick", "getBrowserDimensions()");
        RotateCButton.Attributes.Add("onclick", "getBrowserDimensions()");

        HiddenPageNav.Click += new System.EventHandler(this.HiddenPageNav_Click);
        PageNumberTextBox.TextChanged += new System.EventHandler(this.PageNumberTextBox_TextChanged);
        PreviousPageButton.Click += new System.Web.UI.ImageClickEventHandler(this.PreviousPageButton_Click);
        NextPageButton.Click += new System.Web.UI.ImageClickEventHandler(this.NextPageButton_Click);
        ZoomOutButton.Click += new System.Web.UI.ImageClickEventHandler(this.ZoomOutButton_Click);
        ZoomInButton.Click += new System.Web.UI.ImageClickEventHandler(this.ZoomInButton_Click);
        RotateCCButton.Click += new System.Web.UI.ImageClickEventHandler(this.RotateCCButton_Click);
        RotateCButton.Click += new System.Web.UI.ImageClickEventHandler(this.RotateCButton_Click);
        FitToScreenButton.Click += new System.Web.UI.ImageClickEventHandler(this.FitToScreenButton_Click);
        FitToWidthButton.Click += new System.Web.UI.ImageClickEventHandler(this.FitToWidthButton_Click);
        ActualSizeButton.Click += new System.Web.UI.ImageClickEventHandler(this.ActualSizeButton_Click);
        SearchButton.Click += new System.Web.UI.ImageClickEventHandler(this.SearchButton_Click);
        SearchNextButton.Click += new System.Web.UI.ImageClickEventHandler(this.SearchNextButton_Click);
        SearchPreviousButton.Click += new System.Web.UI.ImageClickEventHandler(this.SearchPreviousButton_Click);

    }

    protected void FitToScreenButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        Size panelsize = new Size(Convert.ToInt16(Convert.ToDouble(HiddenBrowserWidth.Value) * panelWidthFactor), Convert.ToInt16(Convert.ToDouble(HiddenBrowserHeight.Value) * panelHeightFactor));
        parameterHash["DPI"] = AFPDFLibUtil.GetOptimalDPI(Convert.ToString(parameterHash["PDFFileName"]), Convert.ToInt16(parameterHash["CurrentPageNumber"]), ref panelsize);
        DisplayCurrentPage(false);
    }

    protected void FitToWidthButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        Size panelsize = new Size(Convert.ToInt16(Convert.ToDouble(HiddenBrowserWidth.Value) * panelWidthFactor), Convert.ToInt16(Convert.ToDouble(HiddenBrowserHeight.Value) * 4));
        parameterHash["DPI"] = AFPDFLibUtil.GetOptimalDPI(Convert.ToString(parameterHash["PDFFileName"]), Convert.ToInt16(parameterHash["CurrentPageNumber"]), ref panelsize);
        DisplayCurrentPage(false);
    }

    protected void ActualSizeButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["DPI"] = 150;
        DisplayCurrentPage(false);
    }

    protected void SearchButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["SearchDirection"] = AFPDFLibUtil.SearchDirection.FromBeginning;
        DisplayCurrentPage(true);
        //BookmarkContentCell.Text = AFPDFLibUtil.BuildHTMLBookmarksFromSearchResults( _
        //AFPDFLibUtil.GetAllSearchResults(parameterHash["PDFFileName"), parameterHash["SearchText")) _
        //)
    }

    protected void SearchNextButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["SearchDirection"] = AFPDFLibUtil.SearchDirection.Forwards;
        DisplayCurrentPage(true);
    }

    protected void SearchPreviousButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["SearchDirection"] = AFPDFLibUtil.SearchDirection.Backwards;
        DisplayCurrentPage(true);
    }

    protected void HiddenPageNav_Click(object sender, EventArgs e)
    {
        parameterHash["CurrentPageNumber"] = HiddenPageNumber.Value;
        DisplayCurrentPage(false);
    }
    protected void PageNumberTextBox_TextChanged(object sender, EventArgs e)
    {
        if (Regex.IsMatch(PageNumberTextBox.Text, "^\\d+$"))
        {
            parameterHash["CurrentPageNumber"] = PageNumberTextBox.Text;
            DisplayCurrentPage(false);
        }
    }
    protected void PreviousPageButton_Click(object sender, System.Web.UI.ImageClickEventArgs e) 
    {
        parameterHash["CurrentPageNumber"] = Convert.ToInt16(parameterHash["CurrentPageNumber"]) - 1;
        DisplayCurrentPage(false);
    }

    protected void NextPageButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["CurrentPageNumber"] = Convert.ToInt16(parameterHash["CurrentPageNumber"]) + 1;
        DisplayCurrentPage(false);
    }
   

    protected void ZoomOutButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["DPI"] = Convert.ToDouble(parameterHash["DPI"]) / zoomFactor;
        if (Convert.ToDouble(parameterHash["DPI"]) < minDPI)
        {
            parameterHash["DPI"] = minDPI;
        }
        DisplayCurrentPage(false);
    }

    protected void ZoomInButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        parameterHash["DPI"] = Convert.ToDouble(parameterHash["DPI"])  * zoomFactor;
        if (Convert.ToDouble(parameterHash["DPI"]) > maxDPI)
        {
            parameterHash["DPI"] = Convert.ToInt32(maxDPI);
        }
        DisplayCurrentPage(false);
    }

    protected void RotateCCButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        int indexNum = Convert.ToInt32(parameterHash["CurrentPageNumber"]) - 1;
         ((List<int>)parameterHash["RotationPage"])[indexNum] -= 1;
       // ((List<int>)parameterHash["RotationPage"])[indexNum] = 1;
        DisplayCurrentPage(false);
    }

    protected void RotateCButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
    {
        int indexNum = (Convert.ToInt32(parameterHash["CurrentPageNumber"]) - 1);
        //parameterHash["RotationPage"](indexNum) += 1;
        ((List<int>)parameterHash["RotationPage"])[indexNum] += 1;
        DisplayCurrentPage(false);
    }

    #endregion

    #region "Constraints"

    private void CheckPageBounds()
    {
        int pageCount = (int)parameterHash["PDFPageCount"];

        if (Convert.ToInt16(parameterHash["CurrentPageNumber"]) >= pageCount)
        {
            parameterHash["CurrentPageNumber"] = pageCount;
            NextPageButton.Enabled = false;
        }
        else if (Convert.ToInt16(parameterHash["CurrentPageNumber"]) <= 1)
        {
            parameterHash["CurrentPageNumber"] = 1;
            PreviousPageButton.Enabled = false;
        }

        if (Convert.ToInt16(parameterHash["CurrentPageNumber"]) < pageCount & pageCount > 1 & Convert.ToInt16(parameterHash["CurrentPageNumber"]) > 1)
        {
            NextPageButton.Enabled = true;
            PreviousPageButton.Enabled = true;
        }

        if (Convert.ToInt16(parameterHash["CurrentPageNumber"]) == pageCount & pageCount > 1 & Convert.ToInt16(parameterHash["CurrentPageNumber"]) > 1)
        {
            PreviousPageButton.Enabled = true;
        }

        if (Convert.ToInt16(parameterHash["CurrentPageNumber"]) == 1 & pageCount > 1)
        {
            NextPageButton.Enabled = true;
        }

        if (pageCount == 1)
        {
            NextPageButton.Enabled = false;
            PreviousPageButton.Enabled = false;
        }

    }

    #endregion

    #region "Helper Functions"

    private void InitUserVariables()
    {
        parameterHash = new Hashtable();
        parameterHash.Add("PDFFileName", "");
        parameterHash.Add("PDFPageCount", 0);
        parameterHash.Add("CurrentPageNumber", 1);
        parameterHash.Add("UserPassword", "");
        parameterHash.Add("OwnerPassword", "");
        parameterHash.Add("Password", "");
        parameterHash.Add("DPI", baseDPI);
        parameterHash.Add("PagesOnly", false);
        parameterHash.Add("CurrentImageFileName", "");
        parameterHash.Add("Rotation", new List<int>());
        parameterHash.Add("Bookmarks", "");
        parameterHash.Add("SearchText", "");
        parameterHash.Add("SearchDirection", AFPDFLibUtil.SearchDirection.FromBeginning);
    }

    private void UpdatePageLabel()
    {
        PageLabel.Text = "Page " + parameterHash["CurrentPageNumber"] + " of " + parameterHash["PDFPageCount"];
        PageNumberTextBox.Text = parameterHash["CurrentPageNumber"].ToString();
    }

    private void InitPageRange()
    {
        parameterHash["PDFPageCount"] = ImageUtil.GetImageFrameCount(parameterHash["PDFFileName"].ToString(), parameterHash["Password"].ToString());
        parameterHash["CurrentPageNumber"] = 1;
    }

    private void InitBookmarks()
    {
        PDFLibNet.PDFWrapper pdfDoc = default(PDFLibNet.PDFWrapper);
        try
        {
            pdfDoc = new PDFLibNet.PDFWrapper();
            pdfDoc.LoadPDF(parameterHash["PDFFileName"].ToString());
        }
        catch (Exception ex)
        {
            //pdfDoc failed
            if ((null != pdfDoc))
            {
                pdfDoc.Dispose();
            }
        }
        string bookmarkHtml = "";
        if ((null != pdfDoc))
        {
            bool pagesOnly = (bool) parameterHash["PagesOnly"];
            bookmarkHtml = AFPDFLibUtil.BuildHTMLBookmarks(ref pdfDoc ,pagesOnly);
            pdfDoc.Dispose();
        }
        BookmarkContentCell.Text = bookmarkHtml;
        if (Regex.IsMatch(bookmarkHtml, "\\<\\!--PageNumberOnly--\\>"))
        {
            parameterHash["PagesOnly"] = true;
        }
    }

    private void InitRotation()
    {
        parameterHash["RotationPage"] = new List<int>();
        for (int i = 1; i <= (int)parameterHash["PDFPageCount"]; i++)
        {
            ((List<int>)parameterHash["RotationPage"]).Add(0);
        }
    }

    private void ResizePanels()
    {
        if (!string.IsNullOrEmpty(HiddenBrowserWidth.Value) & !string.IsNullOrEmpty(HiddenBrowserHeight.Value))
        {
            BookmarkPanel.Width = Convert.ToInt32(100 * panelBookWidthFactor);

            BookmarkPanel.Width = Convert.ToInt32(Convert.ToDouble(HiddenBrowserWidth.Value) * panelBookWidthFactor);
            BookmarkPanel.Height = Convert.ToInt32(Convert.ToDouble(HiddenBrowserHeight.Value) * panelHeightFactor); 
            ImagePanel.Width = Convert.ToInt32(Convert.ToDouble(HiddenBrowserWidth.Value) * panelWidthFactor);
            ImagePanel.Height = Convert.ToInt32(Convert.ToDouble(HiddenBrowserHeight.Value) * panelHeightFactor); 
        }
    }

    private void DisplayCurrentPage(bool doSearch )
    {
        //Set how long to wait before deleting the generated PNG file
        DateTime expirationDate = DateTime.Now.AddMinutes(5);
        TimeSpan noSlide = System.Web.Caching.Cache.NoSlidingExpiration;
        CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(OnCacheRemove);
        ResizePanels();
        CheckPageBounds();
        UpdatePageLabel();
        InitBookmarks();
        string destPath = Request.MapPath("render");
        int indexNum = (Convert.ToInt16(parameterHash["CurrentPageNumber"]) - 1);
        int numRotation = Convert.ToInt16(((List<int>)parameterHash["RotationPage"])[indexNum]);
        string imageLocation = null;
        int CurrentPageNumber = Convert.ToInt16( parameterHash["CurrentPageNumber"]);
        if (doSearch == false)
        {
            imageLocation = ASPPDFLib.GetPageFromPDF(Convert.ToString(parameterHash["PDFFileName"]), destPath, ref CurrentPageNumber, Convert.ToInt32(parameterHash["DPI"]), Convert.ToString(parameterHash["Password"]), numRotation, "", 0);
        }
        else
        {
            imageLocation = ASPPDFLib.GetPageFromPDF(Convert.ToString(parameterHash["PDFFileName"]), destPath, ref CurrentPageNumber, Convert.ToInt32(parameterHash["DPI"]), Convert.ToString(parameterHash["Password"]), numRotation, Convert.ToString(parameterHash["SearchText"]), Convert.ToInt32(parameterHash["SearchDirection"]));
            UpdatePageLabel();
        }
        ImageUtil.DeleteFile(parameterHash["CurrentImageFileName"].ToString());
        parameterHash["CurrentImageFileName"] = imageLocation;
        //Add full filename to the Cache with an expiration
        //When the expiration occurs, it will call OnCacheRemove whih will delete the file
        //string sguid = new Guid().ToString()
        Cache.Insert(new Guid().ToString() + "_DeleteFile", imageLocation, null, expirationDate, noSlide, System.Web.Caching.CacheItemPriority.Default, callBack);
        string matchString = Request.MapPath("").Replace("\\", "\\\\");
        // escape backslashes
        CurrentPageImage.ImageUrl = Regex.Replace(imageLocation, matchString + "\\\\", "~/");
    }

    private void OnCacheRemove(string key, object val, CacheItemRemovedReason reason)
    {
        if (Regex.IsMatch(key, "DeleteFile"))
        {
            ImageUtil.DeleteFile(val.ToString());
        }
    }

    #endregion

    public PDFViewer()
    {
     
      //  Init += Page_Init;
    }

  
}

 

Points of Interest

Please NOTE that the dlls only support .NET 3.5 version and hence the application will not run on .NET 4 or higher.

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

src: http://www.codeproject.com/Tips/897735/Csharp-Version-PDF-Viewer-Control-Without-Acrobat

posted @ 2015-04-20 06:59  testglen  阅读(2467)  评论(0编辑  收藏  举报