RDLC报表

图片显示:1,直接在报表中拖一个picturebox控件,选择图片,最简单的

                 2,根据路径选择显示图片

RDLC报表添加图片

1. 添加固定图片(嵌入式图片) 选择一个RDLC报表文件,选择菜单栏中的报表-->嵌入图像-->新建图像(从本地选择一个图片)-->确定选中从工具栏拖动一个Image控件(图像)到RDLC,设置Source属性为Embedded,Value属性为刚才添加的图 片名称即可

2. 动态加载图片(根据图片路径) 2.1 菜单-->报表-->报表参数(新增一个参数,比如名称为image1,类型为string)

2.2 拖动一个image控件到rdlc报表中,设置Source属性为External,Value属性为 =Parameters!image1.Value (注意:这里的image1要和报表参数的名称一致)

2.3 包含报表文件的asp.net窗体

this.ReportViewer1.LocalReport.ReportPath = "..\\ClothesManagement\\Report\\reportFzzst.rdlc"; this.ReportViewer1.LocalReport.EnableExternalImages = true;

ReportParameter[] image = new ReportParameter[1];

string path = "file:///" + Server.MapPath("~") + "Images\\image.gif";

//图片地址 image[0] = new ReportParameter("image1", path); //image1必须和报表参数一致 this.ReportViewer1.LocalReport.SetParameters(image);

this.ReportViewer1.LocalReport.Refresh();

3. 图片属性

3.1 AutoSize 自动根据图片显示大小 3.2 Fit 根据图片控件的大小显示

实例:

                   在RDLC报表里面添加一个参数,添加一个picturebox设置图像原为外部,使用此图像为所添加的参数

                    reportViewer1.LocalReport.EnableExternalImages = true;
                    ReportParameter[] image = new ReportParameter[1];

                    string path = "file:///" + System.IO.Path.Combine(Application.StartupPath, "红色.png");    //前面一定要加fille:///
                    image[0] = new ReportParameter("Image", path);
                    reportViewer1.LocalReport.SetParameters(image);

                          3,把图片转化为二进制进行显示,查看http://blog.csdn.net/long54831/article/details/4302573   rdlc报表显示图片链接

 

                    报表里图片的获取的形式如上图

图片转化为二进制的方法:

 public   byte[] GetImage(Image image)
        {
            byte[] imgBytes;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);
                image.GetThumbnailImage(1000, 708, new Image.GetThumbnailImageAbort(IsTrue), IntPtr.Zero);
                imgBytes = new Byte[ms.Length];
                imgBytes = ms.ToArray();
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }

}

 PDF文件:

             string deviceInfo =
                   @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>8.30in</PageWidth>
                <PageHeight>11.6in</PageHeight>
                <MarginTop>0.5in</MarginTop>
                <MarginLeft>0.24in</MarginLeft>
                <MarginRight>0.24in</MarginRight>
                <MarginBottom>0.5in</MarginBottom>
                </DeviceInfo>";

 把PageWidth和PageHeight和Rdlc报表的宽度设置相同,避免变为两页

后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Data;
using System.Reflection;
using Microsoft.Reporting.WinForms;
using System.IO;
using System.Drawing.Printing;
using System.Drawing.Imaging;
using System.Drawing;

using DeviceModels;
using System.Windows.Forms;

namespace TSCDeviceSelector.Models
{
    public class PrintReport : IDisposable
    {
        private CraneInfo _CraneInfo = null;

        // 打印机名称
        private string PrinterName = "Microsoft XPS Document Writer";

        private int m_currentPageIndex;

        private IList<Stream> m_streams;

        private string _ReportPath = "";
        private string MyProjectName = "";
        private string MyProjectNO = "";

        private Image _Picture;
        private Bitmap _Chart;

        public PrintReport(CraneInfo CraneInfo, Image Picture, Bitmap Chart, string ProjectName, string ProjectNO, string ReportPath)
        {
            this._CraneInfo = CraneInfo;
            this._Picture = Picture;
            this._Chart = Chart;
            this.MyProjectName = ProjectName;
            this.MyProjectNO = ProjectNO;
            this._ReportPath = ReportPath;
        }

        public string Run()
        {
            LocalReport report = new LocalReport();

            try
            {
                report.ReportPath = Path.Combine(Application.StartupPath, "Reports\\TSCDeviceReport.rdlc");
                report.DataSources.Add(new ReportDataSource("loadtable2", GetLoadTable2(_CraneInfo)));
                report.DataSources.Add(new ReportDataSource("loadtable", GetLoadTable(_CraneInfo)));
                report.DataSources.Add(new ReportDataSource("DSPictureDatas", GetDevicePictureDatas(_CraneInfo)));
                report.DataSources.Add(new ReportDataSource("image", GetImage(_Picture)));
                report.DataSources.Add(new ReportDataSource("lineimage", GetLineImage(_Chart)));
                report.DataSources.Add(new ReportDataSource("DSTheParameters", GetParameters()));

                Export(report);

                if (!File.Exists(_ReportPath))
                    throw new Exception();
            }
            catch (Exception ex) { throw new Exception(); }

            return null;
        }

        // BaseTable
        private DataTable GetBaseTable(CraneInfo CraneInfo)
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("CraneTitle", typeof(string));
            dt.Columns.Add("CraneDetail", typeof(string));
            dt.Columns.Add("WorkPlatform", typeof(string));
            dt.Columns.Add("WaveHeight", typeof(string));
            dt.Columns.Add("CraneGenre", typeof(string));
            dt.Columns.Add("BoomLength", typeof(int));
            dt.Columns.Add("Weight", typeof(string));
            dt.Columns.Add("BoomSectionSize", typeof(string));
            dt.Columns.Add("TotalHeight", typeof(string));
            dt.Columns.Add("TurningRadius", typeof(string));

            dt.Rows.Add(CraneInfo);

            return dt;
        }
        private DataTable GetParameters()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ProjectName", typeof(string));
            dt.Columns.Add("ProjectNO", typeof(string));
            dt.Columns.Add("CraneTitle", typeof(string));
            dt.Columns.Add("BoomLength", typeof(string));
            dt.Columns.Add("WorkPlatform", typeof(string));
            dt.Columns.Add("HEEL", typeof(string));
            dt.Columns.Add("TRIM", typeof(string));
            dt.Columns.Add("WaveHeight", typeof(string));
            dt.Columns.Add("SupplyBoatDeckVelocity", typeof(string));
            dt.Columns.Add("BoomTipVerticalVelocity", typeof(string));
            dt.Columns.Add("HorizontalCraneAcceleration", typeof(string));
            dt.Columns.Add("OnboardMinimumDynamicCoefficient", typeof(string));
            dt.Columns.Add("OffboardMinimumDynamicCoefficient", typeof(string));
            dt.Columns.Add("BoomAngleMax", typeof(string));
            dt.Columns.Add("HookSpeedVh", typeof(string));
            dt.Rows.Add(this.MyProjectName, this.MyProjectNO, this._CraneInfo.CraneTitle, this._CraneInfo.BoomLength, this._CraneInfo.ReportParameters.WorkPlatform.ToUpper(), this._CraneInfo.ReportParameters.HEEL, this._CraneInfo.ReportParameters.TRIM, this._CraneInfo.WaveHeight, this._CraneInfo.ReportParameters.SupplyBoatDeckVelocity, this._CraneInfo.ReportParameters.BoomTipVerticalVelocity, this._CraneInfo.ReportParameters.HorizontalCraneAcceleration, this._CraneInfo.ReportParameters.OnboardMinimumDynamicCoefficient, this._CraneInfo.ReportParameters.OffboardMinimumDynamicCoefficient, this._CraneInfo.ReportParameters.BoomAngleMax.ToString("#0.0"), this._CraneInfo.ReportParameters.HookSpeedVh);
            return dt;
        }

        // LoadTable
        private DataTable GetLoadTable(CraneInfo CraneInfo)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("RadiusFt", typeof(string));
            dt.Columns.Add("RadiusM", typeof(string));
            dt.Columns.Add("BoomAngle", typeof(string));
            dt.Columns.Add("OnboardCapacityLbs", typeof(string));
            dt.Columns.Add("OnboardCapacityTonne", typeof(string));
            dt.Columns.Add("OffboardCapacityLbs", typeof(string));
            dt.Columns.Add("OffboardCapacityTonne", typeof(string));

            if (CraneInfo.LoadTable.Count() > 30)
            {
                foreach (var item in CraneInfo.LoadTable.OrderBy(l => l.RadiusFt).Take(30))
                {
                    dt.Rows.Add(
                        Math.Round(item.RadiusFt, 1),
                        item.RadiusM.ToString("#0.0"),
                        item.BoomAngle.ToString("#0.0"),
                        Math.Round(item.OnBoardCapacityLbs, 1),
                        item.OnBoardCapacityTonne.ToString("#0.0"),
                        Math.Round(item.OffBoardCapacityLbs, 1),
                        item.OffBoardCapacityTonne.ToString("#0.0")
                        );
                }
                return dt;
            }
            else
            {
                foreach (var item in CraneInfo.LoadTable.OrderBy(l => l.RadiusFt))
                {
                    dt.Rows.Add(
                        Math.Round(item.RadiusFt, 1),
                        item.RadiusM.ToString("#0.0"),
                        item.BoomAngle.ToString("#0.0"),
                        Math.Round(item.OnBoardCapacityLbs, 1),
                        item.OnBoardCapacityTonne.ToString("#0.0"),
                        Math.Round(item.OffBoardCapacityLbs, 1),
                        item.OffBoardCapacityTonne.ToString("#0.0")
                        );
                }
                return dt;
            }
        }

        private DataTable GetLoadTable2(CraneInfo CraneInfo)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("OnBoardCapacityLbs", typeof(string));
            dt.Columns.Add("OnBoardCapacityTonne", typeof(string));
            dt.Columns.Add("OffBoardCapacityLbs", typeof(string));
            dt.Columns.Add("OffBoardCapacityTonne", typeof(string));
            dt.Columns.Add("PersonnelLbs", typeof(string));
            dt.Columns.Add("PersonnelTonne", typeof(string));
            dt.Columns.Add("BoomAngle", typeof(string));
            dt.Columns.Add("RadiusFt", typeof(string));
            dt.Columns.Add("RadiusM", typeof(string));
            if (CraneInfo.LoadTable2.Count() < 30)
            {
                foreach (var i in CraneInfo.LoadTable2.OrderBy(l => l.RadiusFt))
                {
                    if (i.OnBoardCapacityLbs == 0)
                    {
                        dt.Rows.Add("", "", "", "", "", "", "", "", "");
                    }
                    else
                    {
                        dt.Rows.Add(
                            Math.Round(i.OnBoardCapacityLbs, 1),
                            i.OnBoardCapacityTonne.ToString("#0.0"),
                            Math.Round(i.OffBoardCapacityLbs, 1),
                            i.OffBoardCapacityTonne.ToString("#0.0"),
                            Math.Round(i.PersonnelLbs, 1),
                            i.PersonnelTonne.ToString("#0.0"),
                            i.BoomAngle.ToString("#0.0"),
                            Math.Round(i.RadiusFt, 1),
                            i.RadiusM.ToString("#0.0")
                            );
                    }
                }
                return dt;
            }
            else
            {
                foreach (var i in CraneInfo.LoadTable2.OrderBy(l => l.RadiusFt).Take(30))
                {
                    if (i.OnBoardCapacityLbs == 0)
                    {
                        dt.Rows.Add("", "", "", "", "", "", "", "", "");
                    }
                    else
                    {
                        dt.Rows.Add(
                            Math.Round(i.OnBoardCapacityLbs, 1),
                            i.OnBoardCapacityTonne.ToString("#0.0"),
                            Math.Round(i.OffBoardCapacityLbs, 1),
                            i.OffBoardCapacityTonne.ToString("#0.0"),
                            Math.Round(i.PersonnelLbs, 1),
                            i.PersonnelTonne.ToString("#0.0"),
                            i.BoomAngle.ToString("#0.0"),
                            Math.Round(i.RadiusFt, 1),
                            i.RadiusM.ToString("#0.0")
                            );
                    }
                }
                return dt;
            }
        }

        public DataTable GetDevicePictureDatas(CraneInfo CraneInfo)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("BoomLength", typeof(string));
            dt.Columns.Add("TotalHeight", typeof(string));
            dt.Columns.Add("Weight", typeof(string));
            dt.Columns.Add("TurningRadius", typeof(string));
            dt.Columns.Add("BoomSectionSize", typeof(string));
            dt.Columns.Add("MaxMainHoistRadius", typeof(string));
            dt.Columns.Add("MaxAuxHoistRadius", typeof(string));
            dt.Columns.Add("Para1", typeof(string));
            dt.Columns.Add("Para2", typeof(string));
            dt.Columns.Add("Para3", typeof(string));
            dt.Columns.Add("Para4", typeof(string));
            dt.Columns.Add("Para5", typeof(string));
            dt.Rows.Add(CraneInfo.BoomLength, CraneInfo.TotalHeight, CraneInfo.Weight,
                CraneInfo.TurningRadius, CraneInfo.BoomSectionSize,
                CraneInfo.MaxAuxHoistRadius, CraneInfo.MaxMainHoistRadius,CraneInfo.Para1,
                CraneInfo.Para2,CraneInfo.Para3,CraneInfo.Para4,CraneInfo.Para5
                );
            return dt;
        }

        private bool IsTrue()
        {
            return true;
        }

        public DataTable GetImage(Image image)
        {
            DataTable dt = new DataTable();

            byte[] imgBytes;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                image.Save(ms, ImageFormat.Jpeg);
                image.GetThumbnailImage(1000, 708, new Image.GetThumbnailImageAbort(IsTrue), IntPtr.Zero);
                imgBytes = new Byte[ms.Length];
                imgBytes = ms.ToArray();
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }

            dt.Columns.Add("Image", typeof(string));
            dt.Rows.Add(Convert.ToBase64String(imgBytes));
            return dt;
        }

        public DataTable GetLineImage(Bitmap image)
        {
            DataTable dt = new DataTable();

            byte[] imgBytes;
            MemoryStream ms = null;
            try
            {
                ms = new MemoryStream();
                image.Save(ms, ImageFormat.Gif);
                imgBytes = new Byte[ms.Length];
                imgBytes = ms.ToArray();
            }
            catch (ArgumentNullException ex)
            {
                throw ex;
            }
            finally
            {
                ms.Close();
            }

            dt.Columns.Add("Image", typeof(string));
            dt.Rows.Add(Convert.ToBase64String(imgBytes));
            return dt;
        }

        System.Drawing.Printing.PageSettings p;
        private void Print()
        {
            if (m_streams == null || m_streams.Count == 0)
                throw new Exception("Error: no stream to print.");

            PrintDocument printDoc = new PrintDocument();
            printDoc.PrinterSettings.PrinterName = PrinterName;

            if (!printDoc.PrinterSettings.IsValid)
            {
                throw new Exception("Error: cannot find the default printer.");
            }
            else
            {
                printDoc.PrintPage += new PrintPageEventHandler(PrintPage);
                m_currentPageIndex = 0;
                printDoc.Print();
            }
        }

        // Handler for PrintPageEvents
        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(m_streams[m_currentPageIndex]);

            // Adjust rectangular area with printer margins.
            Rectangle adjustedRect = new Rectangle(
                ev.PageBounds.Left - (int)ev.PageSettings.HardMarginX,
                ev.PageBounds.Top - (int)ev.PageSettings.HardMarginY,
                ev.PageBounds.Width,
                ev.PageBounds.Height);

            // Set Margins
            //ev.PageSettings.Margins = new System.Drawing.Printing.Margins() { Left = 30, Right = 0, Top = 0, Bottom = 0 };

            // Set PageSize
            //ev.PageSettings.PaperSize = new System.Drawing.Printing.PaperSize("DYPage", 492, 716);

            // Draw a white background for the report
            ev.Graphics.FillRectangle(Brushes.White, adjustedRect);

            // Draw the report content
            ev.Graphics.DrawImage(pageImage, adjustedRect);

            // Prepare for the next page. Make sure we haven't hit the end.
            m_currentPageIndex++;
            ev.HasMorePages = (m_currentPageIndex < m_streams.Count);

            //p = ev.PageSettings;
        }

        // 貌似有问题?2012.12.08
        // Routine to provide to the report renderer, in order to
        // save an image for each page of the report.
        private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
        {
            Stream stream = new MemoryStream();
            m_streams.Add(stream);

            return stream;
        }

        // Export the given report as an EMF (Enhanced Metafile) file.
        private void Export(LocalReport report)
        {
            string deviceInfo =
            @"<DeviceInfo>
                <OutputFormat>EMF</OutputFormat>
                <PageWidth>8.30in</PageWidth>
                <PageHeight>11.6in</PageHeight>
                <MarginTop>0.5in</MarginTop>
                <MarginLeft>0.24in</MarginLeft>
                <MarginRight>0.24in</MarginRight>
                <MarginBottom>0.5in</MarginBottom>
                </DeviceInfo>";
            Warning[] warnings;
            string mimeType = "";
            string encoding;
            string fileNameExtension;
            string[] str;

            //m_streams = new List<Stream>();
            //report.Render("PDF", deviceInfo, CreateStream, out warnings); 
            //foreach (Stream stream in m_streams)
            //    stream.Position = 0;

            byte[] bytes = report.Render("PDF", deviceInfo, out mimeType, out encoding, out fileNameExtension, out str, out warnings);

            using (System.IO.FileStream fs = new FileStream(_ReportPath, FileMode.Create))
            {
                fs.Write(bytes, 0, bytes.Length);
            }
        }

        public void Dispose()
        {
            if (m_streams != null)
            {
                foreach (Stream stream in m_streams)
                    stream.Close();
                m_streams = null;
            }
        }
    }
}



Winform 用报表控件进行导出报表:

private void btnConfirm_Click(object sender, EventArgs e)
{
string ReportPath = Directory.GetParent(Directory.GetParent(Path.GetDirectoryName(Application.ExecutablePath)).FullName).FullName + "\\Report\\今日任务报表.rdlc";
reportViewer1.LocalReport.DataSources.Clear();//清除控件的数据源


reportViewer1.LocalReport.ReportPath = ReportPath;



DateTime Date = dateTimePicker1.Value.Date;


List<Task> todayTask = adb.GetTaskByTaskType(0).Where(t => t.CreateDate.Year == Date.Year && t.CreateDate.Month == Date.Month && t.CreateDate.Day == Date.Day).ToList();
List<Task> TomorrowTask = adb.GetTaskByTaskType(1).Where(t => t.CreateDate.Year == Date.Year && t.CreateDate.Month == Date.Month && t.CreateDate.Day == Date.Day).ToList();


DataTable today = new DataTable();
today.Columns.Add(new DataColumn("UserName", typeof(string)));
today.Columns.Add(new DataColumn("CreateDate", typeof(string)));
today.Columns.Add(new DataColumn("TaskDetails", typeof(string)));
today.Columns.Add(new DataColumn("SXTime", typeof(string)));
today.Columns.Add(new DataColumn("SYTime", typeof(string)));
today.Columns.Add(new DataColumn("Status", typeof(string)));
today.Columns.Add(new DataColumn("TaskType", typeof(string)));


if (todayTask.Count == 0)
{


today.Rows.Add("张明", " ", "无", "数", " ", "据", " ");
}
else
{
foreach (var item in todayTask)
{
string TaskType = item.TaskType == 0 ? "本日任务" : "明日计划";
today.Rows.Add(item.UserName, item.CreateDate, item.TaskDetails, item.SXTime, item.SYTime, item.Status, TaskType);
}
}


DataTable date = new DataTable();
date.Columns.Add(new DataColumn("Date", typeof(string)));
string D = Date.Year.ToString() + "年" + Date.Month.ToString() + "月" + Date.Day.ToString();
date.Rows.Add(D);


DataTable Tomorrow = new DataTable();
Tomorrow.Columns.Add(new DataColumn("UserName", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("CreateDate", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("TaskDetails", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("SXTime", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("SYTime", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("Status", typeof(string)));
Tomorrow.Columns.Add(new DataColumn("TaskType", typeof(string)));


if (TomorrowTask.Count == 0)
{
Tomorrow.Rows.Add(" ", " ", "无数据", " ", " ", " ");
}
else
{
int i = 1;
foreach (var item in TomorrowTask)
{
string XH = (i++).ToString() + "、";
Tomorrow.Rows.Add(XH, item.CreateDate, item.TaskDetails, item.SXTime, item.SYTime, item.TaskType);
}


}
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Task", today));
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Date", date));
reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Tomorrow", Tomorrow));


this.reportViewer1.RefreshReport();
}
}


 
原文地址:https://www.cnblogs.com/wangchengshen/p/3088992.html