using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.Drawing;

namespace Pdf2Png
{
    public class ImgHelper
    {
        public static Bitmap[] GetBitmapArrFromPdf(string pdfPath)
        {
            List<Bitmap> rList = new List<Bitmap>();
            //初始化一个PdfDocument类实例,并加载PDF文档
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(pdfPath);
            doc.PageSettings.Margins.All = 0;
            doc.Pages.Insert(0);
            doc.Pages.RemoveAt(0);
            //遍历PDF每一页
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                //将PDF页转换成Bitmap图形
                System.Drawing.Image bmp = doc.SaveAsImage(i);
                //bmp = MakeThumbnail(bmp);
                rList.Add(new Bitmap(bmp));
            }
            return rList.ToArray();
        }

        public static void MergerImg(Bitmap[] arrMap, string savePath)
        {
            //获取图片数组长度
            int len = arrMap.Length;
            if (len == 0)
                return;

            //求数组中最宽图片的宽度
            int maxWidth = 0;
            //计算图片的总数
            int sumHeight = 0;

            for (int i = 0; i < len; i++)
            {
                maxWidth = Math.Max(maxWidth, arrMap[i].Width);
                sumHeight += arrMap[i].Height;
            }
            //创建一个位图
            Bitmap bgImg = new Bitmap(maxWidth, sumHeight);
            Graphics g = Graphics.FromImage(bgImg);
            //清除画布，背景设置为白色
            g.Clear(Color.White);

            int gHeight = 0;
            for (int i = 0; i < len; i++)
            {
                gHeight = i == 0 ? 0 : gHeight = arrMap[i - 1].Height + gHeight;
                g.DrawImage(arrMap[i], 0, gHeight, arrMap[i].Width, arrMap[i].Height);
            }
            g.Dispose();
            bgImg.Save(savePath);
        }
    }//end of class
}//end of namespace
