/// <summary>
/// word转图片
/// </summary>
/// /// <param name="wordInputPath">Word文件路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>
/// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public static void ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
{
ImageFormat imageFormat=ImageFormat.Png;
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
int docNum = doc.PageCount;//文档页数
Log.Error("文档页数为:" + docNum.ToString(), "word转图片");
if (doc == null)
{
throw new Exception("Word文件无效或者Word文件被加密!");
}
if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(wordInputPath);
}
if (!Directory.Exists(imageOutputDirPath))
{
Directory.CreateDirectory(imageOutputDirPath);
}
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > doc.PageCount || endPageNum <= 0)
{
endPageNum = doc.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
}
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
if (resolution <= 0)
{
resolution = 128;
}
string imageName = Path.GetFileNameWithoutExtension(wordInputPath);
Aspose.Words.Saving.ImageSaveOptions imageSaveOptions = new Aspose.Words.Saving.ImageSaveOptions(Aspose.Words.SaveFormat.Png);
imageSaveOptions.Resolution = resolution;
for (int i = startPageNum; i <= endPageNum; i++)
{
MemoryStream stream = new MemoryStream();
imageSaveOptions.PageIndex = i - 1;
string imgPath = Path.Combine(imageOutputDirPath, imageName) + "_" + i.ToString("000") + "." + imageFormat.ToString();
doc.Save(stream, imageSaveOptions);
Image img = Image.FromStream(stream);
Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
bm.Save(imgPath, imageFormat);
img.Dispose();
stream.Dispose();
bm.Dispose();
//注意了————————本来这里是200毫秒的,如果报错了的话,请改回去哦。
System.Threading.Thread.Sleep(20);
}
}
catch (Exception ex)
{
Log.Error("错误信息为:" + ex.ToString(), "word转图片");
}
}