ASP.NET - PDF Viewer на C# и .NET


Полный код.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SautinSoft;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        uplPDF.Attributes["onchange"] = "UploadFile(this)";

        if (!this.IsPostBack)
        {
            Session["page"] = 1;
        }
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        int page = (int)Session["page"];
        page++;
        if (IsPageInRange(page))
        {
            Session["page"] = page;
            ShowPdf();
        }
    }

    protected void btnPrev_Click(object sender, EventArgs e)
    {
        int page = (int)Session["page"];
        page--;
        if (IsPageInRange(page))
        {
            Session["page"] = page;
            ShowPdf();
        }
    }

    protected void Upload(object sender, EventArgs e)
    {        
        lblMessage.Visible = true;
        PdfFocus f = new PdfFocus();
        f.OpenPdf(uplPDF.FileBytes);
        Session["focus"] = f;
        ShowPdf();

    }
    protected bool IsPageInRange(int page)
    {
        if (Session["focus"] != null)
        {
            PdfFocus f = (PdfFocus)Session["focus"];

            if (page > 0 && page <= f.PageCount)
                return true;
        }
        return false;
    }

    private void ShowPdf()
    {
        if (Session["focus"] != null)
        {
            PdfFocus f = (PdfFocus)Session["focus"];
            
            if (f.PageCount > 0)
            {
                f.HtmlOptions.IncludeImageInHtml = true;
                f.EmbeddedImagesFormat = PdfFocus.eImageFormat.Png;

                int page = (int)Session["page"];

                string html = f.ToHtml(page, page);
                htmlLiteral.Text = html;
                txtPage.Text = String.Format("Page {0} of {1}", page, f.PageCount);
            }
        }
    }
}

Скачать


 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function () {

            var zoom = 1.0;
            var zoomStep = 0.05;
            var margin = 0;
            var marginStep = 30;

            $('#zoom-in').click(function () {
                margin += marginStep;
                $('#page-window').css({ transform: 'scale(' + (zoom += zoomStep) + ')' });
                var w = $('#page-window').css("width");

                $('#page-window').css({ "margin-left": (margin) });
                $('#page-window').css({ "margin-top": (margin) });
            })
            $('#zoom-out').click(function () {

                margin -= marginStep;

                $('#page-window').css({ transform: 'scale(' + (zoom -= zoomStep) + ')' });
                $('#page-window').css({ "margin-left": margin });
                $('#page-window').css({ "margin-top": margin });


            })
        });
    </script>

    <script type="text/javascript">
        function UploadFile(fileUpload) {
            if (fileUpload.value != '') {
                document.getElementById("<%=btnUpload.ClientID %>").click();
            }
        }
    </script>

</head>
<body>
    <form class="panel-body" id="form1" runat="server">
        <div class="panel">
            <asp:FileUpload ID="uplPDF" runat="server" ToolTip="Please select a PDF document." /><br />
            <asp:Label ID="lblMessage" runat="server" Text="File uploaded successfully." ForeColor="Green"
                Visible="false" />
            <asp:Button CssClass="btn btn-primary" ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
            <asp:Button CssClass="btn btn-primary" ID="btnPrev" runat="server" Text="Prev" OnClick="btnPrev_Click" /> 
        <asp:TextBox ID="txtPage" runat="server"></asp:TextBox> 
        <asp:Button CssClass="btn btn-primary" ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
            <span class="text-center">
                <input class="btn btn-primary" type="button" value="+" id="zoom-in" /> 
        <input class="btn btn-primary" type="button" value="-" id="zoom-out" />
            </span>
        </div>
        <div id="page-window">
            <asp:Literal ID="htmlLiteral" runat="server" />
        </div>

    </form>

</body>
</html>

    
    
        
            Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports SautinSoft

Partial Public Class _Default
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        uplPDF.Attributes("onchange") = "UploadFile(this)"

        If Not Me.IsPostBack Then
            Session("page") = 1
        End If
    End Sub

    Protected Sub btnNext_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim page As Integer = CInt(Fix(Session("page")))
        page += 1
        If IsPageInRange(page) Then
            Session("page") = page
            ShowPdf()
        End If
    End Sub

    Protected Sub btnPrev_Click(ByVal sender As Object, ByVal e As EventArgs)
        Dim page As Integer = CInt(Fix(Session("page")))
        page -= 1
        If IsPageInRange(page) Then
            Session("page") = page
            ShowPdf()
        End If
    End Sub

    Protected Sub Upload(ByVal sender As Object, ByVal e As EventArgs)
        lblMessage.Visible = True
        Dim f As New PdfFocus()
        f.OpenPdf(uplPDF.FileBytes)
        Session("focus") = f
        ShowPdf()

    End Sub
    Protected Function IsPageInRange(ByVal page As Integer) As Boolean
        If Session("focus") IsNot Nothing Then
            Dim f As PdfFocus = CType(Session("focus"), PdfFocus)

            If page > 0 AndAlso page <= f.PageCount Then
                Return True
            End If
        End If
        Return False
    End Function

    Private Sub ShowPdf()
        If Session("focus") IsNot Nothing Then
            Dim f As PdfFocus = CType(Session("focus"), PdfFocus)

            If f.PageCount > 0 Then
                f.HtmlOptions.IncludeImageInHtml = True
                f.EmbeddedImagesFormat = PdfFocus.eImageFormat.Png

                Dim page As Integer = CInt(Fix(Session("page")))
                Dim html As String = f.ToHtml(page, page)
                htmlLiteral.Text = html
                txtPage.Text = String.Format("Page {0} of {1}", page, f.PageCount)
            End If
        End If
    End Sub
End Class

Скачать

<%@ Page Language="VB" AutoEventWireup="true"  CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function () {

            var zoom = 1.0;
            var zoomStep = 0.05;
            var margin = 0;
            var marginStep = 30;

            $('#zoom-in').click(function () {
                margin += marginStep;
                $('#page-window').css({ transform: 'scale(' + (zoom += zoomStep) + ')' });
                var w = $('#page-window').css("width");

                $('#page-window').css({ "margin-left": (margin) });
                $('#page-window').css({ "margin-top": (margin) });
            })
            $('#zoom-out').click(function () {

                margin -= marginStep;

                $('#page-window').css({ transform: 'scale(' + (zoom -= zoomStep) + ')' });
                $('#page-window').css({ "margin-left": margin });
                $('#page-window').css({ "margin-top": margin });


            })
        });
    </script>

    <script type="text/javascript">
        function UploadFile(fileUpload) {
            if (fileUpload.value != '') {
                document.getElementById("<%=btnUpload.ClientID %>").click();
            }
        }
    </script>

</head>
<body>
    <form class="panel-body" id="form1" runat="server">
        <div class="panel">
            <asp:FileUpload ID="uplPDF" runat="server" ToolTip="Please select a PDF document." /><br />
            <asp:Label ID="lblMessage" runat="server" Text="File uploaded successfully." ForeColor="Green"
                Visible="false" />
            <asp:Button CssClass="btn btn-primary" ID="btnUpload" Text="Upload" runat="server" OnClick="Upload" Style="display: none" />
            <asp:Button CssClass="btn btn-primary" ID="btnPrev" runat="server" Text="Prev" OnClick="btnPrev_Click" /> 
        <asp:TextBox ID="txtPage" runat="server"></asp:TextBox> 
        <asp:Button CssClass="btn btn-primary" ID="btnNext" runat="server" Text="Next" OnClick="btnNext_Click" />
            <span class="text-center">
                <input class="btn btn-primary" type="button" value="+" id="zoom-in" /> 
        <input class="btn btn-primary" type="button" value="-" id="zoom-out" />
            </span>
        </div>
        <div id="page-window">
            <asp:Literal ID="htmlLiteral" runat="server" />
        </div>

    </form>

</body>
</html>

    
    

Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.