using O2S.Components.PDFRender4NET;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace Common.system
{
///
///
/// Class to convert a pdf to an image using GhostScript DLL
/// Credit for this code go to:Rangel Avulso
/// i only fix a little bug and refactor a little
/// http://www.hrangel.com.br/index.php/2006/12/04/converter-pdf-para-imagem-jpeg-em-c/
///
///
public class PdfTrunImage
{
public enum Definition
{
One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
}
///
/// 将PDF文档转换为图片的方法
///
/// PDF文件路径
/// 图片输出路径
/// 生成图片的名字
/// 从PDF文档的第几页开始转换
/// 从PDF文档的第几页开始停止转换
/// 设置所需图片格式
/// 设置图片的清晰度,数字越大越清晰
public static List ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
{
List images = new List();
try
{
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
if (!Directory.Exists(imageOutputPath))
{
Directory.CreateDirectory(imageOutputPath);
}
// validate pageNum
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum == 0 || endPageNum > pdfFile.PageCount)
{
endPageNum = pdfFile.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
string imgPath = imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString();
pageImage.Save(imgPath, imageFormat);
images.Add(imgPath);
// 返回的图片绝对路径集合
pageImage.Dispose();
}
pdfFile.Dispose();
return images;
}
catch (System.Exception ex)
{
LogHelper.WriteErrLog("PDF转图片" +
"【PdfTrunImage】" + ex.Message, ex);
images = new List();
return images;
}
}
}
}