创建DocToImage工厂用于创建不同类型的实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface IImageConverter
{
/// <summary>
/// 将Doc文档转换为图片的方法
/// </summary>
/// <param name="filepath">Doc文件路径</param>
/// <param name="output">图片输出路径,如果为空,默认值为Doc所在路径</param>
/// <param name="startpage">从Doc文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endpage">从Doc文档的第几页开始停止转换,如果为0,默认值为Doc总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
/// <return>返回以逗号隔开的转换成图片文件名</return>
string ConvertToImage(string filepath, string output, int startpage, int endpage, ImageFormat imageFormat=null, int resolution=300);
}

各不同类型的实例实现

提供Excel、PPT、PDF、Word转换成图片的方法,其实这几者之间还可以互相转换,但暂时还没有用到就偷懒了。需要引用Aspose的dll,通过nuget的DLL转换的图片会有水印,下面提供去除水印的dll下载

点我下载

Doc文档转换图片后返回的是图片string以逗号隔开,有需要可以自行修改方法返回结果,这里是用于拼接文件路径和Token搭配文件管理保存到数据库。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
using Aspose.Cells;
using Aspose.Cells.Rendering;
using Aspose.Pdf;
using Aspose.Pdf.Devices;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Huaxi.Util
{
public class ImageConverterFactory
{
public static IImageConverter CreateImageConverter(string extendName)
{
if (extendName == "xls" || extendName == "xlsx")
{
return new Excel2ImageConverter();
}
if (extendName == "doc" || extendName == "docx")
{
return new Word2ImageConverter();
}

if (extendName == "pdf")
{
return new Pdf2ImageConverter();
}

if (extendName == "ppt" || extendName == "pptx")
{
return new Ppt2ImageConverter();
}

//if (extendName == ".rar")
//{
// return new Rar2ImageConverter();
//}

return null;
}

public static bool Support(string extendName)
{
return extendName == "doc" || extendName == "docx"||extendName == "ppt" || extendName == "pptx" || extendName == "pdf" || extendName == "xls" || extendName == "xlsx";
}
}

#region 将Excel文档转换为图片
public class Excel2ImageConverter : IImageConverter
{
public string ConvertToImage(string filepath, string output, int startpage, int endpage, ImageFormat imageFormat = null, int resolution = 300)
{
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
return _ConvertToImage(filepath, output, startpage, endpage, imageFormat, resolution);
}

/// <summary>
/// 将Excel文档转换为图片的方法
/// </summary>
/// <param name="filepath">Excel文档路径</param>
/// <param name="outpath">图片输出路径,如果为空,默认值为Excel文档所在路径</param>
/// <param name="startPage">从Excel文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endPage">从Excel文档的第几页开始停止转换,如果为0,默认值为Excel总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
private string _ConvertToImage(string filepath, string outpath, int startPage, int endPage, ImageFormat imageFormat, int resolution)
{
try
{
var workBook = new Workbook(filepath);

if (workBook == null)
{
throw new Exception("Excel文件无效或者Excel文件已被加密!");
}
var iop = new ImageOrPrintOptions();
iop.ImageFormat = imageFormat;
//iop.AllColumnsInOnePagePerSheet = true;
iop.ImageFormat = imageFormat;
iop.OnePagePerSheet = true;

iop.HorizontalResolution = 400;
iop.VerticalResolution = 400;

if (!Directory.Exists(outpath))
{
Directory.CreateDirectory(outpath);
}

if (startPage <= 0)
{
startPage = 0;
}
if (endPage > workBook.Worksheets.Count || endPage <= 0)
{
endPage = workBook.Worksheets.Count;
}

if (resolution <= 0)
{
resolution = 300;
}
string result = "";
for (int index = startPage; index < endPage; index++)
{
Worksheet item = workBook.Worksheets[index];
SheetRender sr = new SheetRender(item, iop);
string imgName = item.Name + "_" + DateTime.Now.ToString("ddhhmmss_") + index.ToString("000") + "." + imageFormat.ToString();
result += imgName + ",";
string filePath = outpath + "/" + imgName;
for (int kindex = 0; kindex < sr.PageCount; kindex++)
{
sr.ToImage(kindex, filePath);
}
}
return CommonHelper.DelLastComma(result);
}
catch (Exception ex)
{
throw new Exception("转换失败!"+ ex.Message);
}
}
}
#endregion

#region 将word文档转换为图片

public class Word2ImageConverter : IImageConverter
{
/// <summary>
/// 将Word文档转换为图片的方法
/// </summary>
/// <param name="originFilePath">Word文件路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为Word所在路径</param>
/// <param name="startpage">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endpage">从PDF文档的第几页开始停止转换,如果为0,默认值为Word总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage(string originFilePath, string imageOutputDirPath, int startpage, int endpage, ImageFormat imageFormat=null, int resolution=300)
{
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
return _ConvertToImage(originFilePath, imageOutputDirPath, startpage, endpage, imageFormat, resolution);
}

/// <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>
private string _ConvertToImage(string wordInputPath, string imageOutputDirPath, int startPageNum, int endPageNum,
ImageFormat imageFormat, int resolution)
{
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(wordInputPath);

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 (resolution <= 0)
{
resolution = 128;
}

string result = "";
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 = imageName+ "_" + DateTime.Now.ToString("ddhhmmss_")+ i.ToString("000") + "." +imageFormat.ToString();
result += imgPath + ",";
string filePath = imageOutputDirPath + "/" + imgPath;
doc.Save(stream, imageSaveOptions);
System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
bm.Save(filePath, imageFormat);
img.Dispose();
stream.Dispose();
}
return CommonHelper.DelLastComma(result);
}
catch (Exception ex)
{
throw new Exception("转换失败!" + ex.Message);
}
}
}

#endregion

#region 将pdf文档转换为图片

public class Pdf2ImageConverter : IImageConverter
{
/// <summary>
/// 将pdf文档转换为图片的方法
/// </summary>
/// <param name="filepath">pdf文档路径</param>
/// <param name="output">图片输出路径,如果为空,默认值为pdf文档所在路径</param>
/// <param name="startpage">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endpage">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage(string filepath, string output, int startpage, int endpage, ImageFormat imageFormat=null, int resolution=300)
{
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
return _ConvertToImage(filepath, output, startpage, endpage, imageFormat, resolution);
}


private string _ConvertToImage(string filepath, string outpath, int startPage, int endPage, ImageFormat imageFormat,int resolution)
{
try
{
string result = "";
Document pdfDocument = new Document(filepath);
if (pdfDocument == null)
{
throw new Exception("PDF文件无效或者PDF文件已被加密!");
}
if (startPage <= 0)
{
startPage = 1;
}
if (endPage > pdfDocument.Pages.Count || endPage <= 0)
{
endPage = pdfDocument.Pages.Count;
}
if (!Directory.Exists(outpath))
{
Directory.CreateDirectory(outpath);
}

string imageName = Path.GetFileNameWithoutExtension(filepath);

for (int page = startPage; page <= pdfDocument.Pages.Count; page++)
{
if (page > endPage)
{
break;
}

string imgPath = imageName+ "_"+ DateTime.Now.ToString("ddhhmmss_")+ page.ToString("000") + "." +imageFormat.ToString();
result += imgPath + ",";

string filePath = outpath + "/" + imgPath;
using (FileStream imageStream = File.OpenWrite(filePath))
{
// Create PNG device with specified attributes
// Width, Height, Resolution, Quality
// Quality [0-100], 100 is Maximum
// Create Resolution object
Resolution res = new Resolution(resolution);
PngDevice pngDevice = new PngDevice(res);

// Convert a particular page and save the image to stream
pngDevice.Process(pdfDocument.Pages[page], imageStream);

// Close stream
imageStream.Close();
}
}

result= CommonHelper.DelLastComma(result);
return result;
}
catch (Exception ex)
{
throw new Exception("转换失败!" + ex.Message);
}
}
}

#endregion

#region 将ppt文档转换为图片

public class Ppt2ImageConverter : IImageConverter
{
/// <summary>
/// 将PPT文档转换为图片的方法
/// </summary>
/// <param name="originFilePath">PPT文档路径</param>
/// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为PPT文档所在路径</param>
/// <param name="startpage">从PPT文档的第几页开始转换,如果为0,默认值为1</param>
/// <param name="endpage">从PPT文档的第几页开始停止转换,如果为0,默认值为PPT总页数</param>
/// <param name="imageFormat">设置所需图片格式,如果为null,默认格式为PNG</param>
/// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
public string ConvertToImage(string originFilePath, string imageOutputDirPath, int startpage, int endpage, ImageFormat imageFormat=null, int resolution=300)
{
if (imageFormat == null)
{
imageFormat = ImageFormat.Png;
}
return _ConvertToImage(originFilePath, imageOutputDirPath, startpage, endpage,imageFormat,resolution);
}


private string _ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum,
ImageFormat imageFormat, int resolution)
{
try
{
Aspose.Slides.Presentation doc = new Aspose.Slides.Presentation(originFilePath);

if (doc == null)
{
throw new Exception("ppt文件无效或者ppt文件被加密!");
}

if (imageOutputDirPath.Trim().Length == 0)
{
imageOutputDirPath = Path.GetDirectoryName(originFilePath);
}

if (!Directory.Exists(imageOutputDirPath))
{
Directory.CreateDirectory(imageOutputDirPath);
}

if (startPageNum <= 0)
{
startPageNum = 1;
}

if (endPageNum > doc.Slides.Count || endPageNum <= 0)
{
endPageNum = doc.Slides.Count;
}

if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}

if (resolution <= 0)
{
resolution = 128;
}

//先将ppt转换为pdf临时文件
string tmpPdfPath = originFilePath.Substring(0, originFilePath.LastIndexOf(".")) + ".pdf";
doc.Save(tmpPdfPath, Aspose.Slides.Export.SaveFormat.Pdf);

//再将pdf转换为图片
Pdf2ImageConverter converter = new Pdf2ImageConverter();
string result= converter.ConvertToImage(tmpPdfPath, imageOutputDirPath, startPageNum, endPageNum, imageFormat, resolution);

//删除pdf临时文件
File.Delete(tmpPdfPath);
return result;

}
catch (Exception ex)
{
throw new Exception("转换失败!" + ex.Message);
}
}
}

#endregion
}

调用方法根据文件后缀通过工厂获取实例对象转换成图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#region DOC文档转换成图片
if (requestInfo.DocToImg)//是否开启Doc文档转换图片
{
//判断文件后缀是否支持Doc文档转换成图片
if (ImageConverterFactory.Support(fileExtensions))
{
IImageConverter converter = ImageConverterFactory.CreateImageConverter(fileExtensions);
//这里取到Doc文档转换成图片返回的图片名称String以逗号隔开
var imgNameStrs= converter.ConvertToImage(absolutePath, filePath, 0, 0);
//拼接返回结果Name、Size、Token、Path搭配文件管理保存到数据库
List<FileModel> fileModelList = new List<FileModel>();
foreach (var item in imgNameStrs.Split(','))
{
string token = TokenHelper.GetToken(TokenFileName + "/" + item);
fileModelList.Add(new FileModel()
{
Name = item,
Size=FileServiceHelper.GetFileSize(filePath + "/" + item).ToString(),
Token = token,
Path = TokenHelper.GetFileName(token)
});
}
result.DocImgList = fileModelList;
}
}
#endregion