ConverterHelper.cs 26 KB

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