ASP按钮不张贴后从ashx导出pdf使用response.write

本文关键字:pdf 导出 使用 response write ashx 按钮 张贴 ASP | 更新日期: 2023-09-27 18:19:24

我从数据库导出一个json字符串的pdf。我的导出按钮是在gridview控件-图像按钮。我使用处理程序(ashx)文件导出。

问题是,导出页面上的按钮(一个按钮和一个命令字段)后没有发布回来。我的处理程序代码和aspx代码在

下面

处理程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Web.UI;
using System.Data;
using GE.MSA.DataQuality.DataAccess;
using GE.MSA.DataQuality.DataAccess.Authentication;
using GE.MSA.DataQuality.DataAccess.EntityModel;
using Newtonsoft.Json;
namespace GE.MSA.DataQuality.Web
{
    /// <summary>
    /// Summary description for CreatePDF
    /// </summary>
    public class CreatePDF : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            int _id = Convert.ToInt32(context.Request.QueryString["Id"]);
            string _report = context.Request.QueryString["Report"];
            string _lockedfrom = context.Request.QueryString["LockedFrom"];
            string _lockedto = context.Request.QueryString["LockedTo"];
            string _docheader = (_report == "CostServiceReport" ? "Cost & Service Report - " : "Service Report - ") + "Locked from : " + _lockedfrom + " to " + _lockedto;
            string _doctitle = _report + "-" + _lockedfrom + "-" + _lockedto + ".pdf";
            DataTable _PDFReport = new DataTable();
            if (_report == "CostServiceReport")
            {
                using (var db = new dbReferenceTablesEntities())
                {
                    string csr = (from i in db.CS_Billing_LockPeriod
                                  where i.ID == _id
                                  select i.CostServiceReport).FirstOrDefault().ToString();
                    _PDFReport = (DataTable)JsonConvert.DeserializeObject(csr, _PDFReport.GetType());
                }
            }
            else
            {
                if (_report == "ServiceReport")
                {
                    using (var db = new dbReferenceTablesEntities())
                    {
                        string sr = (from i in db.CS_Billing_LockPeriod
                                     where i.ID == _id
                                     select i.ServiceReport).FirstOrDefault().ToString();
                        _PDFReport = (DataTable)JsonConvert.DeserializeObject(sr, _PDFReport.GetType());
                    }
                }
            }
            Document pdfDoc = new Document(PageSize.A3, 20, 20, 20, 20);
            pdfDoc.SetPageSize(iTextSharp.text.PageSize.A3.Rotate());
            try
            {
                PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);
                pdfDoc.Open();
                Chunk c = new Chunk("" + _docheader + "", FontFactory.GetFont("Verdana", 15));
                Paragraph p = new Paragraph();
                p.Alignment = Element.ALIGN_CENTER;
                p.Add(c);
                pdfDoc.Add(p);
                string clientLogo = context.Server.MapPath(".") + "/images/abc.png";
                string imageFilePath = context.Server.MapPath(".") + "/images/abc.png";
                iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
                //Resize image depend upon your need   
                jpg.ScaleToFit(60f, 40f);
                //Give space before image   
                jpg.SpacingBefore = 0f;
                //Give some space after the image   
                jpg.SpacingAfter = 1f;
                jpg.Alignment = Element.HEADER;
                pdfDoc.Add(jpg);
                Font font8 = FontFactory.GetFont("ARIAL", 7);
                DataTable dt = _PDFReport;
                if (dt != null & dt.Rows.Count > 0)
                {
                    //Craete instance of the pdf table and set the number of column in that table  
                    PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
                    PdfTable.HeaderRows = 1;
                    PdfPCell PdfPCell = null;
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[i].ColumnName.ToString(), FontFactory.GetFont("Verdana", 12))));
                        PdfPCell.HorizontalAlignment = Element.ALIGN_CENTER;
                        PdfPCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                        PdfPCell.BackgroundColor = new Color(109, 159, 213);
                        PdfTable.AddCell(PdfPCell);
                    }
                    for (int rows = 0; rows < dt.Rows.Count; rows++)
                    {
                        for (int column = 0; column < dt.Columns.Count; column++)
                        {
                            PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                            PdfTable.AddCell(PdfPCell);
                        }
                    }
                    //PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table            
                    pdfDoc.Add(PdfTable); // add pdf table to the document   
                }
                pdfDoc.Close();
                context.Response.ContentType = "application/pdf";
                context.Response.AddHeader("content-disposition", "attachment; filename= " + _doctitle);
                System.Web.HttpContext.Current.Response.Write(pdfDoc);
                context.Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (DocumentException de)
            {
                System.Web.HttpContext.Current.Response.Write(de.Message);
            }
            catch (IOException ioEx)
            {
                System.Web.HttpContext.Current.Response.Write(ioEx.Message);
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write(ex.Message);
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

ASPX页

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="LockForcing.aspx.cs" Inherits="GE.MSA.DataQuality.Web.LockForcing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <asp:ScriptManager ID="scriptManager1" runat="server"></asp:ScriptManager>
    <asp:UpdatePanel ID="up1" runat="server">
        <ContentTemplate>
            <h2>Lock Force Calculation</h2>
            <div>
                <fieldset>
                    <legend>Set Lock Period</legend>
                    <table>
                        <tr>
                            <td>
                                <label>Start Month</label></td>
                            <td>
                                <asp:DropDownList ID="ddlStartMonth" runat="server" Width="100%">
                                    <asp:ListItem>01</asp:ListItem>
                                    <asp:ListItem>02</asp:ListItem>
                                    <asp:ListItem>03</asp:ListItem>
                                    <asp:ListItem>04</asp:ListItem>
                                    <asp:ListItem>05</asp:ListItem>
                                    <asp:ListItem>06</asp:ListItem>
                                    <asp:ListItem>07</asp:ListItem>
                                    <asp:ListItem>08</asp:ListItem>
                                    <asp:ListItem>09</asp:ListItem>
                                    <asp:ListItem>10</asp:ListItem>
                                    <asp:ListItem>11</asp:ListItem>
                                    <asp:ListItem>12</asp:ListItem>
                                </asp:DropDownList></li></td>
                            <td></td>
                            <td>
                                <label>Start Year</label></td>
                            <td>
                                <asp:DropDownList ID="ddlStartYear" runat="server" Width="100%">
                                </asp:DropDownList></td>
                        </tr>
                        <tr>
                            <td>
                                <label>End Month</label></td>
                            <td>
                                <asp:DropDownList ID="ddlEndMonth" runat="server" Width="100%">
                                    <asp:ListItem>01</asp:ListItem>
                                    <asp:ListItem>02</asp:ListItem>
                                    <asp:ListItem>03</asp:ListItem>
                                    <asp:ListItem>04</asp:ListItem>
                                    <asp:ListItem>05</asp:ListItem>
                                    <asp:ListItem>06</asp:ListItem>
                                    <asp:ListItem>07</asp:ListItem>
                                    <asp:ListItem>08</asp:ListItem>
                                    <asp:ListItem>09</asp:ListItem>
                                    <asp:ListItem>10</asp:ListItem>
                                    <asp:ListItem>11</asp:ListItem>
                                    <asp:ListItem>12</asp:ListItem>
                                </asp:DropDownList></td>
                            <td></td>
                            <td>
                                <label>End Year</label></td>
                            <td>
                                <asp:DropDownList ID="ddlEndYear" runat="server" Width="100%">
                                </asp:DropDownList></td>
                            <td>
                                <asp:Button ID="btnLock" runat="server" Width="120px" Text="Lock" CssClass="submitButton"
                                    BorderStyle="None" OnClick="btnLock_Click" />
                            </td>
                            <td>
                                <asp:Label runat="server" ID="lblLockMessage"></asp:Label>
                                <asp:Timer ID="Timer1" runat="server" Interval="5000" Enabled="false" OnTick="Timer1_Tick"></asp:Timer>
                            </td>
                        </tr>
                    </table>
                </fieldset>
            </div>
            <div>
                <table width="100%">
                    <tr>
                        <td>
                            <label>Lock Period Details</label>
                        </td>
                        <td align="right">
                            <asp:Label runat="server" ID="lblmsg"></asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2">
                            <asp:GridView ID="gvLockPeriod" runat="server" AutoGenerateColumns="false" CssClass="mGrid" OnRowDeleting="gvLockPeriod_RowDeleting"
                                DataKeyNames="Id">
                                <Columns>
                                    <asp:CommandField ShowDeleteButton="true" ControlStyle-ForeColor="darkcyan" DeleteText="Unlock"></asp:CommandField>
                                    <asp:BoundField DataField="FromDate" HeaderText="FromDate" />
                                    <asp:BoundField DataField="ToDate" HeaderText="ToDate" />
                                    <asp:TemplateField HeaderText="Cost&ServiceReport">
                                        <ItemTemplate>
                                            <asp:ImageButton ImageUrl="~/images/Pdf-16.png" runat="server" ToolTip="Download Cost & Service Report"
                                                Visible='<%# Convert.ToBoolean(Eval("CostServiceReport")) %>'
                                                PostBackUrl='<%#"CreatePDF.ashx?id="+Eval("Id")+"&Report=CostServiceReport"+"&LockedFrom="+Eval("fromdate")+"&LockedTo="+Eval("todate")+""%>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="ServiceReport">
                                        <ItemTemplate>
                                            <asp:ImageButton ImageUrl="~/images/Pdf-16.png" runat="server" ToolTip="Download Service Report"
                                                Visible='<%# Convert.ToBoolean(Eval("ServiceReport")) %>'
                                                PostBackUrl='<%#"CreatePDF.ashx?id="+Eval("Id")+"&Report=ServiceReport"+"&LockedFrom="+Eval("fromdate")+"&LockedTo="+Eval("todate")+""%>' />
                                        </ItemTemplate>
                                    </asp:TemplateField>
                                    <asp:BoundField DataField="ModifiedBy" HeaderText="CreatedUser" />
                                    <asp:BoundField DataField="ModifiedDate" HeaderText="CreatedDate" />
                                </Columns>
                            </asp:GridView>
                        </td>
                    </tr>
                </table>
            </div>
        </ContentTemplate>
    </asp:UpdatePanel>
     <asp:UpdateProgress ID="UpdateProgress1" runat="server">
        <ProgressTemplate>
            <div class="overlays" />
            <div style="font-weight: bold; align-content: center" class="overlayContents">
                <asp:Image ID="aspImg1" runat="server" ImageUrl="~/images/ajax-loader.GIF" />
            </div>
        </ProgressTemplate>
    </asp:UpdateProgress>
</asp:Content>

ASP按钮不张贴后从ashx导出pdf使用response.write

刷新响应后,调用响应结束方法。

context.Response.Flush();
System.Web.HttpContext.Current.Response.End();