using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Drawing.Printing;
using ComPDFKit.PDFDocument;
using PDF_Office.Model;
using System.Drawing;
using System.Reflection;
using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePagePrinter;
using System.Threading.Tasks;
using ComPDFKit.PDFPage;
using PDF_Office.Helper;
using System.Drawing.Drawing2D;
using ComPDFKitViewer.PdfViewer;
using System.Windows.Media.Imaging;
using System.Drawing.Imaging;
using PDF_Office.CustomControl;
using Prism.Events;
using ImTools;

namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs.HomePagePrinter
{
    public class HomePagePrinterDialogViewModel : BindableBase, IDialogAware
    {
        #region Base
        public IDialogService Dialogs;
        private readonly IEventAggregator eventAggregator;
        public IRegionManager PrintModRegion;
        private Object locker = new Object();
        private CPDFViewer currentViewer;

        private string _currentPrintModName;
        public string CurrentPrintModName
        {
            get { return _currentPrintModName; }
            set
            {
                if (value == "ModSize")
                {
                    IsEnableForModBooklet = true;
                    IsEnableForModMultiple = true;
                    IsEnableForModSize = false;
                }
                else if (value == "ModMultiple")
                {
                    IsEnableForModBooklet = true;
                    IsEnableForModMultiple = false;
                    IsEnableForModSize = true;
                }
                else if (value == "ModBooklet")
                {
                    IsEnableForModBooklet = false;
                    IsEnableForModMultiple = true;
                    IsEnableForModSize = true;
                }
                _currentPrintModName = value;
            }
        }

        public HomePagePrinterDialogModel homePagePrinterDialogModel;
        public HomePagePrinterPageSetDialogViewModel homePagePrinterPageSetDialogViewModel { get; set; }
        public PrintSettingsInfo printSettingsInfo;
        #endregion

        #region 界面和组件设置
        private string _printModRegionName;
        public string PrintModRegionName
        {
            get
            {
                return _printModRegionName;
            }
            set
            {
                SetProperty(ref _printModRegionName, value);
            }
        }

        private List<string> _printerNameList;
        public List<string> PrinterNameList
        {
            get { return _printerNameList; }
            set { _printerNameList = value; }
        }

        private List<string> _printContentList;
        public List<string> PrintContentList
        {
            get { return _printContentList; }
            set { _printContentList = value; }
        }

        private CPDFDocument document;

        private List<string> _printerOrientationList;
        public List<string> PrintOrientationList
        {
            get { return _printerOrientationList; }
            set
            {
                _printerOrientationList = value;
            }
        }

        private bool _isEnableForGetNextPage = true;
        public bool IsEnableForGetNextPage
        {
            get { return _isEnableForGetNextPage; }
            set
            {
                _isEnableForGetNextPage = value;
                RaisePropertyChanged();
            }
        }

        private bool _isEnableForGetPreviousPage = false;
        public bool IsEnableForGetPreviousPage
        {
            get { return _isEnableForGetPreviousPage; }
            set
            {
                _isEnableForGetPreviousPage = value;
                RaisePropertyChanged();
            }
        }

        private bool _isEnableForModSize = false;
        public bool IsEnableForModSize
        {
            get { return _isEnableForModSize; }
            set
            {
                SetProperty(ref _isEnableForModSize, value);
            }
        }

        private bool _isEnableForModPoster = false;
        public bool IsEnableForModPoster
        {
            get { return _isEnableForModPoster; }
            set { _isEnableForModPoster = value; }
        }

        private bool _isEnableForModMultiple = true;
        public bool IsEnableForModMultiple
        {
            get { return _isEnableForModMultiple; }
            set { SetProperty(ref _isEnableForModMultiple, value); }
        }

        private bool _isEnableForModBooklet = true;
        public bool IsEnableForModBooklet
        {
            get { return _isEnableForModBooklet; }
            set
            {
                SetProperty(ref _isEnableForModBooklet, value);
            }
        }
        #endregion

        #region 属性设置
        private int _paperHeight = 297;
        /// <summary>
        /// 纸张高度，默认A4
        /// </summary>
        public int PaperHeight
        {
            get { return _paperHeight; }
            set { SetProperty(ref _paperHeight, value); }
        }

        private int _paperWidth = 210;
        public int PaperWidth
        {
            get { return _paperWidth; }
            set { SetProperty(ref _paperWidth, value); }
        }

        private int _canvasHeight = 297;
        public int CanvasHeight
        {
            get { return _canvasHeight; }
            set { SetProperty(ref _canvasHeight, value); }
        }

        private int _canvasWidth = 210;
        public int CanvasWidth
        {
            get { return _canvasWidth; }
            set { SetProperty(ref _canvasWidth, value); }
        }

        private int _viewBoxHeight = 296;
        /// <summary>
        /// 显示（高）度，默认A4
        /// </summary>
        public int ViewBoxHeight
        {
            get { return _viewBoxHeight; }
            set
            {
                SetProperty(ref _viewBoxHeight, value);
            }
        }

        private int _viewBoxWidth = 209;
        /// <summary>
        /// 显示宽度，默认A4
        /// </summary>
        public int ViewBoxWidth
        {
            get { return _viewBoxWidth; }
            set
            {
                SetProperty(ref _viewBoxWidth, value);

            }
        }

        private EnumPaperSize _enumPaperSize;
        /// <summary>
        /// 纸张尺寸枚举
        /// </summary>
        public EnumPaperSize EnumPaperSize
        {
            get { return _enumPaperSize; }
            set { _enumPaperSize = value; }
        }

        private int _leftMargin = 0;
        /// <summary>
        /// 纸张左边距
        /// </summary>
        public int LeftMargin
        {
            get { return _leftMargin; }
            set { _leftMargin = value; }
        }

        private int _rightMargin = 0;
        /// <summary>
        /// 纸张右边距
        /// </summary>
        public int RightMargin
        {
            get { return _rightMargin; }
            set { _rightMargin = value; }
        }

        private int _bottomMargin = 0;
        /// <summary>
        /// 纸张下边距
        /// </summary>
        public int BottomMargin
        {
            get { return _bottomMargin; }
            set { _bottomMargin = value; }
        }

        private int _topMargin = 0;
        /// <summary>
        /// 纸张上边距
        /// </summary>
        public int TopMargin
        {
            get { return _topMargin; }
            set { _topMargin = value; }
        }

        private int _rotateAngle = 0;
        public int RotateAngle
        {
            get { return _rotateAngle; }
            set { SetProperty(ref _rotateAngle, value); }
        }

        private int _rotateCenterX = 0;
        public int RotateCenterX
        {
            get { return _rotateCenterX; }
            set { SetProperty(ref _rotateCenterX, value); }
        }

        private int _rotateCenterY = 0;
        public int RotateCenterY
        {
            get { return _rotateCenterY; }
            set { SetProperty(ref _rotateCenterY, value); }
        }

        private Visibility _printModVisible = Visibility.Collapsed;
        /// <summary>
        /// PrintMod region可见
        /// </summary>
        public Visibility PrintModVisible
        {
            get { return _printModVisible; }
            set { SetProperty(ref _printModVisible, value); }
        }

        private BitmapSource _bitmapSource;
        /// <summary>
        /// 渲染后的图
        /// </summary>
        public BitmapSource BitmapSource
        {
            get { return _bitmapSource; }
            set { SetProperty(ref _bitmapSource, value); }
        }

        private int _printerIndex = 0;
        /// <summary>
        /// 打印机索引
        /// </summary>
        public int PrinterIndex
        {
            get { return _printerIndex; }
            set { _printerIndex = value; }
        }

        private string _maxPageNumber;
        /// <summary>
        /// 总页面数
        /// </summary>
        public string MaxPageNumber
        {
            get
            {
                return _maxPageNumber;
            }
            set
            {
                if (TargetPages.Count != 0)
                {
                    _maxPageNumber = value.ToString();
                }
                else
                {
                    _maxPageNumber = "NaN";
                }
                RaisePropertyChanged();
            }
        }

        private string _customPageRange;
        /// <summary>
        /// 页面范围：自定义页面
        /// </summary>
        public string CustomPageRange
        {
            get { return _customPageRange; }
            set { _customPageRange = value; }
        }

        private int _pageRangeIndex = 0;
        /// <summary>
        ///<para>页面范围：下拉框索引</para>  
        ///<para>0：全部页面</para>
        ///<para>1：当前页面</para>
        ///<para>2：奇数页</para>
        ///<para>3：偶数页</para>
        ///<para>4：自定义页面</para>
        /// </summary>
        public int PageRangeIndex
        {
            get { return _pageRangeIndex; }
            set
            {
                _pageRangeIndex = value;
                RaisePropertyChanged();
            }
        }

        private bool _isBlackAndWhite;
        /// <summary>
        /// 是否黑白打印
        /// </summary>
        public bool IsBlackAndWhite
        {
            get { return _isBlackAndWhite; }
            set { _isBlackAndWhite = value; }
        }

        private int _printContentIndex = 1;
        /// <summary>
        /// 打印内容索引
        /// <para>0：文档</para>
        /// <para>1：文档和标记</para>
        /// <para>2：文档和图章</para>
        /// <para>3：文档和表单</para>
        /// </summary>
        public int PrintContentIndex
        {
            get { return _printContentIndex; }
            set { _printContentIndex = value; }
        }

        private bool _isPageIndexReverse;
        /// <summary>
        /// 是否逆序打印(属性)
        /// </summary>
        public bool IsPageIndexReverse
        {
            get { return _isPageIndexReverse; }
            set { _isPageIndexReverse = value; }
        }

        private bool _needPageIndexReverse;
        public bool NeedPageIndexReverse
        {
            get { return _needPageIndexReverse; }
            set { _needPageIndexReverse = value; }
        }

        private int _printOrientationIndex;
        /// <summary>
        ///<para>打印方向索引</para>
        ///<para>0：纵向(默认)</para>
        ///<para>1：横向</para>
        /// </summary>
        public int PrintOrientationIndex
        {
            get { return _printOrientationIndex; }
            set
            {
                if (value != _printOrientationIndex)
                {
                    if(value == 0)
                    {
                        RotatePreviewPaperWhenPortrait();
                    }
                    if (value == 1)
                    {
                        RotatePreviewPaperWhenLandscape();
                    }
                }
                _printOrientationIndex = value;
                if (flagIsAutoOrientation == true)
                {
                    flagIsAutoOrientation = false;
                }
                RaisePropertyChanged(nameof(PrintOrientationIndex));

            }
        }
        #endregion

        #region 打印
        private PrintDocument printDocument = new PrintDocument();
        private PrinterSettings printerSettings = new PrinterSettings();
        private PageSettings pageSettings = new PageSettings();

        private int PrintIndex = 0;
        private int printListIndex = 0;



        private PageSettings PageSettings = new PageSettings();

        /// <summary>
        ///待打印页面集合，存储页面索引值
        /// </summary>
        private List<int> TargetPages = new List<int>();

        /// <summary>
        /// 当前显示的页码索引, 该值被设置到边界时将修改翻页按钮的可用性
        /// </summary>
        private int _currentPreviewIndex;
        public int CurrentPreviewIndex
        {
            get { return _currentPreviewIndex; }
            set
            {
                if (currentListIndex > 0)
                {
                    IsEnableForGetPreviousPage = true;
                }
                else
                {
                    IsEnableForGetPreviousPage = false;
                }

                if (currentListIndex < int.Parse(MaxPageNumber) - 1)
                {
                    IsEnableForGetNextPage = true;
                }
                else
                {
                    IsEnableForGetNextPage = false;
                }
                _currentPreviewIndex = value;
            }
        }

        /// <summary>
        /// 预览显示的页码编号，由TargetPages映射
        /// </summary>
        public int currentListIndex = 0;

        /// <summary>
        /// <para>Current表示当前选中的，Existent表示目前存在的</para>
        /// <para>一次改变后，current成为existent,existent变成previous</para>
        /// </summary>
        private string _existentPrintModName = "ModSize";
        public string ExistentPrintModName
        {
            get { return _existentPrintModName; }
            set { _existentPrintModName = value; }
        }

        /// <summary>
        /// 预览显示的页码编号，由TargetPages映射
        /// </summary>
        private int _currentListIndex = 1;
        public string CurrentListIndexString
        {
            get { return _currentListIndex.ToString(); }
            set
            {
                if (value != "")
                {
                    if (int.Parse(value) >= 0 && int.Parse(value) < int.Parse(MaxPageNumber))
                    {
                        _currentListIndex = int.Parse(value);
                        currentListIndex = _currentListIndex;
                        SetProperty(ref _currentListIndex, int.Parse(value));
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("error num");
                    }
                }
                else
                {
                    System.Windows.MessageBox.Show("error space");
                }
            }
        }

        /// <summary>
        /// 海报模式，水平需要的纸张计数
        /// </summary>
        private int _horizontalPaperCountModPoster;
        public int HorizontalPaperCountModPoster
        {
            get { return _horizontalPaperCountModPoster; }
            set { _horizontalPaperCountModPoster = value; }
        }

        /// <summary>
        /// 海报模式：垂直需要的纸张计数
        /// </summary>
        private int _verticalPaperCountModPoster;
        public int VerticalPaperCountModPoster
        {
            get { return _verticalPaperCountModPoster; }
            set { _verticalPaperCountModPoster = value; }
        }

        private int _printIndexModMultiple = 0;
        /// <summary>
        /// 多页模式下打印原PDF文件页面顺序索引
        /// </summary>
        public int PrintIndexModMultiple
        {
            get { return _printIndexModMultiple; }
            set { _printIndexModMultiple = value; }
        }


        System.Drawing.Point location = new System.Drawing.Point(10, 10);
        System.Drawing.Size size = new System.Drawing.Size(600, 150);
        #endregion

        #region 字典
        public Dictionary<string, string> GetContentByPrintMod;
        public Dictionary<int, string> GetPrinterNameByPrinterIndex;
        #endregion

        #region 杂项和其他标记
        /// <summary>
        /// 标记：自动旋转-仅未修改旋转方向时生效
        /// </summary>
        private bool flagIsAutoOrientation = true;

        /// <summary>
        /// 标记：防止控件相互调用多次渲染
        /// </summary>
        private bool flagForNotRenderTwice = true;

        /// <summary>
        /// 标记：第一次启动窗口，防止其他控件唤起渲染
        /// </summary>
        private bool flagIsFirstView = true;

        /// <summary>
        /// 
        /// </summary>
        private int flagPreviousRenderPageIndex;
        #endregion

        #region 委托
        public DelegateCommand SetPaperSizeCommand { get; set; }
        public DelegateCommand SetIsBlackAndWhiteCommand { get; set; }
        public DelegateCommand SetPrintOrientationCommand { get; set; }
        public DelegateCommand SetPrintContentCommand { get; set; }
        public DelegateCommand SetIsPageIndexReverseCommand { get; set; }
        public DelegateCommand SetPageRangeCommand { get; set; }

        public DelegateCommand<object> ChangePrintModCommand { get; set; }

        public DelegateCommand GetNextPagePreviewCommand { get; set; }
        public DelegateCommand GetPreviousPagePreviewCommand { get; set; }
        public DelegateCommand GetPagePreviewWhenIndexChangedCommand { get; set; }
        public DelegateCommand SubscribeCommand { get; set; }

        public DelegateCommand ConfirmPrintCommand { get; set; }

        #endregion

        public HomePagePrinterDialogViewModel(IDialogService dialogService, IRegionManager regionManager, IEventAggregator eventAggregator)
        {

            Dialogs = dialogService;
            PrintModRegion = regionManager;
            PrintModVisible = Visibility.Visible;
            homePagePrinterDialogModel = new HomePagePrinterDialogModel();
            homePagePrinterPageSetDialogViewModel = new HomePagePrinterPageSetDialogViewModel();
            PrintModRegionName = Guid.NewGuid().ToString();

            SetPaperSizeCommand = new DelegateCommand(SetPaperSize);
            SetIsBlackAndWhiteCommand = new DelegateCommand(SetIsBlackAndWhite);
            SetPrintOrientationCommand = new DelegateCommand(SetPrintOrientation);
            SetPageRangeCommand = new DelegateCommand(SetPageRange);
            SetPrintContentCommand = new DelegateCommand(SetPrintContent);
            SetIsPageIndexReverseCommand = new DelegateCommand(SetIsPageIndexReverse);
            ChangePrintModCommand = new DelegateCommand<object>(ChangePrintMod);

            eventAggregator.GetEvent<ModInfoSendEvent>().Subscribe(SubscribeEvent);

            GetPagePreviewWhenIndexChangedCommand = new DelegateCommand(GetPagePreviewWhenIndexChanged);

            ConfirmPrintCommand = new DelegateCommand(ConfirmPrint);

            printSettingsInfo = new PrintSettingsInfo();

            GetContentByPrintMod = new Dictionary<string, string>();
            InitGetContentByPrintMod(ref GetContentByPrintMod);

            GetPrinterNameByPrinterIndex = new Dictionary<int, string>();
            InitGetPrinterNameByPrinterIndex(ref GetPrinterNameByPrinterIndex);

            InitComponent();

        }

        #region 组件初始化
        private void InitComponent()
        {
            InitPrinterNameList();
            InitPrintContentList();
            InitPrintContentList();
            InitPrintOrientationList();
        }

        private void PaintPageByCurrentPreviewIndex()
        {
            if (flagIsAutoOrientation)
            {
                if (document.GetPageSize(CurrentPreviewIndex).Width > document.GetPageSize(CurrentPreviewIndex).Height)
                {
                    //printSettingsInfo.EnumPrintOrientation = EnumPrintOrientation.StatusLandscape;
                    PrintOrientationIndex = 1;
                }
            }

            if (NeedPageIndexReverse)
            {
                CurrentPreviewIndex = TargetPages.Count - CurrentPreviewIndex - 1;
            }

            lock (locker)
            {
                switch (CurrentPrintModName)
                {
                    case "ModPoster":
                        PreviewModPoster(CurrentPreviewIndex);
                        break;
                    case "ModMultiple":
                        PreviewModMultiple(CurrentPreviewIndex);
                        break;
                    case "ModBooklet":
                        PreviewModBooklet(CurrentPreviewIndex);
                        break;
                    case "ModSize":
                    default:
                        PreviewModSize(CurrentPreviewIndex);
                        break;
                }
            }
        }

        private void InitPrinterNameList()
        {
            PrinterNameList = new List<string>();
            PrintDocument printDocument = new PrintDocument();
            string defaultPrinterName = printDocument.PrinterSettings.PrinterName;

            foreach (string printerListItem in PrinterSettings.InstalledPrinters)
            {
                PrinterNameList.Add(printerListItem);
            }
        }
        private void InitPrintContentList()
        {
            PrintContentList = new List<string>();
            PrintContentList.Add("文档");
            PrintContentList.Add("文档和标记");
            PrintContentList.Add("文档和图章");
            PrintContentList.Add("文档和表单");
        }

        private void InitPrintOrientationList()
        {
            PrintOrientationList = new List<string>();
            PrintOrientationList.Add("纵向");
            PrintOrientationList.Add("横向");
        }

        private void InitGetContentByPrintMod(ref Dictionary<string, string> dictionary)
        {
            dictionary.Add("ModSize", "HomePagePrinterModSizeContent");
            dictionary.Add("ModPoster", "HomePagePrinterModPosterContent");
            dictionary.Add("ModMultiple", "HomePagePrinterModMultipleContent");
            dictionary.Add("ModBooklet", "HomePagePrinterModBookletContent");
        }

        private void InitGetPrinterNameByPrinterIndex(ref Dictionary<int, string> dictionary)
        {
            int index = 0;
            PrinterNameList = new List<string>();
            PrintDocument printDocument = new PrintDocument();
            string defaultPrinterName = printDocument.PrinterSettings.PrinterName;

            foreach (string printerListItem in PrinterSettings.InstalledPrinters)
            {
                dictionary.Add(index++, printerListItem);
            }
            if (index == 0)
            {
#if DEBUG
                MessageBoxEx.Show("No Printer!");
#endif
            }
        }

        #endregion

        #region 状态初始化
        /// <summary>
        /// 初始化PrintSettingsInfo表
        /// </summary>
        public void InitPrintParams()
        {
            printSettingsInfo.PrinterName = GetPrinterNameByPrinterIndex[PrinterIndex];
            printSettingsInfo.Copies = 1;
            printSettingsInfo.IsBlackAndWhite = false;
            printSettingsInfo.IsReverseOrder = false;
            printSettingsInfo.PrintWithAnnot = true;
            printSettingsInfo.PrintWithForm = true;
            printSettingsInfo.EnumPrintOrientation = EnumPrintOrientation.StatusPortrait;

            SizeInfo sizeSetttingsInfo = new SizeInfo();
            sizeSetttingsInfo.EnumSizeType = EnumSizeType.StatusAdaptive;
            sizeSetttingsInfo.DisplayRatio = 100;
            printSettingsInfo.printMod = sizeSetttingsInfo;
        }

        /// <summary>
        /// 初始化预览
        /// </summary>
        public void InitRender()
        {
            CurrentPreviewIndex = TargetPages[0];
            PaintPageByCurrentPreviewIndex();
            flagIsFirstView = false;
        }
        #endregion

        #region 打印预览

        public void RotatePreviewPaperWhenLandscape()
        {
                RotateAngle = 90;
                RotateCenterX = ViewBoxWidth / 2;
                RotateCenterY = ViewBoxHeight / 2;
                int temp;
                temp = PaperWidth;
                PaperWidth = PaperHeight;
                PaperHeight = temp;
        }
        public void RotatePreviewPaperWhenPortrait()
        {
                RotateAngle = 0;
                RotateCenterX = 0;
                RotateCenterY = 0;
        }


        /// <summary>
        /// 翻页刷新
        /// </summary>
        public void GetPagePreviewWhenIndexChanged()
        {
            if (CurrentPrintModName == "ModSize" && CurrentPrintModName == "ModPoster")
            {
                CurrentPreviewIndex = TargetPages[currentListIndex];
            }
            else
            {
                CurrentPreviewIndex = currentListIndex;
            }
            PaintPageByCurrentPreviewIndex();
        }

        public double GetDpiByGraphics()
        {
            BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.NonPublic;
            PropertyInfo property = typeof(SystemParameters).GetProperty("Dpi", bindingAttr);
            return (int)property.GetValue(null, null);
        }



        /// <summary>
        /// bitmap->bitmapsource转换器，用于显示到image控件
        /// </summary>
        /// <param name="image">
        /// Bitmap格式图片资源
        /// </param>
        /// <returns></returns>
        public static BitmapSource ToBitmapSource(System.Drawing.Bitmap image)
        {
            IntPtr ptr = image.GetHbitmap();//obtain the Hbitmap
            BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap
            (
                ptr,
                IntPtr.Zero,
                Int32Rect.Empty,
                System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()
            );
            return bs;
        }

        /// <summary>
        /// 重新调整图片大小(比例不变) 缩放图片
        /// 可以直接传入目标区域大小，不会丢失原图比例
        /// </summary>
        /// <param name="image"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public System.Drawing.Image ResizeImage(System.Drawing.Image image, System.Drawing.Size size)
        {
            //获取图片宽度
            int sourceWidth = image.Width;
            //获取图片高度
            int sourceHeight = image.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            //计算宽度的缩放比例
            //nPercentW = ((float)size.Width * (float)GetDpiByGraphics()/120/ (float)sourceWidth);
            ////计算高度的缩放比例
            //nPercentH = ((float)size.Height*(float)GetDpiByGraphics() / 120 / (float)sourceHeight);
            nPercentW = ((float)size.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)size.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;
            //期望的宽度
            int destWidth = (int)(sourceWidth * nPercent);
            //期望的高度
            int destHeight = (int)(sourceHeight * nPercent);

            System.Drawing.Bitmap b = new System.Drawing.Bitmap(destWidth, destHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.SmoothingMode = SmoothingMode.None; //抗锯齿
            g.InterpolationMode = InterpolationMode.HighQualityBicubic; //高质量的双三次插值
            g.CompositingQuality = CompositingQuality.HighQuality; //高质量、低速度复合
                                                                   //绘制图像
            g.DrawImage(image, 0, 0, destWidth, destHeight);
            g.Dispose();
            return b;
        }

        /// <summary>
        /// 转灰度
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        private Bitmap ToGray(Bitmap bmp, int mode)
        {
            if (bmp == null)
            {
                return null;
            }

            int w = bmp.Width;
            int h = bmp.Height;
            try
            {
                byte newColor = 0;
                BitmapData srcData = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                unsafe
                {
                    byte* p = (byte*)srcData.Scan0.ToPointer();
                    for (int y = 0; y < h; y++)
                    {
                        for (int x = 0; x < w; x++)
                        {

                            if (mode == 0)　// 加权平均
                            {
                                newColor = (byte)((float)p[0] * 0.114f + (float)p[1] * 0.587f + (float)p[2] * 0.299f);
                            }
                            else　　　　// 算数平均
                            {
                                newColor = (byte)((float)(p[0] + p[1] + p[2]) / 3.0f);
                            }
                            p[0] = newColor;
                            p[1] = newColor;
                            p[2] = newColor;

                            p += 3;
                        }
                        p += srcData.Stride - w * 3;
                    }
                    bmp.UnlockBits(srcData);
                    return bmp;
                }
            }
            catch
            {
                return null;
            }
        }



        /// <summary>
        /// Size模式下的当前页预览
        /// </summary>
        /// <param name="paperIndex"></param>
        private async void PreviewModSize(int paperIndex)
        {
            SizeInfo sizeInfo = (SizeInfo)printSettingsInfo.printMod;
            CPDFPage cPDFPage = document.PageAtIndex(paperIndex);
            if (cPDFPage != null)
            {
                double left = 0;
                double top = 0;
                double ratio = 0.55;
                int dpi = (int)GetDpiByGraphics();
                Bitmap bitmap = await ToolMethod.RenderPageBitmap(document, (int)(cPDFPage.PageSize.Width * ratio * 1.4), (int)(cPDFPage.PageSize.Height * ratio * 1.4), paperIndex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                var pageBound = printDocument.DefaultPageSettings.Bounds;

                if (printSettingsInfo.IsBlackAndWhite)
                {
                    bitmap = ToGray(bitmap, 0);
                }

                double ZoomRate = (double)sizeInfo.DisplayRatio / 100.0;

                if (printSettingsInfo.EnumPrintOrientation == EnumPrintOrientation.StatusLandscape)
                {
                    bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    bitmap = (Bitmap)ResizeImage(bitmap, new System.Drawing.Size((int)(pageBound.Width * ratio), (int)(pageBound.Height * ratio)));
                }

                System.Drawing.Size newSize = new System.Drawing.Size();

                if (sizeInfo.EnumSizeType == EnumSizeType.StatusAdaptive)
                {
                    float zoompercent = 0;
                    float percentW = 0;
                    float percentH = 0;
                    percentW = ((float)(pageBound.Width * ratio) / (float)bitmap.Width);
                    percentH = ((float)(pageBound.Height * ratio) / (float)bitmap.Height);
                    zoompercent = percentH > percentW ? percentW : percentH;

                    newSize = new System.Drawing.Size((int)(bitmap.Width * zoompercent), (int)(bitmap.Height * zoompercent));

                }
                else if (sizeInfo.EnumSizeType == EnumSizeType.StatusActural)
                {
                    newSize = new System.Drawing.Size((int)(bitmap.Width), (int)(bitmap.Height));
                }
                else
                {
                    newSize = new System.Drawing.Size((int)(bitmap.Width * (double)(sizeInfo.DisplayRatio / 100)), (int)(bitmap.Height * (double)(sizeInfo.DisplayRatio / 100)));
                }

                bitmap = (Bitmap)ResizeImage(bitmap, newSize);

                left = (pageBound.Width * ratio - bitmap.Width) / 2;
                top = (pageBound.Height * ratio - bitmap.Height) / 2;

                int pwidth = (int)(pageBound.Width * ratio);
                int pheight = (int)(pageBound.Height * ratio);

                Bitmap bmp = new Bitmap(pwidth, pheight);
                Graphics g = Graphics.FromImage(bmp);
                g.DrawImage(bitmap, (float)left, (float)top, newSize.Width, bitmap.Height);
                BitmapSource = ToBitmapSource(bitmap);
            }
        }

        /// <summary>
        /// 海报模式预览
        /// </summary>
        /// <param name="paperIndex"></param>
        private async void PreviewModPoster(int paperIndex)
        {
            PosterInfo PosterInfo = (PosterInfo)printSettingsInfo.printMod;
            if (PosterInfo.EnumPosterMod == EnumPosterMod.StatusTile)
            {
                PostModTileInfo postModTileInfo = (PostModTileInfo)PosterInfo;
                double zoomRatio = (double)postModTileInfo.TileRatio / 100.0;
                double Ratio = 0.35;
                int dpi = (int)GetDpiByGraphics();
                //重叠部分的像素
                double overLap = Ratio * ((double)postModTileInfo.OverLap / 10) / 2.54 * dpi;
                var pagebound = printDocument.DefaultPageSettings.Bounds;
                //裁剪标记的矩形边长和位置
                int side = 20;
                int margin = -side / 2;
                //预览图的纸张大小 已缩小
                Rectangle printBound = new Rectangle(pagebound.X, pagebound.Y, (int)(pagebound.Width * Ratio), (int)(pagebound.Height * Ratio));
                CPDFPage cPDFPage = document.PageAtIndex(paperIndex);
                Bitmap bitmap = await ToolMethod.RenderPageBitmap(document, (int)(cPDFPage.PageSize.Width * Ratio * zoomRatio * 1.4), (int)(cPDFPage.PageSize.Height * Ratio * zoomRatio * 1.4), paperIndex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                if (printSettingsInfo.IsBlackAndWhite)
                {
                    bitmap = ToGray(bitmap, 0);
                }
                int horizontalMargin = 0;
                int verticalMargin = 0;
                if (postModTileInfo.HasCutMarks || postModTileInfo.HasLabel)
                {
                    horizontalMargin = side * HorizontalPaperCountModPoster;
                    verticalMargin = side * VerticalPaperCountModPoster;
                }

                if (bitmap.Width + horizontalMargin > printBound.Width || bitmap.Height + verticalMargin > printBound.Height)
                {
                    HorizontalPaperCountModPoster = (int)((bitmap.Width + horizontalMargin + overLap) % printBound.Width == 0 ? (bitmap.Width + horizontalMargin + overLap) / printBound.Width : (bitmap.Width + horizontalMargin + overLap) / printBound.Width + 1);
                    VerticalPaperCountModPoster = (int)((bitmap.Height + verticalMargin + overLap) % printBound.Height == 0 ? (bitmap.Height + verticalMargin + overLap) / printBound.Height : (bitmap.Height + horizontalMargin + overLap) / printBound.Height + 1);
                }
            }
        }

        /// <summary>
        /// 多页模式
        /// </summary>
        private async void PreviewModMultiple(int currentPreviewIndex)
        {
            MultipleInfo multipleInfo = (MultipleInfo)this.printSettingsInfo.printMod;

            int pageCount = multipleInfo.HorizontalPageNumber * multipleInfo.VerticalPageNumber;
            printDocument.DefaultPageSettings.PaperSize = new PaperSize("CustomisePaperSize", PaperWidth * 4, PaperHeight * 4);
            Rectangle pageBound = printDocument.DefaultPageSettings.Bounds;

            double ratio = 0.5;
            double adjustRatio = 0.25;

            //每个区域的大小
            double eachPageWidth = pageBound.Width * 1.0 * ratio / multipleInfo.HorizontalPageNumber;
            double eachPageHeight = pageBound.Height * 1.0 * ratio / multipleInfo.VerticalPageNumber;
            System.Drawing.Size newSize = new System.Drawing.Size(Convert.ToInt32(eachPageWidth), Convert.ToInt32(eachPageHeight));

            int indexOfList = currentPreviewIndex;
            if (currentPreviewIndex != 0)
            {
                indexOfList = currentPreviewIndex * pageCount;
            }

            Bitmap bitmapWhenDefault = new Bitmap((int)(pageBound.Width * ratio), (int)(pageBound.Height * ratio));

            var dpi = GetDpiByGraphics();

            Graphics g = Graphics.FromImage(bitmapWhenDefault);

            try
            {
                if ((int)multipleInfo.EnumPageOrder < 2)//横向
                {
                    for (int tempCurrentVerticalPageIndex = 0; tempCurrentVerticalPageIndex < multipleInfo.VerticalPageNumber; tempCurrentVerticalPageIndex++)
                    {

                        for (int tempCurrentHorizonPageIndex = 0; tempCurrentHorizonPageIndex < multipleInfo.HorizontalPageNumber; tempCurrentHorizonPageIndex++)
                        {
                            if (indexOfList > document.PageCount - 1)
                            {
                                BitmapSource = ToBitmapSource(bitmapWhenDefault);
                                return;
                            }
                            CPDFPage cPDFPage = document.PageAtIndex(TargetPages[indexOfList]);
                            double pageWidth = cPDFPage.PageSize.Width * 1.4;
                            double pageHeight = cPDFPage.PageSize.Height * 1.4;
                            Bitmap bitmapWhenSuccessful =
                                await ToolMethod.RenderPageBitmap(
                                    document,
                                (int)(cPDFPage.PageSize.Width * ratio * 1.4),
                                (int)(cPDFPage.PageSize.Height * ratio * 1.4),
                                TargetPages[indexOfList],
                                printSettingsInfo.PrintWithAnnot,
                                printSettingsInfo.PrintWithForm);

                            if (printSettingsInfo.IsBlackAndWhite == true)
                            {
                                bitmapWhenSuccessful = ToGray(bitmapWhenSuccessful, 0);
                            }

                            if (printSettingsInfo.EnumPrintOrientation == EnumPrintOrientation.StatusLandscape)
                            {
                                bitmapWhenSuccessful.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            }

                            if (multipleInfo.IsAutoRotate &&
                                (newSize.Width - newSize.Height) * (bitmapWhenSuccessful.Width * bitmapWhenSuccessful.Height) < 0)
                            {
                                bitmapWhenSuccessful.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            }

                            bitmapWhenSuccessful = (Bitmap)ResizeImage(bitmapWhenSuccessful, newSize);
                            int LocationMarginLeft = (newSize.Width - bitmapWhenSuccessful.Width) / 2;
                            int LocationMarginTop = (newSize.Height - bitmapWhenSuccessful.Height) / 2;

                            if (multipleInfo.EnumPageOrder == EnumPageOrder.StatusHorizontalOrder)
                            {

                                g.DrawImage(
                                    bitmapWhenSuccessful,
                                    (int)(tempCurrentHorizonPageIndex * eachPageWidth + LocationMarginLeft),
                                    (int)(tempCurrentVerticalPageIndex * eachPageHeight + LocationMarginTop),
                                    bitmapWhenSuccessful.Width,
                                    bitmapWhenSuccessful.Height);
                            }
                            else
                            {
                                g.DrawImage(
                                    bitmapWhenSuccessful,
                                    (int)((multipleInfo.HorizontalPageNumber - 1 - tempCurrentHorizonPageIndex) * eachPageWidth + LocationMarginLeft),
                                    (int)(tempCurrentVerticalPageIndex * eachPageHeight + LocationMarginTop),
                                    bitmapWhenSuccessful.Width,
                                    bitmapWhenSuccessful.Height);
                            }
                            indexOfList++;
                        }
                    }
                }
                else
                {
                    for (int tempCurrentHorizonPageIndex = 0; tempCurrentHorizonPageIndex < multipleInfo.HorizontalPageNumber; tempCurrentHorizonPageIndex++)
                    {
                        for (int tempCurrentVerticalPageIndex = 0; tempCurrentVerticalPageIndex < multipleInfo.VerticalPageNumber; tempCurrentVerticalPageIndex++)
                        {
                            if (indexOfList > document.PageCount - 1)
                            {
                                BitmapSource = ToBitmapSource(bitmapWhenDefault);
                                return;
                            }
                            CPDFPage cPDFPage = document.PageAtIndex(indexOfList);
                            Bitmap bitmapWhenSuccessful = await ToolMethod.RenderPageBitmap(
                                document,
                                (int)(cPDFPage.PageSize.Width * ratio * 1.4),
                                (int)(cPDFPage.PageSize.Height * ratio * 1.4),
                                indexOfList,
                                printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                            if (printSettingsInfo.IsBlackAndWhite)
                            {
                                bitmapWhenSuccessful = ToGray(bitmapWhenSuccessful, 0);
                            }
                            if (multipleInfo.IsAutoRotate && (newSize.Width - newSize.Height) * (bitmapWhenSuccessful.Width - bitmapWhenSuccessful.Height) < 0)
                            {
                                bitmapWhenSuccessful.RotateFlip(RotateFlipType.Rotate270FlipNone);
                            }
                            bitmapWhenSuccessful = (Bitmap)ResizeImage(bitmapWhenSuccessful, newSize);

                            int LocationMarginLeft = (newSize.Width - bitmapWhenSuccessful.Width) / 2;
                            int LocationMarginTop = (newSize.Height - bitmapWhenSuccessful.Height) / 2;

                            if (multipleInfo.EnumPageOrder == EnumPageOrder.StatusVerticalOrder)
                            {
                                g.DrawImage(
                                    bitmapWhenSuccessful,
                                    (int)(tempCurrentHorizonPageIndex * eachPageWidth + LocationMarginLeft),
                                    (int)(tempCurrentVerticalPageIndex * eachPageHeight + LocationMarginTop),
                                    bitmapWhenSuccessful.Width,
                                    bitmapWhenSuccessful.Height);
                            }
                            else
                            {
                                g.DrawImage(
                                      bitmapWhenSuccessful,
                                      (int)((multipleInfo.HorizontalPageNumber - 1 - tempCurrentHorizonPageIndex) * eachPageWidth + LocationMarginLeft),
                                      (int)(tempCurrentVerticalPageIndex * eachPageHeight + LocationMarginTop),
                                      bitmapWhenSuccessful.Width,
                                      bitmapWhenSuccessful.Height);

                            }
                            indexOfList++;
                            bitmapWhenSuccessful.Dispose();
                        }
                    }
                }
            }
            catch
            {
                BitmapSource = ToBitmapSource(bitmapWhenDefault);
            }
            BitmapSource = ToBitmapSource(bitmapWhenDefault);
        }

        /// <summary>
        /// 小册子模式预览
        /// PDF Reader Pro原代码，基本未作改动
        /// </summary>
        /// <param name="paperIndex"></param>
        private async void PreviewModBooklet(int currentPreviewIndex)
        {
            BookletInfo bookletInfo = (BookletInfo)printSettingsInfo.printMod;

            printDocument.DefaultPageSettings.PaperSize = new PaperSize("CustomisePaperSize", PaperWidth * 4, PaperHeight * 4);
            Rectangle pageBound = printDocument.DefaultPageSettings.Bounds;
            double ratio = 0.5;

            pageBound.Width = (int)(pageBound.Width * ratio);
            pageBound.Height = (int)(pageBound.Height * ratio);


            double eachPageWidth = 0;
            double eachPageHeight = 0;

            if (printSettingsInfo.EnumPrintOrientation == EnumPrintOrientation.StatusPortrait)
            {
                eachPageWidth = pageBound.Width * 1.0 / 2;
                eachPageHeight = pageBound.Height;
            }
            else
            {
                eachPageWidth = pageBound.Height * 1.0 / 2;
                eachPageHeight = pageBound.Width;
            }
            System.Drawing.Size eachPageSize = new System.Drawing.Size((int)eachPageWidth, (int)eachPageHeight);

            List<int> newPages = TargetPages;

            if (bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly && newPages.Count > 1)
            {
                currentPreviewIndex = 2 * currentPreviewIndex;
            }
            else if (bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusBackSideOnly && newPages.Count > 1)
            {
                currentPreviewIndex = 2 * currentPreviewIndex + 1;
            }

            if (newPages.Count % 4 != 0)
            {
                int tag = newPages.Count % 4;
                if (newPages.Count == 1)
                {
                    tag = 3;
                }
                for (int i = 0; i < 4 - tag; i++)
                {
                    newPages.Add(-1);
                }
            }

            Bitmap bmp = new Bitmap(pageBound.Height, pageBound.Width);
            if (!printDocument.DefaultPageSettings.Landscape)
                bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);
            Graphics g = Graphics.FromImage(bmp);
            var dpi = GetDpiByGraphics();
            for (int i = newPages[currentPreviewIndex], k = 0; k < 2; i = newPages[newPages.Count - 1 - currentPreviewIndex], k++)//为了减少代码量，凑的for循环（跑两次）
            {
                CPDFPage kMPDFPage = document.PageAtIndex(i);
                if (kMPDFPage == null) continue;//表示填充的空白页
                                                //Rect renderRect = new Rect(0.0, 0.0, (int)(kMPDFPage.PageSize.Width*Rate / 72.0 * dpi * 0.85), (int)(kMPDFPage.PageSize.Height*Rate / 72.0 * dpi * 0.85));
                                                //Bitmap bitmap = KMPDFWrapper.RenderPDFPageToBitmap(Doc, i, renderRect,adjustRate * dpi / 72);//这里的参数不能直接用Rate 要手动调试得出
                Bitmap bitmap = await ToolMethod.RenderPageBitmap(document, (int)(kMPDFPage.PageSize.Width * ratio * 1.4), (int)(kMPDFPage.PageSize.Height * ratio * 1.4), i, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);

                if (printSettingsInfo.IsBlackAndWhite)//灰度打印
                    bitmap = ToGray(bitmap, 0);
                if (bookletInfo.IsAutoRotate && ((eachPageSize.Width - eachPageSize.Height) * (bitmap.Width - bitmap.Height) < 0))
                {
                    bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                    bitmap = (Bitmap)ResizeImage(bitmap, eachPageSize);
                }
                else
                    bitmap = (Bitmap)ResizeImage(bitmap, eachPageSize);//重新调整大小
                int top = 0;
                int left = 0;

                //left = (new_size.Width - bitmap.Width) / 2;
                left = (int)(eachPageSize.Width - bitmap.Width);
                top = (eachPageSize.Height - bitmap.Height) / 2;

                if (bookletInfo.EnumBookletBinding == EnumBookletBinding.StatusLeft)//左装订
                {
                    if (bookletInfo.EnumBookletSubset < (EnumBookletSubset)2 || newPages.Count == 2)//仅双面打印的时候需要左右装订的方式交替打印，单面打印的时候不需要
                    {
                        if (currentPreviewIndex == 0 || currentPreviewIndex % 2 == 0 || bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly)//仅打印正面时，不需要左右装订轮着打
                            g.DrawImage(bitmap, (float)((1 - k) * eachPageSize.Width + k * left), (float)(top), bitmap.Width, bitmap.Height);//左订
                        else
                            g.DrawImage(bitmap, (float)(k * eachPageSize.Width + ((k + 1) % 2) * left), (float)(top), bitmap.Width, bitmap.Height);
                    }
                    else//仅反面
                    {
                        g.DrawImage(bitmap, (float)(k * eachPageSize.Width + ((k + 1) % 2) * left), (float)(top), bitmap.Width, bitmap.Height);
                    }
                }
                else//右装订 
                {
                    if (bookletInfo.EnumBookletSubset < (EnumBookletSubset)2 || newPages.Count == 2)//等于2说明 只有一张图和一张空白页
                    {
                        if (currentPreviewIndex == 0 || currentPreviewIndex % 2 == 0 || bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly)
                            g.DrawImage(bitmap, (float)(k * eachPageSize.Width + ((k + 1) % 2) * left), (float)(top), bitmap.Width, bitmap.Height);
                        else
                            g.DrawImage(bitmap, (float)((1 - k) * eachPageSize.Width + k * left), (float)(top), bitmap.Width, bitmap.Height);
                    }
                    else//仅反面
                    {
                        g.DrawImage(bitmap, (float)((1 - k) * eachPageSize.Width + k * left), (float)(top), bitmap.Width, bitmap.Height);
                    }
                }
            }
            BitmapSource = ToBitmapSource(bmp);
        }
        #endregion

        #region 打印

        public System.Drawing.Size Resize(System.Drawing.Size sourceSize, System.Drawing.Size targetSize)
        {
            int sourceWidth = sourceSize.Width;
            //获取图片高度
            int sourceHeight = sourceSize.Height;
            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;
            nPercentW = ((float)targetSize.Width / (float)sourceWidth);
            //计算高度的缩放比例
            nPercentH = ((float)targetSize.Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
                nPercent = nPercentH;
            else
                nPercent = nPercentW;

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);
            return new System.Drawing.Size(destWidth, destHeight);
        }

        private async void ConfirmPrint()
        {
            try
            {
                printerSettings.PrinterName = PrinterNameList[PrinterIndex];
                if (CurrentPrintModName == "ModBooklet")
                {
                    BookletInfo bookletInfo = (BookletInfo)printSettingsInfo.printMod;
                    pageSettings.Landscape = true;
                    if (printerSettings.CanDuplex && bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusBothSides)
                    {
                        printerSettings.Duplex = Duplex.Horizontal;
                    }
                    printDocument.DefaultPageSettings = pageSettings;
                    printDocument.PrinterSettings = printerSettings;
                    currentListIndex = 0;
                    CurrentPreviewIndex = 0;
                    printListIndex = 0;
                }
                await Task.Run(() =>
                {
                    printDocument.Print();
                });
            }
            catch (Exception ex)
            {

            }
        }
        public void InitPrinterSettings()
        {
            location = new System.Drawing.Point((int)(18 * GetDpiByGraphics() / 120), (int)(66 * GetDpiByGraphics() / 120));
            size = new System.Drawing.Size((int)(624 * GetDpiByGraphics() / 120), (int)(130 * GetDpiByGraphics() / 120));
            pageSettings = printDocument.DefaultPageSettings;
            printerSettings = printDocument.PrinterSettings;
            printDocument.DocumentName = document.FileName;
            printDocument.PrintPage += PrintDocument_PrintPage;
        }

        private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            switch (CurrentPrintModName)
            {
                case "ModPoster":
                    PrintDocumentModPoster(e);
                    break;
                case "ModMultiple":
                    PrintDocumentModMultiple(e);
                    break;
                case "ModBooklet":
                    PrintDocumentModBooklet(e);
                    break;
                case "ModSize"://普通 大小模式
                default:
                    PrintDocumentModSize(e);
                    break;
            }
        }

        private void PrintDocumentModSize(PrintPageEventArgs e)
        {
            SizeInfo sizeInfo = (SizeInfo)printSettingsInfo.printMod;

            PrintIndex = TargetPages[printListIndex];
            if (printSettingsInfo.IsIndexReverse)
            {
                PrintIndex = TargetPages[TargetPages.Count - 1 - printListIndex];
            }

            if (printListIndex < TargetPages.Count)
            {

                CPDFPage kMPDFPage = document.PageAtIndex(PrintIndex);
                double left = 0;
                double top = 0;//用于居中设置的边距
                double pagewidth = kMPDFPage.PageSize.Width * 1.4;
                double pageheight = kMPDFPage.PageSize.Height * 1.4;

                int dpi = (int)GetDpiByGraphics();
                double rate = e.Graphics.DpiX / 100;
                //打印不需要跟根据DPI缩放  参数最好手动转int  不然底层库容易报错   0.85是为了调整拿到图和万兴的大小差不多。  0.51是为了调整接口拿到整个图片
                // Rect renderRect = new Rect(0.0, 0.0, (int)(kMPDFPage.PageSize.Width / 72.0 * dpi * 0.85), (int)(kMPDFPage.PageSize.Height / 72.0 * dpi * 0.85));
                //Bitmap bitmap = KMPDFWrapper.RenderPDFPageToBitmap(Doc, PrintIndex, renderRect, 0.51 * dpi / 72);//小数参数需要手动调试
                Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(document, (int)(pagewidth * rate), (int)(pageheight * rate), PrintIndex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);

                var pageBound = printDocument.DefaultPageSettings.Bounds;
                //根据选项 进行微处理
                if (printSettingsInfo.IsBlackAndWhite)//灰度打印
                    bitmap = ToGray(bitmap, 0);

                System.Drawing.Size newSize = new System.Drawing.Size();
                if (sizeInfo.EnumSizeType == EnumSizeType.StatusCustomized)//自定义尺寸
                {
                    newSize = new System.Drawing.Size((int)(pagewidth * sizeInfo.DisplayRatio), (int)(pageheight * sizeInfo.DisplayRatio));
                    //bitmap = (bitmap)resizeimage(bitmap, newsize);
                }
                else if (sizeInfo.EnumSizeType == EnumSizeType.StatusAdaptive)
                {
                    float zoompercent = 0;
                    float percentW = 0;
                    float percentH = 0;
                    percentW = ((float)pageBound.Width / (float)pagewidth);
                    percentH = ((float)pageBound.Height / (float)pageheight);
                    zoompercent = percentH > percentW ? percentW : percentH;

                    newSize = new System.Drawing.Size((int)(pagewidth * zoompercent), (int)(pageheight * zoompercent));
                    //bitmap = (Bitmap)ResizeImage(bitmap, newSize);
                }
                else
                {
                    newSize = new System.Drawing.Size((int)pagewidth, (int)pageheight);
                }
                var r = printDocument.DefaultPageSettings.PrintableArea;
                left = (r.Width - newSize.Width) / 2;
                top = (r.Height - newSize.Height) / 2;

                if (printDocument.DefaultPageSettings.Landscape)//横向打印/横图 分自动旋转和非自动旋转
                {
                    if (pageheight > pagewidth)
                    {
                        e.Graphics.DrawImage(bitmap, new Rectangle((int)left, (int)top, newSize.Width, newSize.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                    }
                    else
                    {
                        e.Graphics.DrawImage(bitmap, new Rectangle((int)left, (int)top, newSize.Width, newSize.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                    }
                }
                else
                {
                    e.Graphics.DrawImage(bitmap, new Rectangle((int)left, (int)top, newSize.Width, newSize.Height), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                }

                bitmap.Dispose();
                if (printListIndex < TargetPages.Count - 1)
                {
                    e.HasMorePages = true;
                }
                printListIndex++;
            }
        }

        private void PrintDocumentModPoster(PrintPageEventArgs e)
        {

        }

        private void PrintDocumentModMultiple(PrintPageEventArgs e)
        {
            MultipleInfo multipleInfo = (MultipleInfo)printSettingsInfo.printMod;

            if (printListIndex < TargetPages.Count)
            {

                //一张纸的页面数
                int h = multipleInfo.VerticalPageNumber;//行
                int v = multipleInfo.HorizontalPageNumber;//列
                int num = h * v;
                //纸张大小
                var pageBound = printDocument.DefaultPageSettings.Bounds;

                //每个区域的大小
                double size_width = pageBound.Width * 1.0 / v;
                double size_height = pageBound.Height * 1.0 / h;
                System.Drawing.Size new_size = new System.Drawing.Size(Convert.ToInt32(size_width), Convert.ToInt32(size_height));

                int indexofList = printListIndex;
                if (printListIndex != 0)
                    indexofList = printListIndex * num;

                var dpi = GetDpiByGraphics();
                Graphics g = e.Graphics;
                try
                {
                    if ((int)multipleInfo.EnumPageOrder < 2)//横向
                    {
                        for (int j = 0; j < h; j++)
                            for (int i = 0; i < v; i++)
                            {
                                if (indexofList > TargetPages.Count - 1)
                                {
                                    return;
                                }
                                int pageindex = 0;

                                CPDFPage kMPDFPage = document.PageAtIndex(pageindex);
                                double pagewidth = kMPDFPage.PageSize.Width * 1.4;
                                double pageheight = kMPDFPage.PageSize.Height * 1.4;
                                var rate = e.Graphics.DpiX / 100;
                                //Rect renderRect = new Rect(0.0, 0.0, (int)(kMPDFPage.PageSize.Width / 72.0 * dpi * 0.85), (int)(kMPDFPage.PageSize.Height / 72.0 * dpi * 0.85));
                                //Bitmap bitmap = KMPDFWrapper.RenderPDFPageToBitmap(Doc, pageindex, renderRect, 0.51 * dpi / 72);//这里的参数不能直接用Rate 要手动调试得出
                                Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(document, (int)(pagewidth * rate), (int)(pageheight * rate), pageindex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                                if (printSettingsInfo.IsBlackAndWhite)//灰度打印
                                    bitmap = ToGray(bitmap, 0);

                                //图片的宽高和容器的宽高大小关系不一致时
                                if (multipleInfo.IsAutoRotate && ((new_size.Width - new_size.Height) * (bitmap.Width - bitmap.Height) < 0))
                                {
                                    bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                    var temp = Resize(new System.Drawing.Size((int)pageheight, (int)pagewidth), new_size);
                                    pagewidth = temp.Width;
                                    pageheight = temp.Height;
                                }
                                else
                                {
                                    //重新调整
                                    var temp = Resize(new System.Drawing.Size((int)pagewidth, (int)pageheight), new_size);
                                    pagewidth = temp.Width;
                                    pageheight = temp.Height;
                                }

                                int top = 0;
                                int left = 0;

                                left = (int)(new_size.Width - pagewidth) / 2;
                                top = (int)(new_size.Height - pageheight) / 2;

                                if (multipleInfo.EnumPageOrder == EnumPageOrder.StatusHorizontalOrder)
                                {
                                    // g.DrawImage(bitmap, (float)(i * size_width + left), (float)(j * size_height + top), bitmap.Width, bitmap.Height);
                                    g.DrawImage(bitmap, new Rectangle((int)(i * size_width + left), (int)(j * size_height + top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                                }
                                else//横向倒序
                                {
                                    //g.DrawImage(bitmap, (float)((v - 1 - i) * size_width + left), (float)((j) * size_height + top), bitmap.Width, bitmap.Height);
                                    g.DrawImage(bitmap, new Rectangle((int)((v - 1 - i) * size_width + left), (int)((j) * size_height + top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                                }
                                indexofList++;
                                bitmap.Dispose();
                            }
                    }
                    else//纵向
                    {
                        for (int j = 0; j < v; j++)
                            for (int i = 0; i < h; i++)
                            {
                                if (indexofList > TargetPages.Count - 1)
                                {
                                    return;
                                }
                                int pageindex = 0;

                                CPDFPage kMPDFPage = document.PageAtIndex(pageindex);
                                double pagewidth = kMPDFPage.PageSize.Width * 1.4;
                                double pageheight = kMPDFPage.PageSize.Height * 1.4;
                                var rate = e.Graphics.DpiX / 100;
                                //Rect renderRect = new Rect(0.0, 0.0, (int)(kMPDFPage.PageSize.Width / 72.0 * dpi * 0.85), (int)(kMPDFPage.PageSize.Height / 72.0 * dpi * 0.85));
                                //Bitmap bitmap = KMPDFWrapper.RenderPDFPageToBitmap(Doc, pageindex, renderRect, 0.51 * dpi / 72);//这里的参数不能直接用Rate 要手动调试得出
                                Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(document, (int)(pagewidth * rate), (int)(pageheight * rate), pageindex, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                                if (printSettingsInfo.IsBlackAndWhite)//灰度打印
                                    bitmap = ToGray(bitmap, 0);

                                if (multipleInfo.IsAutoRotate && ((new_size.Width - new_size.Height) * (bitmap.Width - bitmap.Height) < 0))
                                {
                                    bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                                    // bitmap = (Bitmap)ResizeImage(bitmap, new_size);
                                    var temp = Resize(new System.Drawing.Size((int)pageheight, (int)pagewidth), new_size);
                                    pagewidth = temp.Width;
                                    pageheight = temp.Height;
                                }
                                else
                                {
                                    var temp = Resize(new System.Drawing.Size((int)pagewidth, (int)pageheight), new_size);
                                    pagewidth = temp.Width;
                                    pageheight = temp.Height;
                                }
                                int top = 0;
                                int left = 0;

                                left = (new_size.Width - (int)pagewidth) / 2;
                                top = (new_size.Height - (int)pageheight) / 2;

                                if (multipleInfo.EnumPageOrder == EnumPageOrder.StatusVerticalOrder)//纵向
                                {
                                    g.DrawImage(bitmap, new Rectangle((int)(j * size_width + left), (int)(i * size_height + top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                                }
                                else//纵向倒序
                                {
                                    g.DrawImage(bitmap, new Rectangle((int)((v - 1 - j) * size_width + left), (int)((i) * size_height + top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                                }
                                indexofList++;
                                bitmap.Dispose();
                            }
                    }
                }
                catch (Exception ex)
                {

                }
                if ((printListIndex + 1) * num < TargetPages.Count)
                {
                    e.HasMorePages = true;
                }
                printListIndex++;
            }
        }

        private void PrintDocumentModBooklet(PrintPageEventArgs e)
        {
            BookletInfo bookletInfo = (BookletInfo)printSettingsInfo.printMod;
            if (printListIndex < TargetPages.Count)
            {
                int index = printListIndex;
                var pagebound = printDocument.DefaultPageSettings.Bounds;
                double size_width = 0;
                double size_height = 0;
                //已经设置了横置
                size_width = pagebound.Width * 1.0 / 2;
                size_height = pagebound.Height;


                System.Drawing.Size new_size = new System.Drawing.Size((int)size_width, (int)size_height);

                if (bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly && TargetPages.Count > 1)
                    index = 2 * index;
                else if ((int)bookletInfo.EnumBookletSubset == 2 && TargetPages.Count > 1)
                    index = 2 * index + 1;

                if (TargetPages.Count % 4 != 0)//如果不能整除  要添加空白页
                {
                    int tag = TargetPages.Count % 4;
                    if (TargetPages.Count == 1)
                        tag = 3;//补一张空白页
                    for (int i = 0; i < 4 - tag; i++)
                    {
                        TargetPages.Add(-1);
                    }
                }

                //拿首尾两张图片
                //Bitmap bmp = new Bitmap(pagebound.Width, pagebound.Height);
                //if (!printDocument.DefaultPageSettings.Landscape)
                //    bmp.RotateFlip(RotateFlipType.Rotate270FlipNone);//没有横置时。    实际打印不用这么麻烦，必然是横置的
                Graphics g = e.Graphics;
                var dpi = GetDpiByGraphics();
                for (int i = TargetPages[index], k = 0; k < 2; i = TargetPages[TargetPages.Count - 1 - index], k++)//为了减少代码量，凑的for循环（跑两次）
                {
                    CPDFPage kMPDFPage = document.PageAtIndex(i);
                    if (kMPDFPage == null) continue;//表示填充的空白页
                    var pagewidth = kMPDFPage.PageSize.Width * 1.4;
                    var pageheight = kMPDFPage.PageSize.Height * 1.4;
                    var rate = e.Graphics.DpiX / 100;
                    //Rect renderRect = new Rect(0.0, 0.0, (int)(kMPDFPage.PageSize.Width / 72.0 * dpi * 0.85), (int)(kMPDFPage.PageSize.Height / 72.0 * dpi * 0.85));
                    //Bitmap bitmap = KMPDFWrapper.RenderPDFPageToBitmap(Doc, i, renderRect, 0.51 * dpi / 72);//这里的参数不能直接用Rate 要手动调试得出
                    Bitmap bitmap = ToolMethod.RenderPageBitmapNoWait(document, (int)(pagewidth * rate), (int)(pageheight * rate), i, printSettingsInfo.PrintWithAnnot, printSettingsInfo.PrintWithForm);
                    if (printSettingsInfo.IsBlackAndWhite)//灰度打印
                        bitmap = ToGray(bitmap, 0);
                    if (bookletInfo.IsAutoRotate && ((new_size.Width - new_size.Height) * (bitmap.Width - bitmap.Height) < 0))
                    {
                        bitmap.RotateFlip(RotateFlipType.Rotate270FlipNone);
                        var temp = Resize(new System.Drawing.Size((int)pageheight, (int)pagewidth), new_size);
                        pagewidth = temp.Width;
                        pageheight = temp.Height;
                    }
                    else
                    {
                        var temp = Resize(new System.Drawing.Size((int)pagewidth, (int)pageheight), new_size);
                        pagewidth = temp.Width;
                        pageheight = temp.Height;
                    }

                    int top = 0;
                    int left = 0;

                    left = (new_size.Width - (int)pagewidth) / 2;
                    top = (new_size.Height - (int)pageheight) / 2;

                    if (bookletInfo.EnumBookletBinding == EnumBookletBinding.StatusLeft)//左装订
                    {
                        if ((int)bookletInfo.EnumBookletSubset < 2 || TargetPages.Count == 2)//仅双面打印的时候需要左右装订的方式交替打印，单面打印的时候不不需要
                        {
                            if (index == 0 || index % 2 == 0 || bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly)//仅打印正面时，不需要左右装订轮着打
                            {
                                g.DrawImage(bitmap, new Rectangle((int)((1 - k) * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            }
                            // g.DrawImage(bitmap, (float)((1 - k) * size_width + left), (float)(top), bitmap.Width, bitmap.Height);//左订
                            else
                            {
                                g.DrawImage(bitmap, new Rectangle((int)(k * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            }
                            //g.DrawImage(bitmap, (float)(k * size_width + left), (float)(top), bitmap.Width, bitmap.Height);
                        }
                        else//仅反面
                        {
                            g.DrawImage(bitmap, new Rectangle((int)(k * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            //g.DrawImage(bitmap, (float)(k * size_width + left), (float)(top), bitmap.Width, bitmap.Height);
                        }
                    }
                    else//右装订 
                    {
                        if ((int)bookletInfo.EnumBookletSubset < 2 || TargetPages.Count == 2)
                        {
                            if (index == 0 || index % 2 == 0 || bookletInfo.EnumBookletSubset == EnumBookletSubset.StatusFrontSideOnly)
                            {
                                g.DrawImage(bitmap, new Rectangle((int)(k * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            }
                            else
                            {
                                g.DrawImage(bitmap, new Rectangle((int)((1 - k) * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            }
                            //g.DrawImage(bitmap, (float)(k * size_width + left), (float)(top), bitmap.Width, bitmap.Height);
                            //else
                            //    g.DrawImage(bitmap, (float)((1 - k) * size_width + left), (float)(top), bitmap.Width, bitmap.Height);
                        }
                        else//仅反面
                        {
                            g.DrawImage(bitmap, new Rectangle((int)((1 - k) * size_width + left), (int)(top), (int)pagewidth, (int)pageheight), new Rectangle(0, 0, bitmap.Width, bitmap.Height), GraphicsUnit.Pixel);
                            //g.DrawImage(bitmap, (float)((1 - k) * size_width + left), (float)(top), bitmap.Width, bitmap.Height);
                        }
                    }
                    bitmap.Dispose();
                }
            }
            int MaxPageIndex = ((document.PageCount % 4 == 0) ? (document.PageCount / 4) : (document.PageCount / 4 + 1)) * 2;
            if (printListIndex + 1 < MaxPageIndex)
            {
                e.HasMorePages = true;
            }
            printListIndex++;
        }
        #endregion

        #region 参数设置辅助函数
        /// <summary>
        /// 获取目标页码：从全部页面
        /// </summary>
        public void GetTargetPageIndexFromAll()
        {
            TargetPages.Clear();
            for (int temp = 0; temp < document.PageCount; temp++)
            {
                TargetPages.Add(temp);
            }
            MaxPageNumber = TargetPages.Count.ToString();
        }

        /// <summary>
        /// 获取目标页码：从当前页面
        /// </summary>
        public void GetTargePageIndexFromCurrentPage()
        {
            TargetPages.Clear();
            TargetPages.Add(CurrentPreviewIndex);
            MaxPageNumber = TargetPages.Count.ToString();
        }

        public void GetTargetPageIndexFromOddPage()
        {
            TargetPages.Clear();
            for (int temp = 0; temp < document.PageCount; temp += 2)
            {
                TargetPages.Add(temp);
            }
            MaxPageNumber = TargetPages.Count.ToString();
        }

        public void GetTargetPageIndexFromEvenPage()
        {
            TargetPages.Clear();
            if (document.PageCount > 2)
            {
                for (int temp = 1; temp < document.PageCount; temp += 2)
                {
                    TargetPages.Add(temp);
                }
                MaxPageNumber = TargetPages.Count.ToString();
            }
            else
            {
                TargetPages.Clear();
                for (int temp = 0; temp < document.PageCount; temp++)
                {
                    TargetPages.Add(temp);
                }
                MaxPageNumber = TargetPages.Count.ToString();
            }
        }
        #endregion

        #region 事件
        /// <summary>
        /// 事件：来自PrintMod Region的参数修改
        /// </summary>
        /// <param name="printMod"></param>
        private void SubscribeEvent(Model.Dialog.HomePageToolsDialogs.HomePagePrinter.PrintMod printMod)
        {
            this.printSettingsInfo.printMod = printMod;
            if (CurrentPrintModName == "ModMultiple")
            {
                MultipleInfo multipleInfo = (MultipleInfo)this.printSettingsInfo.printMod;
                MaxPageNumber = ((TargetPages.Count % (multipleInfo.HorizontalPageNumber * multipleInfo.VerticalPageNumber) == 0) ? (TargetPages.Count / (multipleInfo.HorizontalPageNumber * multipleInfo.VerticalPageNumber)) : (TargetPages.Count / (multipleInfo.HorizontalPageNumber * multipleInfo.VerticalPageNumber) + 1)).ToString();
            }
            else if (CurrentPrintModName == "ModBooklet")
            {
                if (TargetPages.Count < 2)
                {
                    MaxPageNumber = (1).ToString();
                }
                else
                {
                    MaxPageNumber = (((TargetPages.Count % 4 == 0) ? (TargetPages.Count / 4) : (TargetPages.Count / 4 + 1)) * 2).ToString();
                }
            }
            else
            {
                MaxPageNumber = TargetPages.Count.ToString();
            }
            //TODO:
            PaintPageByCurrentPreviewIndex();
        }
        #endregion

        #region  参数设置
        /// <summary>
        /// 唤起页面设置窗口
        /// </summary>
        public void SetPaperSize()
        {
            int previousLeftMargin = LeftMargin;
            int previousRightMargin = RightMargin;
            int previousTopMargin = TopMargin;
            int previousBottomMargin = BottomMargin;
            int previousPaperHeight = PaperHeight;
            int previousPaperWidth = PaperWidth;
            EnumPaperSize previousEnumPaperSize = EnumPaperSize;

            DialogParameters value = new DialogParameters();
            Dialogs.ShowDialog(DialogNames.HomePagePrinterPageSetDialog, value, e =>
            {
                if (e.Result == ButtonResult.OK)
                {
                    LeftMargin = e.Parameters.GetValue<int>("LeftMargin");
                    TopMargin = e.Parameters.GetValue<int>("TopMargin");
                    RightMargin = e.Parameters.GetValue<int>("RightMargin");
                    BottomMargin = e.Parameters.GetValue<int>("BottomMargin");
                    PaperWidth = e.Parameters.GetValue<int>("PaperWidth");
                    PaperHeight = e.Parameters.GetValue<int>("PaperHeight");
                    EnumPaperSize = (EnumPaperSize)e.Parameters.GetValue<int>("PaperSizeIndex");
                }
            });
            if (!(previousLeftMargin == LeftMargin &&
                previousRightMargin == RightMargin &&
                previousTopMargin == TopMargin &&
                previousBottomMargin == BottomMargin &&
                previousPaperHeight == PaperHeight &&
                previousPaperWidth == PaperWidth &&
                previousEnumPaperSize == EnumPaperSize))
            {
                if ((PaperHeight * 1.0 / PaperWidth) >= (297 * 1.0 / 210))
                {
                    CanvasHeight = 297;
                    CanvasWidth = 297 * PaperWidth / PaperHeight;
                }
                else
                {
                    CanvasWidth = 210;
                    CanvasHeight = PaperHeight * 210 / PaperWidth;
                }
                ViewBoxWidth = CanvasWidth - LeftMargin - RightMargin;
                ViewBoxHeight = CanvasHeight - TopMargin - BottomMargin;
                PaintPageByCurrentPreviewIndex();
            }
        }

        /// <summary>
        /// 设置黑白色
        /// </summary>
        public void SetIsBlackAndWhite()
        {
            printSettingsInfo.IsBlackAndWhite = IsBlackAndWhite;
            PaintPageByCurrentPreviewIndex();
        }

        /// <summary>
        /// 设置页面范围
        /// </summary>
        public void SetPageRange()
        {
            switch (PageRangeIndex)
            {
                case 1:
                    {
                        GetTargePageIndexFromCurrentPage();
                        break;
                    }
                case 2:
                    {
                        GetTargetPageIndexFromOddPage();
                        break;
                    }
                case 3:
                    {
                        GetTargetPageIndexFromEvenPage();
                        break;
                    }
                case 0:
                default:
                    {
                        GetTargetPageIndexFromAll();
                        break;
                    }
            }
            currentListIndex = 0;
            CurrentPreviewIndex = TargetPages[currentListIndex];
            PaintPageByCurrentPreviewIndex();
        }

        /// <summary>
        /// 设置页面旋转
        /// </summary>
        public void SetPrintOrientation()
        {
            if (PrintOrientationIndex == 0)
            {
                printSettingsInfo.EnumPrintOrientation = EnumPrintOrientation.StatusPortrait;
            }
            else
            {
                printSettingsInfo.EnumPrintOrientation = EnumPrintOrientation.StatusLandscape;
            }
            if (!flagIsFirstView)
            {
                PaintPageByCurrentPreviewIndex();
            }
        }

        /// <summary>
        /// 设置打印内容
        /// </summary>
        public void SetPrintContent()
        {
            switch (PrintContentIndex)
            {
                case 1:
                    {
                        printSettingsInfo.PrintWithAnnot = true;
                        printSettingsInfo.PrintWithForm = true;
                        break;
                    }
                case 2:
                    {
                        printSettingsInfo.PrintWithAnnot = true;
                        printSettingsInfo.PrintWithForm = false;
                        break;
                    }
                case 3:
                    {
                        printSettingsInfo.PrintWithAnnot = false;
                        printSettingsInfo.PrintWithForm = true;
                        break;
                    }
                case 0:
                default:
                    {
                        printSettingsInfo.PrintWithAnnot = false;
                        printSettingsInfo.PrintWithForm = false;
                        break;
                    }
            }
            if (!flagIsFirstView)
            {
                PaintPageByCurrentPreviewIndex();
            }
        }

        /// <summary>
        /// 设置逆序打印
        /// </summary>
        public void SetIsPageIndexReverse()
        {
            bool previewIsPageIndexReverse = printSettingsInfo.IsIndexReverse;
            printSettingsInfo.IsIndexReverse = IsPageIndexReverse;
            if (printSettingsInfo.IsIndexReverse || (previewIsPageIndexReverse && (printSettingsInfo.IsIndexReverse == false)))
            {
                NeedPageIndexReverse = true;
                currentListIndex = 0;
            }
            else
            {
                NeedPageIndexReverse = false;
            }


            if (!flagIsFirstView)
            {
                PaintPageByCurrentPreviewIndex();
            }
        }
        #endregion

        #region 打印模式导航

        private void EnterSelectedMod(string currentPrinterModContent)
        {
            if (ExistentPrintModName != currentPrinterModContent)
            {
                NavigationParameters param = new NavigationParameters();
                PrintModVisible = Visibility.Collapsed;
                NavigationParameters keyValuePairs = param;
                keyValuePairs.Add("document", this.document);
                PrintModRegion.RequestNavigate(PrintModRegionName, GetContentByPrintMod[currentPrinterModContent], keyValuePairs);
                PrintModVisible = Visibility.Visible;
                ExistentPrintModName = currentPrinterModContent;
                //TODO:
                PaintPageByCurrentPreviewIndex();
            }
        }

        private void ChangePrintMod(object e)
        {
            var args = e as System.Windows.Controls.Button;
            if (args != null)
            {
                CurrentPrintModName = args.Name;
                EnterSelectedMod(CurrentPrintModName);
                //TODO：
            }
        }
        #endregion

        #region 初始化和结束
        public string Title => "";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            if (ExistentPrintModName != "ModSize")
            {
                CurrentPrintModName = "ModSize";
                NavigationParameters param = new NavigationParameters();
                PrintModVisible = Visibility.Collapsed;
                NavigationParameters keyValuePairs = param;
                keyValuePairs.Add("document", this.document);
                PrintModRegion.RequestNavigate(PrintModRegionName, GetContentByPrintMod["ModSize"], keyValuePairs);
                PrintModVisible = Visibility.Visible;
                ExistentPrintModName = "ModSize";
            }
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            CPDFViewer viewer = null;
            string filepath = "";
            parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out viewer);
            parameters.TryGetValue<string>(ParameterNames.FilePath, out filepath);
            if (viewer != null && viewer.Document != null)
            {
                currentViewer = viewer;
                document = currentViewer.Document;
                if (CurrentPrintModName == null)
                {
                    CurrentPrintModName = "ModSize";
                }
                PrintModRegion.RequestNavigate(PrintModRegionName, GetContentByPrintMod[CurrentPrintModName]);
                InitPrintParams();
                GetTargetPageIndexFromAll();
                InitRender();
                InitPrinterSettings();

            }
        }
        #endregion
    }
}
