lenlenya
3/23/2018 - 12:49 AM

将RDLC渲染为PDF输出

将RDLC渲染为PDF输出

public abstract class BaseReport : Page
{
    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //将本地报表写入到HTTP输出流
        using (var localReport = GetLocalReport())
        {
            var dispayName = localReport.DisplayName;
            RenderReportToPDFOutput(localReport, dispayName, IsExport);
        }
    }

    /// <summary>
    /// 标记当前请求是呈现报表还是导出报表
    /// </summary>
    protected bool IsExport { get; set; }

    Margins _margin;
    /// <summary>
    /// 指定报表的边距尺寸,以百分之一英寸为单位。默认所有外边距为0in。
    /// </summary>
    protected Margins ReportMargin
    {
        get
        {
            if (_margin == null)
            {
                _margin = new Margins(0, 0, 0, 0);
            }
            return _margin;
        }
        set { _margin = value; }
    }

    /// <summary>
    /// 获取一个附带了数据源的本地报表
    /// </summary>
    /// <returns></returns>
    protected abstract LocalReport GetLocalReport();

    /// <summary>
    /// 将LocalReport渲染为PDF输出
    /// </summary>
    /// <param name="localReport">包含了数据源的本地报表</param>
    /// <param name="displayName">导出文件名称</param>
    /// <param name="isExport">是否为导出</param>
    protected void RenderReportToPDFOutput(LocalReport localReport, string displayName = null, bool isExport = false)
    {
        string mimeType, encoding, extension, deviceInfo;
        string[] streamids;
        Warning[] warnings;
        deviceInfo = string.Format(@"<DeviceInfo>
<SimplePageHeaders>False</SimplePageHeaders>
<MarginTop>{0}in</MarginTop>
<MarginLeft>{1}in</MarginLeft>
<MarginRight>{2}in</MarginRight>
<MarginBottom>{3}in</MarginBottom>
</DeviceInfo>"
        , ReportMargin.Top / 100.0, ReportMargin.Left / 100.0, ReportMargin.Right / 100.0, ReportMargin.Bottom / 100.0);

        if (!string.IsNullOrEmpty(displayName)) localReport.DisplayName = displayName;
        byte[] bytes = localReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamids, out warnings);

        Response.Clear();
        Response.ContentEncoding = Encoding.UTF8;
        Response.ContentType = mimeType;
        //Response.AppendHeader("Content-Length", bytes.Length.ToString());//Render方法已经处理了。
        if (isExport)
        {
            if (string.IsNullOrEmpty(displayName)) displayName = localReport.DisplayName;
            if (string.IsNullOrEmpty(displayName)) displayName = DateTime.Now.ToString("yyyyMMddhhmmss");
            if (!Path.HasExtension(displayName)) displayName += "." + extension;
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(displayName, Encoding.UTF8));
        }
        Response.BinaryWrite(bytes);
        Response.End();
    }
}