DataEntryList.xaml.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. using Comal.Classes;
  2. using InABox.Clients;
  3. using InABox.Core;
  4. using Syncfusion.Pdf.Graphics;
  5. using Syncfusion.Pdf.Parsing;
  6. using Syncfusion.Pdf;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Drawing.Imaging;
  10. using System.Drawing;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Media;
  17. using System.Windows.Media.Imaging;
  18. using InABox.DynamicGrid;
  19. using InABox.WPF;
  20. using Encoder = System.Drawing.Imaging.Encoder;
  21. using Path = System.IO.Path;
  22. using Image = System.Windows.Controls.Image;
  23. using System.ComponentModel;
  24. using System.Windows.Controls;
  25. using Clipboard = System.Windows.Clipboard;
  26. using DataFormats = System.Windows.DataFormats;
  27. using DragDropEffects = System.Windows.DragDropEffects;
  28. using DragEventArgs = System.Windows.DragEventArgs;
  29. using MessageBox = System.Windows.MessageBox;
  30. using UserControl = System.Windows.Controls.UserControl;
  31. using InABox.Wpf;
  32. using System.Collections.ObjectModel;
  33. using System.Windows.Data;
  34. using PRSDesktop.Panels.DataEntry;
  35. using InABox.Wpf.Editors;
  36. using System.Timers;
  37. using Microsoft.Win32;
  38. using javax.xml.crypto;
  39. namespace PRSDesktop;
  40. public static class PDFExtensions
  41. {
  42. public static IEnumerable<PdfPageBase> GetPages(this PdfDocumentBase doc)
  43. {
  44. if (doc is PdfLoadedDocument lDoc)
  45. return lDoc.Pages.Cast<PdfPageBase>();
  46. if (doc is PdfDocument pdfDoc)
  47. return pdfDoc.Pages.Cast<PdfPageBase>();
  48. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  49. }
  50. public static PdfPageBase GetPage(this PdfDocumentBase doc, int index)
  51. {
  52. if (doc is PdfLoadedDocument lDoc)
  53. return lDoc.Pages[index];
  54. if (doc is PdfDocument pdfDoc)
  55. return pdfDoc.Pages[index];
  56. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  57. }
  58. public static int PageCount(this PdfDocumentBase doc)
  59. {
  60. if (doc is PdfLoadedDocument lDoc)
  61. return lDoc.Pages.Count;
  62. if (doc is PdfDocument pdfDoc)
  63. return pdfDoc.Pages.Count;
  64. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  65. }
  66. public static PdfLoadedDocument AsLoadedDocument(this PdfDocumentBase doc)
  67. {
  68. if (doc is PdfLoadedDocument lDoc)
  69. return lDoc;
  70. if (doc is PdfDocument pdfDoc)
  71. {
  72. using var ms = new MemoryStream();
  73. pdfDoc.Save(ms);
  74. var array = ms.ToArray();
  75. return new PdfLoadedDocument(array);
  76. }
  77. throw new Exception($"Unsupported PDF Document type {doc.GetType()}");
  78. }
  79. public static byte[] SaveToBytes(this PdfDocumentBase doc)
  80. {
  81. using var ms = new MemoryStream();
  82. doc.Save(ms);
  83. return ms.ToArray();
  84. }
  85. }
  86. /// <summary>
  87. /// Interaction logic for ScanPanel.xaml
  88. /// </summary>
  89. public partial class DataEntryList : UserControl, ICorePanel, IDockPanel
  90. {
  91. private List<DataEntryDocument> SelectedScans = new();
  92. public delegate void DateEntrySelectionHandler(String appliesTo, Guid entityID, bool allowprocess);
  93. public event DateEntrySelectionHandler? SelectionChanged;
  94. private readonly object _viewListLock = new object();
  95. private class ViewDocument
  96. {
  97. public ImageSource Image { get; set; }
  98. public DataEntryDocument Document { get; set; }
  99. public int PageNumber { get; set; }
  100. public ViewDocument(ImageSource image, DataEntryDocument document, int page)
  101. {
  102. Image = image;
  103. Document = document;
  104. PageNumber = page;
  105. }
  106. }
  107. private List<ViewDocument> ViewDocuments { get; } = new();
  108. public ObservableCollection<ImageSource> ViewList { get; init; } = new();
  109. private List<DataEntryDocumentWindow> OpenWindows = new();
  110. public DataEntryList()
  111. {
  112. BindingOperations.EnableCollectionSynchronization(ViewList, _viewListLock);
  113. InitializeComponent();
  114. }
  115. #region Panel
  116. public void Setup()
  117. {
  118. _dataEntryGrid.HiddenColumns.Add(x => x.Document.ID);
  119. _dataEntryGrid.Refresh(true, false);
  120. _historyGrid.Refresh(true, false);
  121. }
  122. public void Refresh()
  123. {
  124. if (_pages.SelectedIndex == 0)
  125. _dataEntryGrid.Refresh(false, true);
  126. else if (_pages.SelectedIndex == 1)
  127. _historyGrid.Refresh(false,true);
  128. }
  129. public void Shutdown(CancelEventArgs? cancel)
  130. {
  131. CloseImageWindows();
  132. }
  133. #endregion
  134. #region View List
  135. private static List<byte[]> RenderTextFile(string textData)
  136. {
  137. var pdfDocument = new PdfDocument();
  138. var page = pdfDocument.Pages.Add();
  139. var font = new PdfStandardFont(PdfFontFamily.Courier, 14);
  140. var textElement = new PdfTextElement(textData, font);
  141. var layoutFormat = new PdfLayoutFormat
  142. {
  143. Layout = PdfLayoutType.Paginate,
  144. Break = PdfLayoutBreakType.FitPage
  145. };
  146. textElement.Draw(page, new RectangleF(0, 0, page.GetClientSize().Width, page.GetClientSize().Height), layoutFormat);
  147. using var docStream = new MemoryStream();
  148. pdfDocument.Save(docStream);
  149. var loadeddoc = new PdfLoadedDocument(docStream.ToArray());
  150. Bitmap[] bmpImages = loadeddoc.ExportAsImage(0, loadeddoc.Pages.Count - 1);
  151. var jpgEncoder = ImageUtils.GetEncoder(ImageFormat.Jpeg)!;
  152. var quality = Encoder.Quality;
  153. var encodeParams = new EncoderParameters(1);
  154. encodeParams.Param[0] = new EncoderParameter(quality, 100L);
  155. var images = new List<byte[]>();
  156. if (bmpImages != null)
  157. foreach (var image in bmpImages)
  158. {
  159. using var data = new MemoryStream();
  160. image.Save(data, jpgEncoder, encodeParams);
  161. images.Add(data.ToArray());
  162. }
  163. return images;
  164. }
  165. private void UpdateViewList(bool force = false)
  166. {
  167. var selected = _dataEntryGrid.SelectedRows.Select(x => x.ToObject<DataEntryDocument>()).ToList();
  168. if (!force && selected.Count == SelectedScans.Count && !selected.Any(x => SelectedScans.All(y => x.ID != y.ID)))
  169. return;
  170. SelectedScans = selected;
  171. ViewList.Clear();
  172. ViewDocuments.Clear();
  173. Task.Run(() =>
  174. {
  175. var docs = DataEntryCache.Cache.LoadDocuments(SelectedScans.Select(x => x.Document.ID).Distinct(), checkTimestamp: true);
  176. LoadDocuments(docs);
  177. }).ContinueWith((task) =>
  178. {
  179. if(task.Exception is not null)
  180. {
  181. MessageWindow.ShowError("An error occurred while loading the documents", task.Exception);
  182. }
  183. }, TaskScheduler.FromCurrentSynchronizationContext());
  184. }
  185. private void LoadDocuments(IEnumerable<Document> documents)
  186. {
  187. var bitmaps = new Dictionary<Guid, List<ImageSource>>();
  188. foreach (var document in documents)
  189. {
  190. List<byte[]> images;
  191. var bitmapImages = new List<ImageSource>();
  192. var extension = Path.GetExtension(document.FileName).ToLower();
  193. if (extension == ".pdf")
  194. {
  195. images = new List<byte[]>();
  196. try
  197. {
  198. bitmapImages = ImageUtils.RenderPDFToImageSources(document.Data);
  199. }
  200. catch (Exception e)
  201. {
  202. MessageBox.Show($"Cannot load document '{document.FileName}': {e.Message}");
  203. }
  204. }
  205. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  206. {
  207. images = new List<byte[]> { document.Data };
  208. }
  209. else
  210. {
  211. images = ImageUtils.RenderTextFileToImages(Encoding.UTF8.GetString(document.Data));
  212. }
  213. bitmapImages.AddRange(images.Select(x =>
  214. {
  215. try
  216. {
  217. return ImageUtils.LoadImage(x);
  218. }
  219. catch (Exception e)
  220. {
  221. Dispatcher.BeginInvoke(() =>
  222. {
  223. MessageWindow.ShowError($"Cannot load document '{document.FileName}", e);
  224. });
  225. }
  226. return null;
  227. }).Where(x => x != null).Cast<ImageSource>());
  228. foreach (var image in bitmapImages)
  229. {
  230. if (!bitmaps.TryGetValue(document.ID, out var list))
  231. {
  232. list = new List<ImageSource>();
  233. bitmaps[document.ID] = list;
  234. }
  235. list.Add(image);
  236. }
  237. }
  238. ViewDocuments.Clear();
  239. foreach (var scan in SelectedScans)
  240. {
  241. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  242. {
  243. int page = 1;
  244. foreach (var bitmap in list)
  245. {
  246. ViewDocuments.Add(new(bitmap, scan, page));
  247. page++;
  248. }
  249. }
  250. }
  251. lock (_viewListLock)
  252. {
  253. ViewList.Clear();
  254. foreach(var doc in ViewDocuments)
  255. {
  256. ViewList.Add(doc.Image);
  257. }
  258. }
  259. }
  260. #endregion
  261. #region Uploading
  262. private static byte[] RenderData(ref string filename, byte[] data)
  263. {
  264. var extension = Path.GetExtension(filename).ToLower();
  265. if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format))
  266. {
  267. return data;
  268. }
  269. else if (extension == ".pdf")
  270. {
  271. return data;
  272. }
  273. else
  274. {
  275. using var stream = new MemoryStream(data);
  276. filename = Path.ChangeExtension(filename, "pdf");
  277. return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes();
  278. }
  279. throw new Exception("Could not render file to PDF");
  280. }
  281. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  282. {
  283. Task.Run(() =>
  284. {
  285. Dispatcher.Invoke(() =>
  286. {
  287. Progress.Show("Uploading documents");
  288. try
  289. {
  290. var result = DocumentUtils.HandleFileDrop(e);
  291. if (result is not null)
  292. {
  293. foreach (var (filename, stream) in result)
  294. {
  295. var newFilename = filename;
  296. byte[] data;
  297. if (stream is null)
  298. {
  299. data = File.ReadAllBytes(newFilename);
  300. }
  301. else
  302. {
  303. using var memStream = new MemoryStream();
  304. stream.CopyTo(memStream);
  305. data = memStream.ToArray();
  306. }
  307. data = RenderData(ref newFilename, data);
  308. _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty);
  309. }
  310. }
  311. Progress.Close();
  312. }
  313. catch (Exception e)
  314. {
  315. Progress.Close();
  316. MessageWindow.ShowError("Could not upload documents.", e);
  317. }
  318. });
  319. });
  320. }
  321. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  322. {
  323. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  324. {
  325. e.Effects = DragDropEffects.Copy;
  326. }
  327. else
  328. {
  329. e.Effects = DragDropEffects.None;
  330. }
  331. e.Handled = true;
  332. }
  333. #endregion
  334. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  335. {
  336. UpdateViewList(false);
  337. DoSelect(e.Rows);
  338. }
  339. private void DoSelect(CoreRow[] rows)
  340. {
  341. var appliesTo = rows?.Length == 1
  342. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  343. : "";
  344. var entityid = rows?.Length == 1
  345. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  346. : Guid.Empty;
  347. var archived = rows?.Length == 1
  348. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  349. : DateTime.MinValue;
  350. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  351. CloseImageWindows();
  352. }
  353. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  354. {
  355. DoSelect(e.Rows);
  356. }
  357. private void CloseImageWindows()
  358. {
  359. while (OpenWindows.Count > 0)
  360. {
  361. var win = OpenWindows.Last();
  362. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  363. win.Close();
  364. }
  365. }
  366. private void OpenImageWindow(ImageSource image)
  367. {
  368. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  369. if (window is not null)
  370. {
  371. window.Activate();
  372. }
  373. else
  374. {
  375. window = new DataEntryDocumentWindow();
  376. window.Topmost = true;
  377. window.Images.Add(image);
  378. OpenWindows.Add(window);
  379. window.Closed += OpenWindow_Closed;
  380. window.Show();
  381. }
  382. }
  383. private void Image_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  384. {
  385. if (sender is not Image image) return;
  386. if(e.ClickCount >= 2)
  387. {
  388. OpenImageWindow(image.Source);
  389. e.Handled = true;
  390. }
  391. }
  392. private void OpenWindow_Closed(object? sender, EventArgs e)
  393. {
  394. if (sender is not DataEntryDocumentWindow window) return;
  395. OpenWindows.Remove(window);
  396. }
  397. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  398. {
  399. _dataEntryGrid.DoExplode();
  400. }
  401. private List<DataEntryTag>? _tags;
  402. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  403. {
  404. if (Clipboard.ContainsText())
  405. {
  406. _pasteItem.Header = "Paste Text from Clipboard";
  407. _pasteItem.Visibility = Visibility.Visible;
  408. }
  409. else if (Clipboard.ContainsImage())
  410. {
  411. _pasteItem.Header = "Paste Image from Clipboard";
  412. _pasteItem.Visibility = Visibility.Visible;
  413. }
  414. else if (Clipboard.ContainsFileDropList())
  415. {
  416. int count = CheckAllowableFiles();
  417. if (count > 0)
  418. {
  419. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  420. _pasteItem.Visibility = Visibility.Visible;
  421. }
  422. }
  423. else
  424. _pasteItem.Visibility = Visibility.Collapsed;
  425. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  426. ? Visibility.Visible
  427. : Visibility.Collapsed;
  428. _archiveseparator.Visibility = _archive.Visibility;
  429. _tags ??= DataEntryGrid.GetVisibleTagList();
  430. _changeTag.Items.Clear();
  431. foreach (var tag in _tags)
  432. _changeTag.Items.Add(new MenuItem()
  433. {
  434. Header = tag.Name,
  435. Command = new Command((_) => ChangeTag(tag)) { }
  436. });
  437. _changeTag.Items.Add(new Separator());
  438. _changeTag.Items.Add(new MenuItem()
  439. {
  440. Header= "Clear Tags",
  441. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  442. });
  443. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  444. ? Visibility.Visible
  445. : Visibility.Collapsed;
  446. _changeNote.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  447. ? Visibility.Visible
  448. : Visibility.Collapsed;
  449. _changetagseparator.Visibility = _archive.Visibility;
  450. }
  451. private void ChangeTag(object obj)
  452. {
  453. if (obj is DataEntryTag tag)
  454. _dataEntryGrid.DoChangeTags(tag.ID);
  455. }
  456. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  457. {
  458. var ofd = new OpenFileDialog()
  459. {
  460. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  461. Multiselect = true,
  462. Title = @"Select Files to Upload",
  463. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  464. };
  465. if (ofd.ShowDialog() == true)
  466. {
  467. foreach (var file in ofd.FileNames)
  468. Upload(
  469. Path.GetFileName(file),
  470. new FileStream(file,FileMode.Open));
  471. }
  472. }
  473. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  474. {
  475. if (Clipboard.ContainsText())
  476. {
  477. Upload(
  478. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  479. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  480. );
  481. }
  482. else if (Clipboard.ContainsImage())
  483. {
  484. var img = Clipboard.GetImage();
  485. if (img != null)
  486. {
  487. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  488. using (var ms = new MemoryStream())
  489. {
  490. bmp.Save(ms, ImageFormat.Png);
  491. Upload(
  492. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  493. ms
  494. );
  495. }
  496. }
  497. }
  498. else if (CheckAllowableFiles() > 0)
  499. {
  500. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  501. foreach (var file in files)
  502. {
  503. Upload(
  504. Path.GetFileName(file),
  505. new FileStream(file,FileMode.Open)
  506. );
  507. }
  508. }
  509. }
  510. private void Upload(string filename, Stream data)
  511. {
  512. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  513. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  514. }
  515. private static int CheckAllowableFiles()
  516. {
  517. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  518. return extensions.Count(x =>
  519. String.Equals(x, "PDF")
  520. || String.Equals(x, "PNG")
  521. || String.Equals(x, "JPG")
  522. || String.Equals(x, "JPEG")
  523. || String.Equals(x, "BMP")
  524. || String.Equals(x, "TXT")
  525. );
  526. }
  527. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  528. {
  529. if (_pages.SelectedIndex == 0)
  530. _dataEntryGrid.Refresh(false,true);
  531. else if (_pages.SelectedIndex == 1)
  532. _historyGrid.Refresh(false,true);
  533. }
  534. private void _remove_OnClick(object sender, RoutedEventArgs e)
  535. {
  536. _dataEntryGrid.DoRemove();
  537. }
  538. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  539. {
  540. _historyGrid.DoReopen();
  541. }
  542. private void _changeNote_Click(object sender, RoutedEventArgs e)
  543. {
  544. var notes = _dataEntryGrid.SelectedRows.ToObjects<DataEntryDocument>().Select(x => x.Note).Distinct().ToArray();
  545. var note = notes.Length == 1 ? notes[0] : "";
  546. if(TextBoxDialog.Execute("Enter note:", ref note))
  547. {
  548. _dataEntryGrid.DoChangeNote(note);
  549. }
  550. }
  551. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  552. {
  553. }
  554. private void _ShowImage_Click(object sender, RoutedEventArgs e)
  555. {
  556. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  557. OpenImageWindow(image);
  558. }
  559. private void RotateDocument(Document doc, int pageNumber)
  560. {
  561. var extension = Path.GetExtension(doc.FileName).ToLower();
  562. if (extension == ".pdf")
  563. {
  564. var loadeddoc = new PdfLoadedDocument(doc.Data);
  565. bool allPages = loadeddoc.PageCount() > 1;
  566. if (allPages)
  567. {
  568. allPages = MessageWindow.New()
  569. .Message("Do you want to rotate all pages in this PDF?")
  570. .Title("Rotate all?")
  571. .AddYesButton("All pages")
  572. .AddNoButton("Just this page")
  573. .Display().Result == MessageWindowResult.Yes;
  574. }
  575. if(allPages)
  576. {
  577. foreach (var page in loadeddoc.GetPages())
  578. {
  579. var rotation = (int)page.Rotation;
  580. rotation = (rotation + 1) % 4;
  581. page.Rotation = (PdfPageRotateAngle)rotation;
  582. }
  583. }
  584. else if(pageNumber <= loadeddoc.PageCount())
  585. {
  586. var page = loadeddoc.GetPage(pageNumber - 1);
  587. var rotation = (int)page.Rotation;
  588. rotation = (rotation + 1) % 4;
  589. page.Rotation = (PdfPageRotateAngle)rotation;
  590. }
  591. doc.Data = loadeddoc.SaveToBytes();
  592. }
  593. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  594. {
  595. using var stream = new MemoryStream(doc.Data);
  596. var bitmap = Bitmap.FromStream(stream);
  597. bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
  598. using var outStream = new MemoryStream();
  599. bitmap.Save(outStream, extension switch
  600. {
  601. ".jpg" or ".jpeg" => ImageFormat.Jpeg,
  602. ".png" => ImageFormat.Png,
  603. _ => ImageFormat.Bmp
  604. });
  605. doc.Data = outStream.ToArray();
  606. }
  607. else
  608. {
  609. using var stream = new MemoryStream(doc.Data);
  610. var loadeddoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, stream);
  611. foreach (var page in loadeddoc.GetPages())
  612. {
  613. var rotation = (int)page.Rotation;
  614. rotation = (rotation + 1) % 4;
  615. page.Rotation = (PdfPageRotateAngle)rotation;
  616. }
  617. doc.Data = loadeddoc.SaveToBytes();
  618. }
  619. }
  620. private void _RotateImage_Click(object sender, RoutedEventArgs e)
  621. {
  622. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  623. var document = ViewDocuments.FirstOrDefault(x => x.Image == image);
  624. if (document is null)
  625. {
  626. MessageWindow.ShowError("An error occurred", "Document does not exist in ViewDocuments list");
  627. return;
  628. }
  629. var doc = DataEntryCache.Cache.LoadDocuments(CoreUtils.One(document.Document.Document.ID), checkTimestamp: true).First();
  630. try
  631. {
  632. RotateDocument(doc, document.PageNumber);
  633. }
  634. catch(Exception err)
  635. {
  636. MessageWindow.ShowError("Something went wrong while trying to rotate this document.", err);
  637. return;
  638. }
  639. Client.Save(doc, "Rotated by user.");
  640. if (Path.GetExtension(doc.FileName) == ".pdf")
  641. {
  642. document.Document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256);
  643. }
  644. new Client<DataEntryDocument>().Save(document.Document, "");
  645. DataEntryCache.Cache.Add(new DataEntryCachedDocument(doc));
  646. UpdateViewList(true);
  647. }
  648. }