using Aspose.Words.Saving;
using Common.system;
using System;
using System.Collections.Generic;
using System.IO;
namespace XHWK.WKTool.Utils
{
class ZAsposeUtil
{
///
/// 将Word文档转换为图片的方法(该方法基于第三方DLL),
/// 你可以像这样调用该方法: ConvertPDF2Image("F:\\PdfFile.doc", "F:\\","ImageFile", 1, 20);
///
/// Word文件路径
/// 图片输出路径,如果为空,默认值为Word所在路径
/// 图片的名字,不需要带扩展名,如果为空,默认值为Word的名称
/// 从PDF文档的第几页开始转换,如果为0,默认值为1
/// 从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数
/// 设置所需图片格式,如果为null,默认格式为PNG
/// 设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024
public static List ConvertWordToImage(
string wordInputPath,
string imageOutputPath,
string imageName,
int startPageNum = 0,
int endPageNum = 0,
Aspose.Words.SaveFormat imageFormat = Aspose.Words.SaveFormat.Png,
float resolution = 128
)
{
// 返回的图片绝对路径集合
List images = new List();
try
{
// open word file
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);
// validate parameter
if (doc == null) { throw new Exception("Word文件无效或者Word文件被加密!"); }
if (imageOutputPath.Trim().Length == 0) { imageOutputPath = System.IO.Path.GetDirectoryName(wordInputPath); }
if (!Directory.Exists(imageOutputPath)) { Directory.CreateDirectory(imageOutputPath); }
if (imageName.Trim().Length == 0) { imageName = System.IO.Path.GetFileNameWithoutExtension(wordInputPath); }
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 (resolution <= 0) { resolution = 128; }
ImageSaveOptions imageSaveOptions = new ImageSaveOptions(imageFormat)
{
Resolution = resolution
};
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
imageSaveOptions.PageIndex = i - 1;
string savepath = System.IO.Path.Combine(imageOutputPath, imageName) + "_" + i + "." + imageFormat.ToString();
doc.Save(savepath, imageSaveOptions);
images.Add(savepath);
}
imageSaveOptions = null;
doc = null;
}
catch (Exception ex)
{
MessageWindow.Show("该文件无法使用!");
LogHelper.WriteErrLog("【导入方法(ConvertWordToImage)】错误日志:" + ex.Message, ex);
}
return images;
}
}
}