ConverterHelper.cs 24 KB

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