|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using Aspose.Words.Saving;
-
- using Common.system;
-
- using System;
- using System.Collections.Generic;
- using System.IO;
-
- namespace XHWK.WKTool.Utils
- {
- class ZAsposeUtil
- {
- /// <summary>
- /// 将Word文档转换为图片的方法(该方法基于第三方DLL),
- /// 你可以像这样调用该方法: ConvertPDF2Image("F:\\PdfFile.doc", "F:\\","ImageFile", 1, 20);
- /// </summary>
- /// <param name="wordInputPath"></param>
- /// <param name="imageOutputPath">图片输出路径,如果为空,默认值为Word所在路径</param>
- /// <param name="imageName">图片的名字,不需要带扩展名,如果为空,默认值为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 List<string> 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<string> images = new List<string>();
- 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))
- {
- if (imageOutputPath != null)
- {
- 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)
- {
- 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;
- if (imageOutputPath != null)
- {
- string savepath = System.IO.Path.Combine(imageOutputPath, imageName) + "_" + i + "." + imageFormat.ToString();
- doc.Save(savepath, imageSaveOptions);
- images.Add(savepath);
- }
- }
- }
- catch (Exception ex)
- {
- MessageWindow.Show("该文件无法使用!");
- LogHelper.Logerror.Error("【导入方法(ConvertWordToImage)】错误日志:" + ex.Message, ex);
- }
- return images;
- }
- }
- }
|