ConverterHelper.cs 25 KB

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