C#PDF转图片

   
 //引用 itextsharp
#region PDF转图片
        /// <summary>
        /// 将PDF转换为图片的方法
        /// </summary>
        /// <param name="pdfInputPath">PDF文件路径</param>
        /// <param name="imageOutputPath">图片输出路径</param>
        /// <param name="imageName">生成图片的名字</param>
        /// <param name="startPageNum">从PDF文档的第几页开始转换</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换</param>
        /// <param name="imageFormat">设置所需图片格式</param>
        /// <param name="definition">设置图片的清晰度,数字越大越清晰</param>
        public static void PdfToImage(string pdfInputPath, ImageFormat imageFormat)
        {

            string YJ = AppDomain.CurrentDomain.BaseDirectory + "JQ\\";
            if (System.IO.Directory.Exists(YJ))
            {
                var files = Directory.GetFiles(YJ);
                for (int i = 0; i < files.Length; i++)
                {
                    File.Delete(files[i]);
                }
            }
            string imageOutputPath = AppDomain.CurrentDomain.BaseDirectory + "JQ\\";
            int    startPageNum = 1;              
            PDFFile pdfFile = PDFFile.Open(pdfInputPath);
              int  endPageNum = pdfFile.PageCount;
            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }    
            if (startPageNum <= 0)
            {
                startPageNum = 1;
            }
            if (imageFormat == null) { imageFormat = ImageFormat.Jpeg; };
            if (endPageNum > pdfFile.PageCount)
            {
                endPageNum = pdfFile.PageCount;
            }
            if (startPageNum > endPageNum)
            {
                int tempPageNum = startPageNum;
                startPageNum = endPageNum;
                endPageNum = startPageNum;
            }
            for (int i = 0; i < endPageNum; i++)
            {
                //后面乘的那个5是设置清晰度,数字越大越清晰,如果有需要可以设置参数,从外部传参
                Bitmap pageImage = pdfFile.GetPageImage(i, 56 * 2);
                pageImage.Save(imageOutputPath +i .ToString() + "." + imageFormat.ToString(), imageFormat);
                pageImage.Dispose();
            }
            pdfFile.Dispose();
        }

        #endregion

 

posted @ 2021-11-06 14:58  .就这  阅读(992)  评论(0编辑  收藏  举报