首先,需要两个工具Z:1.itextsharp.dll;2.gswin32c.exe(依赖gsdll32.dll)
第一个库用于将图片生成到PDF文件
第二个工具用于解析PDF文件成图片
生成PDF文件代码如下:
/// <summary>
/// 将图片生成到PDF文件
/// </summary>
/// <param name="targetFile">目标文件</param>
/// <param name="images">图片源</param>
/// <param name="pageWidth">期望的PDF页面宽度</param>
/// <param name="pageHeight">期望的PDF页面高度</param>
public void Save(string targetFile,List<string> images,int pageWidth,int pageHeight)
{
var document = new Document();
try
{
document.SetPageSize(new Rectangle(0, 0, pageWidth, pageHeight));
document.SetMargins(0, 0, 0, 0);
PdfWriter.GetInstance(document, new FileStream(targetFile, FileMode.Create));
document.Open();
foreach (var imageFile in images)
{
Image wmf = Image.GetInstance(imageFile);
wmf.ScaleAbsolute(pageWidth, pageHeight);
document.Add(wmf);
}
}
finally
{
document.Close();
}
}
解析PDF文件需要把工具复制到安装目录下,代码如下:
/// <summary>
/// 解析PDF文件为图片列表
/// </summary>
/// <param name="fileName">待解析的PDF文件</param>
/// <param name="tempDir">临时目录</param>
/// <returns></returns>
public static void Resolve(string fileName, string tempDir)
{
List<string> imageList = new List<string>();
//此工具对PDF文件名要求为英文
var newFileName = tempDir + "\\" + Guid.NewGuid() + Path.GetExtension(fileName);
File.Copy(fileName, newFileName);
fileName = newFileName;
string name = Path.GetFileNameWithoutExtension(fileName);
string folder = tempDir + "\\" + Guid.NewGuid() + "\\";
string outputPath = folder;
Directory.CreateDirectory(outputPath);
outputPath = outputPath + name + "-" + "%08d.jpg";
var info = new ProcessStartInfo
{
CreateNoWindow = true,
WindowStyle = ProcessWindowStyle.Hidden,
WorkingDirectory = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, "PDF"),
//设置命令行参数
Arguments = "-dSAFER -dBATCH -dNOPAUSE -r150 -sDEVICE=jpeg -dGraphicsAlphaBits=4 -sOutputFile=" +
"\"" + outputPath + "\"" + " " + "\"" + fileName + "\"",
FileName = @"gswin32c.exe"
};
var subProcess = new Process { StartInfo = info };
subProcess.Start();
subProcess.WaitForExit(int.MaxValue);
}
Over.