Wpf 控件导出Png

源码地址:http://download.csdn.net/detail/yeness/9828055

Wpf 前端

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="WPFImages.RoundedCornerGenerator"
    Title="Rounded Corner Bar Generator" Height="350" Width="480" 
    MinHeight="350" MinWidth="480">
    <Window.Resources>
        <LinearGradientBrush x:Key="BlueGradientBackground" EndPoint ="1,0.5" StartPoint="0,0.5">
            <GradientStop Color="#FFB2C0CD" Offset="0.019"/>
            <GradientStop Color="#FF31487A" Offset="1"/>
            <GradientStop Color="#FF51658E" Offset="0.663"/>
        </LinearGradientBrush>
    </Window.Resources>
    <DockPanel>
        <StackPanel RenderTransformOrigin="0.223,0.248" 
                    x:Name="grdControlContainer" DockPanel.Dock="Top" 
                    Background="{StaticResource BlueGradientBackground}">

            <WrapPanel Margin="10,5,0,0">
                <Label x:Name="lblWidth" Content="Width:" />
                <TextBox HorizontalAlignment="Left"  x:Name="txtWidth"  Width="40" Height="23" Text="200" TextWrapping="Wrap" TextAlignment="Right" TextChanged="UpdateImage"/>
                <Label HorizontalAlignment="Left" VerticalAlignment="Top" Content="    Height:"/>
                <TextBox HorizontalAlignment="Left"  x:Name="txtHeight"  Width="40" Height="23" Text="25" TextWrapping="Wrap" TextAlignment="Right" TextChanged="UpdateImage"/>
                <Label x:Name="lblRadius" Content="   Radius:" />
                <TextBox HorizontalAlignment="Left"  x:Name="txtRadius"  Width="40" Height="23" Text="15" TextWrapping="Wrap" TextAlignment="Right" TextChanged="UpdateImage"/>
                <Label x:Name="lblColor" Content="   Color:" />                
                <TextBox HorizontalAlignment="Left"  x:Name="txtColor"  Width="80" Height="23" Text="Navy" TextWrapping="Wrap" TextChanged="UpdateImage" />                
                <Button Name="btnColorLookup" Content="..." Height="22" Width="22" VerticalAlignment="Bottom" Margin="0,0,0,1" Click="btnColorLookup_Click"/>
            </WrapPanel>
            <WrapPanel Margin="10,10,0,10">
                <Label Content="Corners:" Margin="0,0,5,0"/>
                <RadioButton Name="radTop" Content="Top" IsChecked="True"  Checked="UpdateImage" VerticalAlignment="Center" />
                <RadioButton Name="radBottom" Content="Bottom" Margin="15,0" Checked="UpdateImage" VerticalAlignment="Center" />
                <RadioButton Name="radBoth" Margin="10,0" Content="Both" Checked="UpdateImage" VerticalAlignment="Center" />
            </WrapPanel>
        </StackPanel>
        <StackPanel DockPanel.Dock="Bottom" Background="{StaticResource BlueGradientBackground}" >
            <WrapPanel Margin="10,3,10,3">
                <Label Name="lblFilename" Content="Save to file:" />
                <TextBox Name="txtFilename" Height="23" Width="250" Text="c:\temp\test.png"/>
                <Button Name="btnFileLookup" Content=" ... " Height="22" Width="22" VerticalAlignment="Bottom" Margin="0,0,0,1" Click="btnFileLookup_Click"/>
                <Button x:Name="btnSave" Height="23" Width="75" Margin="20,0,0,0" Content="_Save"  Click="btnSave_Click" />
            </WrapPanel>
        </StackPanel>
        <ScrollViewer Name="graphScrollViewer" Grid.Row="1" Panel.ZIndex="0" ScrollViewer.VerticalScrollBarVisibility="Auto" BorderBrush="{x:Null}" BorderThickness="0" Focusable="False">

            <Grid Name="renderContainer" Background="Azure" ClipToBounds="True">
                <Canvas Name="stOuter">
                    <Canvas Name="cvWrapper" Background="Transparent" ClipToBounds="True">
                        <Rectangle Name="rectMainShape">
                        </Rectangle>
                    </Canvas>
                </Canvas>
            </Grid>
        </ScrollViewer>

    </DockPanel>
</Window>

c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using Microsoft.Win32;

namespace WPFImages
{
    /// <summary>
    /// Interaction logic for RoundedCornerGenerator.xaml
    /// </summary>
    public partial class RoundedCornerGenerator : Window
    {
        public RoundedCornerGenerator()
        {
            InitializeComponent();
            this.txtHeight.Text = this.txtHeight.Text + " ";            
        }

        private void btnRender_Click(object sender, RoutedEventArgs e)
        {
            this.DisplayImage();
        }


        protected void UpdateImage(object sender, RoutedEventArgs e)
        {
            this.DisplayImage();
        }

        public void DisplayImage()
        {
            try
            {
                float Height = float.Parse(this.txtHeight.Text);
                float OriginalHeight = Height;
                float Width = float.Parse(this.txtWidth.Text);
                float Radius = float.Parse(this.txtRadius.Text);

                this.cvWrapper.Width = Width;
                this.cvWrapper.Height = Height;
                this.stOuter.Width = Width;
                this.stOuter.Height = Height;

                this.rectMainShape.RenderTransform = null;

                this.rectMainShape.ClipToBounds = false;
                if (this.radTop.IsChecked.Value || this.radBottom.IsChecked.Value)
                {
                    Height += Radius;
                    this.rectMainShape.ClipToBounds = true;
                }


                this.rectMainShape.Width = Width;
                this.rectMainShape.Height = Height;

                this.rectMainShape.RadiusX = Radius;
                this.rectMainShape.RadiusY = Radius;

                this.rectMainShape.Fill = new BrushConverter().ConvertFrom(this.txtColor.Text) as Brush;

                // *** for bottom shape we'll use TranslateTransform
                if (this.radBottom.IsChecked.Value)
                    this.rectMainShape.RenderTransform = new TranslateTransform(0, Radius * -1);
                        //new RotateTransform(180, Width / 2, OriginalHeight / 2);
            }
            catch
            {}
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            int Height = (int)this.cvWrapper.ActualHeight;
            int Width = (int)this.cvWrapper.ActualWidth;

            RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(this.cvWrapper);

            string file = this.txtFilename.Text;

            string Extension = System.IO.Path.GetExtension(file).ToLower();

            BitmapEncoder encoder;            
            if (Extension == ".gif") 
                encoder = new GifBitmapEncoder();            
            else if (Extension == ".png")
                encoder = new PngBitmapEncoder();            
            else if (Extension == ".jpg")
                encoder = new JpegBitmapEncoder();            
            else
                return;

            encoder.Frames.Add(BitmapFrame.Create(bmp));

            using (Stream stm = File.Create(file))
            {
                encoder.Save(stm);
            }
        }

        private void btnFileLookup_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sd = new SaveFileDialog();
            sd.CheckPathExists = true;
            sd.Filter = "Image files (*.png;*.gif;*.jpg)|*.png;*.gif;*.jpg|All files (*.*)|*.*";
            if (!sd.ShowDialog().Value)
                return;

            this.txtFilename.Text = sd.FileName;
        }

        private void btnColorLookup_Click(object sender, RoutedEventArgs e)
        {
            // *** Ack - no WPF Color picker - use the WinForms one. 
            System.Windows.Forms.ColorDialog cd = new System.Windows.Forms.ColorDialog();
            if (cd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            this.txtColor.Text = System.Drawing.ColorTranslator.ToHtml(cd.Color);

        }
    }
}

补充导出PDF

 /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnExprot_Click(object sender, RoutedEventArgs e)
        {
            // 1.获取路径和文件名称
            string file = "";
            string Extension="";
            string path = "";
            Microsoft.Win32.SaveFileDialog sd = new Microsoft.Win32.SaveFileDialog();
            sd.CheckPathExists = true;
            sd.Filter = "Image files (*.png)|*.png|Pdf File (*.pdf)|*.pdf";
            if (!sd.ShowDialog().Value)
                return;

            file = sd.FileName;                                         // 文件名称
            Extension = System.IO.Path.GetExtension(file).ToLower();    // 扩展名
            path = System.IO.Path.GetFullPath(file);                    // 文件路径

            // 2.1、生成图片
            if (Extension != ".png" && Extension != ".pdf")
                return;

            int Height = (int)this.repeaterStatisticeUserControlList.ActualHeight;
            int Width = (int)this.repeaterStatisticeUserControlList.ActualWidth;
            RenderTargetBitmap bmp = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(this.repeaterStatisticeUserControlList);

            if (Extension == ".png")
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                using (Stream stm = File.Create(file))
                {
                    encoder.Save(stm);
                }
            }
            // 2.2、保存生成pdf
            if (Extension == ".pdf")
            {
                BitmapEncoder encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(bmp));
                using (Stream stm = File.Create(file))
                {
                    encoder.Save(stm);
                }
                // 左右上下
                using (iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0))
                {
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(file);
                    image.ScalePercent(24f);
                    iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(file, FileMode.Create));
                    doc.Open();
                    doc.Add(image); 
                }                
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值