[参考] Asp.Net 生成PDF 报表

      在项目开发的过程中,我们往往需要生成一些不能被再修改的报表,下面就是一个实例,实现把报表生成了PDF文件,此仅供参考。

生成报表

 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using System.Web;
 5using System.Web.UI;
 6using System.Web.UI.WebControls;
 7using System.Data;
 8using Microsoft.Reporting.WinForms;
 9
10
11namespace Demo
12{
13    public partial class ReportTest : System.Web.UI.Page
14    {
15        protected void Page_Load(object sender, EventArgs e)
16        {
17
18        }

19
20        protected void Button1_Click(object sender, EventArgs e)
21        {
22            ReportDataSet ds = new ReportDataSet();
23            ReportDataSet.T_BC_REPORTRow row = ds.T_BC_REPORT.NewT_BC_REPORTRow();
24            row.REPORT_FIELD1 = "abc";
25            row.REPORT_FIELD2 = "def";
26            ds.T_BC_REPORT.Rows.Add(row);
27            Dictionary<string, DataTable> Dictionary = new Dictionary<string, DataTable>();
28            Dictionary.Add("ReportDataSet_T_BC_REPORT", ds.T_BC_REPORT);
29
30            ReportServices ReportServices = new ReportServices(Server.MapPath("~/ReportTemplate.rdlc"), Dictionary);
31            byte[] bytes = ReportServices.Render("PDF");
32            DownLoadFile(bytes, "RAS_Daily_Collector_Statement_by_individual_POS_" + DateTime.Now.ToString("yyyyMMdd"+ '_' + DateTime.Now.ToString("HHMMss"+ ".pdf""application/pdf");
33        }

34
35        public void DownLoadFile(byte[] bypes, string fileName, string contentType)
36        {
37            HttpContext.Current.Response.Buffer = true;
38            HttpContext.Current.Response.Clear();
39            HttpContext.Current.Response.ContentType = contentType;
40            HttpContext.Current.Response.AddHeader("Content-Disposition""attachment; filename=" + fileName + ";");
41            HttpContext.Current.Response.BinaryWrite(bypes);
42            HttpContext.Current.Response.End();
43        }

44    }

45}

46

 

定义的类

  1using System;
  2using System.Collections.Generic;
  3using System.Linq;
  4using System.Web;
  5using System.IO;
  6using Microsoft.Reporting.WinForms;
  7using System.Drawing;
  8using System.Drawing.Printing;
  9using System.Collections;
 10using System.Data;
 11
 12namespace Demo
 13{
 14    public class ReportServices
 15    {
 16        private FileStream fs;
 17        private Font printFont;
 18
 19        private LocalReport _localReport;
 20
 21        public LocalReport LocalReport
 22        {
 23            get return _localReport; }
 24        }

 25
 26        private string _templateFileName;
 27
 28        public string TemplateFileName
 29        {
 30            get return _templateFileName; }
 31        }

 32
 33        private ReportServicesParameters _parameters;
 34
 35        public ReportServicesParameters Parameters
 36        {
 37            get return _parameters; }
 38        }

 39
 40        private string _connectionStringName;
 41
 42        public string ConnectionStringName
 43        {
 44            get return _connectionStringName; }
 45        }

 46
 47        private string _exportOutputFileName;
 48
 49        public string ExportOutputFileName
 50        {
 51            get return _exportOutputFileName; }
 52        }

 53
 54        private string _subDataSourceName;
 55
 56        private DataTable _subDataSource;
 57
 58        private string _subDataSourceName1;
 59
 60        private DataTable _subDataSource1;
 61
 62        public ReportServices(string templateFileName, string dataSourceName, DataTable dataSource)
 63        {
 64            if (templateFileName == null || templateFileName.Length == 0)
 65                throw new ArgumentException("The report template file must be specified.""templateFileName");
 66
 67            _localReport = new LocalReport();
 68
 69            _templateFileName = templateFileName;
 70            LocalReport.ReportPath = templateFileName;
 71            ReportDataSource reportDataSource = new ReportDataSource(dataSourceName, dataSource);
 72            LocalReport.DataSources.Add(reportDataSource);
 73            ArrayList parameterNames = new ArrayList();
 74            foreach (ReportParameterInfo parameterField in LocalReport.GetParameters())
 75            {
 76                parameterNames.Add(parameterField.Name);
 77            }

 78            _parameters = new ReportServicesParameters(this, parameterNames);
 79        }

 80
 81        public ReportServices(string templateFileName, Dictionary<string, DataTable> dataSource)
 82        {
 83            if (templateFileName == null || templateFileName.Length == 0)
 84                throw new ArgumentException("The report template file must be specified.""templateFileName");
 85
 86            _localReport = new LocalReport();
 87
 88            _templateFileName = templateFileName;
 89            LocalReport.ReportPath = templateFileName;
 90
 91            foreach (KeyValuePair<string, DataTable> keyValuePair in dataSource)
 92            {
 93                ReportDataSource reportDataSource = new ReportDataSource(keyValuePair.Key, keyValuePair.Value);
 94                LocalReport.DataSources.Add(reportDataSource);
 95            }

 96
 97            ArrayList parameterNames = new ArrayList();
 98            foreach (ReportParameterInfo parameterField in LocalReport.GetParameters())
 99            {
100                parameterNames.Add(parameterField.Name);
101            }

102            _parameters = new ReportServicesParameters(this, parameterNames);
103        }

104
105        //Add by Ni Na on 29/05/2008 to do AP Letter 700 Goods
106        public ReportServices(string templateFileName, Dictionary<string, DataTable> dataSource, string subDataSourceName, DataTable subDataSource)
107        {
108            this._subDataSourceName = subDataSourceName;
109            this._subDataSource = subDataSource;
110
111            if (templateFileName == null || templateFileName.Length == 0)
112                throw new ArgumentException("The report template file must be specified.""templateFileName");
113
114            _localReport = new LocalReport();
115
116            _templateFileName = templateFileName;
117            LocalReport.ReportPath = templateFileName;
118
119            foreach (KeyValuePair<string, DataTable> keyValuePair in dataSource)
120            {
121                ReportDataSource reportDataSource = new ReportDataSource(keyValuePair.Key, keyValuePair.Value);
122                LocalReport.DataSources.Add(reportDataSource);
123            }

124
125            LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(Report_SubreportProcessing);
126
127            ArrayList parameterNames = new ArrayList();
128            foreach (ReportParameterInfo parameterField in LocalReport.GetParameters())
129            {
130                parameterNames.Add(parameterField.Name);
131            }

132            _parameters = new ReportServicesParameters(this, parameterNames);
133        }

134
135        void Report_SubreportProcessing(object sender, SubreportProcessingEventArgs e)
136        {
137            e.DataSources.Add(new ReportDataSource(_subDataSourceName, _subDataSource));
138        }

139        //End Add
140
141        public ReportServices(string templateFileName, string dataSourceName, DataTable dataSource, string subDataSourceName, DataTable subDataSource)
142        {
143            this._subDataSourceName = subDataSourceName;
144            this._subDataSource = subDataSource;
145
146            if (templateFileName == null || templateFileName.Length == 0)
147                throw new ArgumentException("The report template file must be specified.""templateFileName");
148
149            _localReport = new LocalReport();
150
151            _templateFileName = templateFileName;
152            LocalReport.ReportPath = templateFileName;
153            ReportDataSource reportDataSource = new ReportDataSource(dataSourceName, dataSource);
154            LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
155            LocalReport.DataSources.Add(reportDataSource);
156            ArrayList parameterNames = new ArrayList();
157            foreach (ReportParameterInfo parameterField in LocalReport.GetParameters())
158            {
159                parameterNames.Add(parameterField.Name);
160            }

161            _parameters = new ReportServicesParameters(this, parameterNames);
162        }

163
164        public ReportServices(string templateFileName, string dataSourceName, DataTable dataSource, string subDataSourceName, DataTable subDataSource, string subDataSourceName1, DataTable subDataSource1)
165        {
166            this._subDataSourceName = subDataSourceName;
167            this._subDataSource = subDataSource;
168
169            this._subDataSourceName1 = subDataSourceName1;
170            this._subDataSource1 = subDataSource1;
171
172            if (templateFileName == null || templateFileName.Length == 0)
173                throw new ArgumentException("The report template file must be specified.""templateFileName");
174
175            _localReport = new LocalReport();
176
177            _templateFileName = templateFileName;
178            LocalReport.ReportPath = templateFileName;
179            ReportDataSource reportDataSource = new ReportDataSource(dataSourceName, dataSource);
180            LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler);
181            LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SubreportProcessingEventHandler1);
182            LocalReport.DataSources.Add(reportDataSource);
183            ArrayList parameterNames = new ArrayList();
184            foreach (ReportParameterInfo parameterField in LocalReport.GetParameters())
185            {
186                parameterNames.Add(parameterField.Name);
187            }

188            _parameters = new ReportServicesParameters(this, parameterNames);
189        }

190
191
192        void SubreportProcessingEventHandler(object sender, SubreportProcessingEventArgs e)
193        {
194            e.DataSources.Add(new ReportDataSource(_subDataSourceName, _subDataSource));
195        }

196
197        void SubreportProcessingEventHandler1(object sender, SubreportProcessingEventArgs e)
198        {
199            e.DataSources.Add(new ReportDataSource(_subDataSourceName1, _subDataSource1));
200        }

201
202
203
204        public void Print()
205        {
206            try
207            {
208                printFont = new Font("Arial"10);
209                PrintDocument pd = new PrintDocument();
210                pd.PrintPage += this.pd_PrintPage;
211                // Print the document.
212                pd.Print();
213            }

214            catch (Exception)
215            {
216            }

217        }

218
219        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
220        {
221            StreamReader streamToPrint = new StreamReader(fs);
222            float linesPerPage;
223            float yPos = 0;
224            int count = 0;
225            float leftMargin = ev.MarginBounds.Left;
226            float topMargin = ev.MarginBounds.Top;
227            String line = null;
228
229            // Calculate the number of lines per page.
230            linesPerPage = ev.MarginBounds.Height /
231                           printFont.GetHeight(ev.Graphics);
232
233            // Iterate over the file, printing each line.
234            while (count < linesPerPage &&
235                   ((line = streamToPrint.ReadLine()) != null))
236            {
237                yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
238                ev.Graphics.DrawString(line, printFont, Brushes.Black,
239                                       leftMargin, yPos, new StringFormat());
240                count++;
241            }

242
243            // If more lines exist, print another page.
244            if (line != null)
245                ev.HasMorePages = true;
246            else
247                ev.HasMorePages = false;
248        }

249
250
251        public void Export(string exportOutputFileName, string exportFormatType)
252        {
253            Warning[] warnings;
254            string[] streamids;
255            string mimeType;
256            string encoding;
257            string extension;
258
259            byte[] bytes = this.LocalReport.Render(exportFormatType, nullout mimeType, out encoding, out extension,
260                                                   out streamids, out warnings);
261
262            this.fs = new FileStream(exportOutputFileName, FileMode.Create);
263            this.fs.Write(bytes, 0, bytes.Length);
264            this.fs.Close();
265        }

266
267        public byte[] Render(string renderFormat)
268        {
269            Warning[] warnings;
270            string[] streamids;
271            string mimeType;
272            string encoding;
273            string extension;
274
275            return this.LocalReport.Render(renderFormat, nullout mimeType, out encoding, out extension,
276                                                   out streamids, out warnings);
277
278        }

279    }

280}

281
282
283using System;
284using System.Collections.Generic;
285using System.Linq;
286using System.Web;
287using Microsoft.Reporting.WinForms;
288using System.Collections;
289
290namespace Demo
291{
292    public class ReportServicesParameters
293    {
294        private ReportServices _reportServices;
295
296        public ReportServices ReportServices
297        {
298            get return _reportServices; }
299        }

300
301        private ArrayList _parameterNames;
302
303        public ArrayList ParameterNames
304        {
305            get return _parameterNames; }
306        }

307
308        internal ReportServicesParameters(ReportServices ReportServices, ArrayList parameterNames)
309        {
310            _reportServices = ReportServices;
311            _parameterNames = parameterNames;
312        }

313
314        public object this[string parameterName]
315        {
316            get
317            {
318                if (!_parameterNames.Contains(parameterName))
319                    throw new ArgumentException("The parameter name specified does not exist.""value");
320
321                return _reportServices.LocalReport.GetParameters()[parameterName].Values[0];
322            }

323            set
324            {
325                if (!_parameterNames.Contains(parameterName))
326                    throw new ArgumentException("The parameter name specified does not exist.""value");
327
328                List<ReportParameter> paramList = new List<ReportParameter>();
329                ReportParameter reportParameter = new ReportParameter(parameterName, value.ToString());
330                paramList.Add(reportParameter);
331                _reportServices.LocalReport.SetParameters(paramList);
332            }

333        }

334    }

335}

336

 

 

posted @ 2009-06-29 11:20 我-大熊 阅读(878) 评论(3) 编辑 收藏