ConverterHelper.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using ComPDFKit_Conversion.Converter;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using Microsoft.AppCenter.Crashes.Ingestion.Models;
  10. using static Dropbox.Api.Sharing.ListFileMembersIndividualResult;
  11. using ComPDFKit_Conversion.Options;
  12. using PDF_Master.CustomControl;
  13. using Exception = System.Exception;
  14. using ImageMagick;
  15. using System.IO.Compression;
  16. using System.Windows;
  17. namespace PDF_Master.Helper
  18. {
  19. public static class ConverterHelper
  20. {
  21. public static CPDFConverterWord wordConverter = null;
  22. public static CPDFConverterExcel excelConverter = null;
  23. public static CPDFConverterPPT pptConverter = null;
  24. public static CPDFConverterTxt txtConverter = null;
  25. public static CPDFConverterCsv csvConverter = null;
  26. public static CPDFConverterImg imgConverter = null;
  27. public static CPDFConverterRTF rtfConverter = null;
  28. public static CPDFConverterHTML htmlConverter = null;
  29. public static async Task<bool> WordConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertWordOptions wordOptions = null, bool IsCustomFileName = true)
  30. {
  31. bool result = false;
  32. try
  33. {
  34. int[] pageArray = pageIndexLists.ToArray();
  35. wordConverter = new CPDFConverterWord(inputpath, pawssword);
  36. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  37. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  38. ConvertError error = ConvertError.ERR_UNKNOWN;
  39. string filename = GetFileNameAddSuffix(outputFolder, outputFileName, ".docx");
  40. result = await Task.Run(() => wordConverter.Convert(outputFolder, ref outputFileName, wordOptions, pageArray, ref error, getProgress));
  41. if (result)
  42. {
  43. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  44. }
  45. }
  46. catch (Exception ex)
  47. {
  48. }
  49. return result;
  50. }
  51. public static async Task<bool> PPTConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertPPTOptions pptOptions = null, bool IsCustomFileName = true)
  52. {
  53. bool result = false;
  54. try
  55. {
  56. int[] pageArray = pageIndexLists.ToArray();
  57. pptConverter = new CPDFConverterPPT(inputpath, pawssword);
  58. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  59. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  60. ConvertError error = ConvertError.ERR_UNKNOWN;
  61. string filename = GetFileNameAddSuffix(outputFolder, outputFileName, ".ppt");
  62. result = await Task.Run(() => pptConverter.Convert(outputFolder, ref outputFileName, pptOptions, pageArray, ref error, getProgress));
  63. if (result)
  64. {
  65. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. }
  71. return result;
  72. }
  73. public static async Task<bool> ExcelConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertExcelOptions ExcelOption, bool IsCustomFileName = true)
  74. {
  75. bool result = false;
  76. try
  77. {
  78. excelConverter = new CPDFConverterExcel(inputpath, pawssword);
  79. int[] pageArray = pageIndexLists.ToArray();
  80. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  81. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  82. ConvertError error = ConvertError.ERR_UNKNOWN;
  83. result = await Task.Run(() => excelConverter.Convert(outputFolder, ref outputFileName, ExcelOption, pageArray, ref error, getProgress));
  84. if (result)
  85. {
  86. if (File.Exists(outputFileName))
  87. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  88. else if (outputFileName == "NoTable")
  89. MessageBoxEx.Show("No Table");
  90. }
  91. }
  92. catch (Exception ex)
  93. {
  94. }
  95. return result;
  96. }
  97. //public static async Task<bool> TableConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword)
  98. //{
  99. // bool result = false;
  100. // try
  101. // {
  102. // int[] pageArray = pageIndexLists.ToArray();
  103. // tableConverter = new CPDFConverterTable(inputpath, pawssword);
  104. // string outputFolder = outputpath;
  105. // string outputFileName = Path.GetFileNameWithoutExtension(inputpath);
  106. // ConvertError error = ConvertError.ERR_UNKNOWN;
  107. // string filename = GetFileNameAddSuffix(outputFolder, outputFileName, ".xlsx");
  108. // result = await Task.Run(() => tableConverter.Convert(outputFolder, ref outputFileName, pageArray, ref error, getProgress));
  109. // }
  110. // catch (Exception ex)
  111. // {
  112. // }
  113. // return result;
  114. //}
  115. public static async Task<bool> CSVConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertCsvOptions csvOptions = null, bool IsCustomFileName = true)
  116. {
  117. bool result = false;
  118. try
  119. {
  120. int[] pageArray = pageIndexLists.ToArray();
  121. csvConverter = new CPDFConverterCsv(inputpath, pawssword);
  122. string outputFolder = "";
  123. string outputFileName = "";
  124. if (IsCustomFileName)
  125. {
  126. outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  127. outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  128. }
  129. else
  130. {
  131. outputFolder = outputpath;
  132. outputFileName = Path.GetFileNameWithoutExtension(inputpath);
  133. }
  134. ConvertError error = ConvertError.ERR_UNKNOWN;
  135. string filename = GetFileNameAddSuffix(outputFolder, outputFileName, ".csv");
  136. result = await Task.Run(() => csvConverter.Convert(outputFolder, ref outputFileName, csvOptions, pageArray, ref error, getProgress));
  137. if (result)
  138. {
  139. if (File.Exists(outputFileName))
  140. {
  141. if (IsCustomFileName)
  142. {
  143. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  144. }
  145. else
  146. {
  147. string FileName = CommonHelper.CreateFolder(outputFileName.Replace(".zip", ""));
  148. ZipFile.ExtractToDirectory(outputFileName, FileName);
  149. File.Delete(outputFileName);
  150. CommonHelper.ShowFileBrowser(FileName.Replace("/", "\\"));
  151. }
  152. }
  153. else
  154. MessageBox.Show("None CSV");
  155. }
  156. }
  157. catch (Exception ex)
  158. {
  159. }
  160. return result;
  161. }
  162. public static async Task<bool> TxtConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertTxtOptions txtOptions = null, bool IsCustomFileName = true)
  163. {
  164. bool result = false;
  165. try
  166. {
  167. int[] pageArray = pageIndexLists.ToArray();
  168. txtConverter = new CPDFConverterTxt(inputpath, pawssword);
  169. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  170. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  171. ConvertError error = ConvertError.ERR_UNKNOWN;
  172. string filename = GetFileNameAddSuffix(outputFolder, outputFileName, ".txt");
  173. result = await Task.Run(() => txtConverter.Convert(outputFolder, ref outputFileName, txtOptions, pageArray, ref error, getProgress));
  174. if (result)
  175. {
  176. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  177. }
  178. }
  179. catch (Exception ex)
  180. {
  181. }
  182. return result;
  183. }
  184. public static void ImageMagickPDFToImage(string imageType, string filePath, string outputFolder, string outputFileName, ref string FileName)
  185. {
  186. FileName = CommonHelper.CreateFolder(outputFolder + "\\" + outputFileName);
  187. ZipFile.ExtractToDirectory(filePath, FileName);
  188. var files = Directory.GetFiles(FileName, "*.png");
  189. int i = 0;
  190. var images = new MagickImageCollection();
  191. foreach (var file in files)
  192. {
  193. //pdf整体转为gif,将.gifoff改为.gif
  194. Trace.WriteLine(file);
  195. if (imageType == ".gifoff")
  196. {
  197. images.Add(file);
  198. images[i].AnimationDelay = 100; // in this example delay is 1000ms/1sec
  199. images[i].Flip();
  200. }
  201. using (var image = new MagickImage(file))
  202. {
  203. if (imageType != ".gifoff")
  204. {
  205. //Save frame as jpg
  206. //image.Format = MagickFormat.Jp2;
  207. image.Write(file.Remove(file.LastIndexOf(".png"), 4) + imageType);
  208. }
  209. // 删除该文件
  210. System.IO.File.Delete(file);
  211. }
  212. }
  213. if (imageType == ".gifoff")
  214. {
  215. // Optionally reduce colors
  216. var settings = new QuantizeSettings();
  217. settings.Colors = 256;
  218. images.Quantize(settings);
  219. // Optionally optimize the images (images should have the same size).
  220. images.Optimize();
  221. // Save gif
  222. int fileIndex = 1;
  223. if (File.Exists(outputFolder + "\\" + outputFileName + ".gif"))
  224. {
  225. while (fileIndex >= 1)
  226. {
  227. if (!File.Exists(outputFolder + "\\" + outputFileName + "_" + fileIndex + ".gif"))
  228. {
  229. images.Write(outputFolder + "\\" + outputFileName + ".gif");
  230. fileIndex = -1;
  231. }
  232. fileIndex++;
  233. }
  234. }
  235. else { images.Write(outputFolder + "\\" + outputFileName + ".gif"); }
  236. }
  237. //else {
  238. // int fileIndex = 1;
  239. // if (File.Exists(outputFolder + "\\" + outputFileName + ".zip"))
  240. // {
  241. // while (fileIndex>=1) {
  242. // if (!File.Exists(outputFolder + "\\" + outputFileName + "_" + fileIndex + ".zip"))
  243. // {
  244. // ZipFile.CreateFromDirectory(outputFolder + "\\" + outputFileName, outputFolder + "\\" + outputFileName + "_" + fileIndex + ".zip");
  245. // fileIndex=-1;
  246. // }
  247. // fileIndex++;
  248. // }
  249. // }
  250. // else { ZipFile.CreateFromDirectory(outputFolder + "\\" + outputFileName, outputFolder + "\\" + outputFileName + ".zip"); }
  251. //}
  252. //DirectoryInfo di = new DirectoryInfo(outputFolder + "\\" + outputFileName);
  253. //di.Delete(true);
  254. }
  255. public static async Task<bool> ImgConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, string imageType = ".png", CPDFConvertImgOptions imgOptions = null)
  256. {
  257. string FileName = "";
  258. bool result = false;
  259. try
  260. {
  261. int[] pageArray = pageIndexLists.ToArray();
  262. imgConverter = new CPDFConverterImg(inputpath, pawssword);
  263. string outputFolder = outputpath;
  264. string outputFileName = Path.GetFileNameWithoutExtension(inputpath);
  265. ConvertError error = ConvertError.ERR_UNKNOWN;
  266. if (imageType == ".png" || imageType == ".jpg")
  267. {
  268. result = await Task.Run(() => imgConverter.Convert(outputFolder, ref outputFileName, imgOptions, pageArray, ref error, getProgress));
  269. FileName = CommonHelper.CreateFolder(outputFileName.Replace(".zip", ""));
  270. ZipFile.ExtractToDirectory(outputFileName, FileName);
  271. FileInfo file = new FileInfo(outputFileName);
  272. if (file.Exists) { file.Delete(); }
  273. }
  274. else
  275. { //创建缓存文件夹
  276. string folderPath = Path.Combine(App.CurrentPath, "ConverterImg");
  277. //有可能因为其他原因存在同名文件,导致创建文件夹失败,需要先删除同名文件
  278. //保险措施(猜测)
  279. if (File.Exists(folderPath))
  280. {
  281. File.Delete(folderPath);
  282. }
  283. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  284. if (!tempfolder.Exists)
  285. {
  286. tempfolder.Create();
  287. }
  288. //预览图缓存
  289. string saveName = Guid.NewGuid().ToString();
  290. string savePath = Path.Combine(folderPath, saveName);
  291. result = await Task.Run(() => imgConverter.Convert(folderPath, ref saveName, imgOptions, pageArray, ref error, getProgress));
  292. ImageMagickPDFToImage(imageType, saveName, outputFolder, outputFileName, ref FileName);
  293. DirectoryInfo di = new DirectoryInfo(folderPath);
  294. di.Delete(true);
  295. }
  296. if (result)
  297. {
  298. //Process.Start(FileName.Replace("/", "\\"));
  299. CommonHelper.ShowFileBrowser(FileName.Replace("/", "\\"));
  300. }
  301. }
  302. catch (Exception ex)
  303. {
  304. }
  305. return result;
  306. }
  307. public static async Task<bool> RTFConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertRTFOptions rtfOptions = null, bool IsCustomFileName = true)
  308. {
  309. bool result = false;
  310. try
  311. {
  312. int[] pageArray = pageIndexLists.ToArray();
  313. rtfConverter = new CPDFConverterRTF(inputpath, pawssword);
  314. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  315. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  316. ConvertError error = ConvertError.ERR_UNKNOWN;
  317. result = await Task.Run(() => rtfConverter.Convert(outputFolder, ref outputFileName, rtfOptions, pageArray, ref error, getProgress));
  318. if (result)
  319. {
  320. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  321. }
  322. }
  323. catch (Exception ex)
  324. {
  325. }
  326. return result;
  327. }
  328. public static async Task<bool> HTMLConvert(string inputpath, string outputpath, OnProgress getProgress, List<int> pageIndexLists, string pawssword, CPDFConvertHTMLOptions HtmlOption, bool IsCustomFileName = true)
  329. {
  330. bool result = false;
  331. try
  332. {
  333. htmlConverter = new CPDFConverterHTML(inputpath, pawssword);
  334. int[] pageArray = pageIndexLists.ToArray();
  335. string outputFolder = outputpath.Remove(outputpath.LastIndexOf("\\"));
  336. string outputFileName = Path.GetFileNameWithoutExtension(outputpath);
  337. ConvertError error = ConvertError.ERR_UNKNOWN;
  338. result = await Task.Run(() => htmlConverter.Convert(outputFolder, ref outputFileName, HtmlOption, pageArray, ref error, getProgress));
  339. if (result)
  340. {
  341. CommonHelper.ShowFileBrowser(outputFileName.Replace("/", "\\"));
  342. }
  343. }
  344. catch (Exception ex)
  345. {
  346. }
  347. return result;
  348. }
  349. public static void Clear()
  350. {
  351. if (wordConverter != null)
  352. {
  353. wordConverter.Cancel();
  354. return;
  355. }
  356. if (excelConverter != null)
  357. {
  358. excelConverter.Cancel();
  359. return;
  360. }
  361. if (pptConverter != null)
  362. {
  363. pptConverter.Cancel();
  364. return;
  365. }
  366. if (txtConverter != null)
  367. {
  368. txtConverter.Cancel();
  369. return;
  370. }
  371. if (csvConverter != null)
  372. {
  373. csvConverter.Cancel();
  374. return;
  375. }
  376. if (rtfConverter != null)
  377. {
  378. rtfConverter.Cancel();
  379. return;
  380. }
  381. if (htmlConverter != null)
  382. {
  383. htmlConverter.Cancel();
  384. return;
  385. }
  386. }
  387. private static void StartFile(string path)
  388. {
  389. //Process.Start(path);
  390. }
  391. public static string GetFileNameAddSuffix(string path, string filename, string suffix)
  392. {
  393. int i = 1;
  394. string outname = filename;
  395. while (File.Exists(path + @"\" + outname + suffix))
  396. {
  397. outname = filename + $"({i.ToString()})";
  398. i++;
  399. }
  400. return outname;
  401. }
  402. public static Microsoft.Office.Interop.Word.Application word;
  403. public static Microsoft.Office.Interop.Excel.Application excele;
  404. public static Microsoft.Office.Interop.PowerPoint.Application ppt;
  405. public static string ConvertOfficeToPDF(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  406. {
  407. string folderPath = Path.GetTempPath();
  408. if (File.Exists(folderPath))
  409. {
  410. File.Delete(folderPath);
  411. }
  412. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  413. if (!tempfolder.Exists)
  414. {
  415. tempfolder.Create();
  416. }
  417. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString() + ".pdf");
  418. string ex = System.IO.Path.GetExtension(sourcepath).ToLower();
  419. switch (ex)
  420. {
  421. case ".doc":
  422. case ".docx":
  423. case "docm":
  424. case ".dot":
  425. case ".dotx":
  426. case ".dotm":
  427. case ".txt":
  428. case ".html":
  429. if (word == null)
  430. {
  431. word = new Microsoft.Office.Interop.Word.Application();
  432. }
  433. Microsoft.Office.Interop.Word.Document document = null;
  434. word.Visible = false;
  435. word.ShowWindowsInTaskbar = true;
  436. document = word.Documents.Open(sourcepath, OpenAndRepair: true);
  437. var page = document.PageSetup;
  438. page.PaperSize = paperSize;
  439. if (margin > 0)
  440. {
  441. page.LeftMargin = page.TopMargin = page.RightMargin = page.BottomMargin = (float)margin;
  442. }
  443. document?.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
  444. document?.Close(false);
  445. if (word != null)
  446. {
  447. word.NormalTemplate.Saved = true;
  448. //word.Quit();
  449. }
  450. break;
  451. case ".xls":
  452. case ".xlsx":
  453. case ".xlsm":
  454. case ".xlsb":
  455. case ".xlam":
  456. case ".xltx":
  457. case ".xlt":
  458. if (excele == null)
  459. {
  460. excele = new Microsoft.Office.Interop.Excel.Application();
  461. }
  462. Microsoft.Office.Interop.Excel.Workbook workbook = null;
  463. excele.Visible = false;
  464. try
  465. {
  466. workbook = excele.Workbooks.Open(sourcepath);
  467. }
  468. catch (Exception e)
  469. {
  470. workbook = excele.Workbooks.Open(sourcepath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlRepairFile);
  471. }
  472. workbook?.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, targetPath);
  473. workbook?.Close();
  474. //excele?.Quit();
  475. break;
  476. case ".ppt":
  477. case ".pptx":
  478. case ".pptm":
  479. case ".pptsx":
  480. case ".pps":
  481. case ".pptsm":
  482. case ".pot":
  483. case ".potm":
  484. if (ppt == null)
  485. {
  486. ppt = new Microsoft.Office.Interop.PowerPoint.Application();
  487. }
  488. Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
  489. //ppt.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
  490. //ppt.ShowStartupDialog = Microsoft.Office.Core.MsoTriState.msoFalse;
  491. //ppt.ShowWindowsInTaskbar = Microsoft.Office.Core.MsoTriState.msoFalse;
  492. presentation = ppt.Presentations.Open(sourcepath);
  493. presentation.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
  494. presentation?.Close();
  495. //ppt?.Quit();
  496. break;
  497. }
  498. return targetPath;
  499. }
  500. }
  501. }