DataEntryList.xaml.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  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. var maxWidth = 0.0;
  240. foreach (var scan in SelectedScans)
  241. {
  242. if (bitmaps.TryGetValue(scan.Document.ID, out var list))
  243. {
  244. int page = 1;
  245. foreach (var bitmap in list)
  246. {
  247. maxWidth = Math.Max(maxWidth, bitmap.Width);
  248. ViewDocuments.Add(new(bitmap, scan, page));
  249. page++;
  250. }
  251. }
  252. }
  253. lock (_viewListLock)
  254. {
  255. ViewList.Clear();
  256. foreach(var doc in ViewDocuments)
  257. {
  258. ViewList.Add(doc.Image);
  259. }
  260. if(maxWidth != 0.0)
  261. {
  262. ZoomPanel.Scale = ZoomPanel.ActualWidth / (maxWidth * 1.1);
  263. ZoomPanel.MinScale = ZoomPanel.Scale / 2;
  264. }
  265. }
  266. }
  267. #endregion
  268. #region Uploading
  269. private static byte[] RenderData(ref string filename, byte[] data)
  270. {
  271. var extension = Path.GetExtension(filename).ToLower();
  272. if ((extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp") && ImageUtils.TryGetImageType(data, out var format))
  273. {
  274. return data;
  275. }
  276. else if (extension == ".pdf")
  277. {
  278. return data;
  279. }
  280. else
  281. {
  282. using var stream = new MemoryStream(data);
  283. filename = Path.ChangeExtension(filename, "pdf");
  284. return DataEntryReGroupWindow.RenderToPDF(filename, stream).SaveToBytes();
  285. }
  286. throw new Exception("Could not render file to PDF");
  287. }
  288. private void DynamicTabItem_Drop(object sender, DragEventArgs e)
  289. {
  290. Task.Run(() =>
  291. {
  292. Dispatcher.Invoke(() =>
  293. {
  294. Progress.Show("Uploading documents");
  295. try
  296. {
  297. var result = DocumentUtils.HandleFileDrop(e);
  298. if (result is not null)
  299. {
  300. foreach (var (filename, stream) in result)
  301. {
  302. var newFilename = filename;
  303. byte[] data;
  304. if (stream is null)
  305. {
  306. data = File.ReadAllBytes(newFilename);
  307. }
  308. else
  309. {
  310. using var memStream = new MemoryStream();
  311. stream.CopyTo(memStream);
  312. data = memStream.ToArray();
  313. }
  314. data = RenderData(ref newFilename, data);
  315. _dataEntryGrid.UploadDocument(newFilename, data, Guid.Empty);
  316. }
  317. }
  318. Progress.Close();
  319. }
  320. catch (Exception e)
  321. {
  322. Progress.Close();
  323. MessageWindow.ShowError("Could not upload documents.", e);
  324. }
  325. });
  326. });
  327. }
  328. private void DynamicTabItem_DragOver(object sender, DragEventArgs e)
  329. {
  330. if (e.Data.GetDataPresent(DataFormats.FileDrop) || e.Data.GetDataPresent("FileGroupDescriptor"))
  331. {
  332. e.Effects = DragDropEffects.Copy;
  333. }
  334. else
  335. {
  336. e.Effects = DragDropEffects.None;
  337. }
  338. e.Handled = true;
  339. }
  340. #endregion
  341. private void _documents_OnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  342. {
  343. UpdateViewList(false);
  344. DoSelect(e.Rows);
  345. }
  346. private void DoSelect(CoreRow[]? rows)
  347. {
  348. var appliesTo = rows?.Length == 1
  349. ? rows[0].Get<DataEntryDocument, string>(x => x.Tag.AppliesTo)
  350. : "";
  351. var entityid = rows?.Length == 1
  352. ? rows[0].Get<DataEntryDocument, Guid>(x => x.EntityID)
  353. : Guid.Empty;
  354. var archived = rows?.Length == 1
  355. ? rows[0].Get<DataEntryDocument, DateTime>(x => x.Archived)
  356. : DateTime.MinValue;
  357. SelectionChanged?.Invoke(appliesTo, entityid, archived.IsEmpty());
  358. CloseImageWindows();
  359. }
  360. private void _historyGrid_OnOnSelectItem(object sender, DynamicGridSelectionEventArgs e)
  361. {
  362. DoSelect(e.Rows);
  363. }
  364. private void CloseImageWindows()
  365. {
  366. while (OpenWindows.Count > 0)
  367. {
  368. var win = OpenWindows.Last();
  369. OpenWindows.RemoveAt(OpenWindows.Count - 1);
  370. win.Close();
  371. }
  372. }
  373. private void OpenImageWindow(ImageSource image)
  374. {
  375. var window = OpenWindows.FirstOrDefault(x => x.Images.Contains(image));
  376. if (window is not null)
  377. {
  378. window.Activate();
  379. }
  380. else
  381. {
  382. window = new DataEntryDocumentWindow();
  383. window.Topmost = true;
  384. window.Images.Add(image);
  385. OpenWindows.Add(window);
  386. window.Closed += OpenWindow_Closed;
  387. window.Show();
  388. }
  389. }
  390. private void Image_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  391. {
  392. if (sender is not Image image) return;
  393. if(e.ClickCount >= 2)
  394. {
  395. OpenImageWindow(image.Source);
  396. e.Handled = true;
  397. }
  398. }
  399. private void OpenWindow_Closed(object? sender, EventArgs e)
  400. {
  401. if (sender is not DataEntryDocumentWindow window) return;
  402. OpenWindows.Remove(window);
  403. }
  404. private void _Explode_OnClick(object sender, RoutedEventArgs e)
  405. {
  406. _dataEntryGrid.DoExplode();
  407. }
  408. private List<DataEntryTag>? _tags;
  409. private void _uploadMenu_OnOpened(object sender, RoutedEventArgs e)
  410. {
  411. if (Clipboard.ContainsText())
  412. {
  413. _pasteItem.Header = "Paste Text from Clipboard";
  414. _pasteItem.Visibility = Visibility.Visible;
  415. }
  416. else if (Clipboard.ContainsImage())
  417. {
  418. _pasteItem.Header = "Paste Image from Clipboard";
  419. _pasteItem.Visibility = Visibility.Visible;
  420. }
  421. else if (Clipboard.ContainsFileDropList())
  422. {
  423. int count = CheckAllowableFiles();
  424. if (count > 0)
  425. {
  426. _pasteItem.Header = $@"Paste {count} File{(count > 1 ? "s" : "")} from Clipboard";
  427. _pasteItem.Visibility = Visibility.Visible;
  428. }
  429. }
  430. else
  431. _pasteItem.Visibility = Visibility.Collapsed;
  432. _archive.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  433. ? Visibility.Visible
  434. : Visibility.Collapsed;
  435. _archiveseparator.Visibility = _archive.Visibility;
  436. _tags ??= DataEntryGrid.GetVisibleTagList();
  437. _changeTag.Items.Clear();
  438. foreach (var tag in _tags)
  439. _changeTag.Items.Add(new MenuItem()
  440. {
  441. Header = tag.Name,
  442. Command = new Command((_) => ChangeTag(tag)) { }
  443. });
  444. _changeTag.Items.Add(new Separator());
  445. _changeTag.Items.Add(new MenuItem()
  446. {
  447. Header= "Clear Tags",
  448. Command = new Command((_) => ChangeTag(new DataEntryTag()))
  449. });
  450. _changeTag.Visibility = _dataEntryGrid.SelectedRows.Any() && _tags.Any() && (Security.CanEdit<DataEntryDocument>() || Security.IsAllowed<CanSetupDataEntryTags>())
  451. ? Visibility.Visible
  452. : Visibility.Collapsed;
  453. _changeNote.Visibility = _dataEntryGrid.SelectedRows.Any() && Security.CanEdit<DataEntryDocument>()
  454. ? Visibility.Visible
  455. : Visibility.Collapsed;
  456. _changetagseparator.Visibility = _archive.Visibility;
  457. }
  458. private void ChangeTag(object obj)
  459. {
  460. if (obj is DataEntryTag tag)
  461. _dataEntryGrid.DoChangeTags(tag.ID);
  462. }
  463. private void _addItem_OnClick(object sender, RoutedEventArgs e)
  464. {
  465. var ofd = new OpenFileDialog()
  466. {
  467. Filter = @"All Files (*.pdf, *.bmp, *.png, *.jpg, *.jpeg)|*.pdf;*.bmp;*.png;*.jpg;*.jpeg",
  468. Multiselect = true,
  469. Title = @"Select Files to Upload",
  470. InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
  471. };
  472. if (ofd.ShowDialog() == true)
  473. {
  474. foreach (var file in ofd.FileNames)
  475. Upload(
  476. Path.GetFileName(file),
  477. new FileStream(file,FileMode.Open));
  478. }
  479. }
  480. private void _pasteItem_OnClick(object sender, RoutedEventArgs e)
  481. {
  482. if (Clipboard.ContainsText())
  483. {
  484. Upload(
  485. $"Pasted Text {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.txt",
  486. new MemoryStream(new UTF8Encoding().GetBytes(Clipboard.GetText()))
  487. );
  488. }
  489. else if (Clipboard.ContainsImage())
  490. {
  491. var img = Clipboard.GetImage();
  492. if (img != null)
  493. {
  494. var bmp = ImageUtils.BitmapSourceToBitmap(img);
  495. using (var ms = new MemoryStream())
  496. {
  497. bmp.Save(ms, ImageFormat.Png);
  498. Upload(
  499. $"Pasted Image {DateTime.Now:yyyy-MM-dd hh-mm-ss-fff}.png",
  500. ms
  501. );
  502. }
  503. }
  504. }
  505. else if (CheckAllowableFiles() > 0)
  506. {
  507. var files = Clipboard.GetFileDropList().OfType<String>().ToArray();
  508. foreach (var file in files)
  509. {
  510. Upload(
  511. Path.GetFileName(file),
  512. new FileStream(file,FileMode.Open)
  513. );
  514. }
  515. }
  516. }
  517. private void Upload(string filename, Stream data)
  518. {
  519. var doc = DataEntryReGroupWindow.RenderToPDF(filename, data);
  520. _dataEntryGrid.UploadDocument(Path.ChangeExtension(filename,"pdf"), doc.SaveToBytes(), Guid.Empty);
  521. }
  522. private static int CheckAllowableFiles()
  523. {
  524. var extensions = Clipboard.GetFileDropList().OfType<String>().Select(x => Path.GetExtension(x.ToUpper())).ToArray();
  525. return extensions.Count(x =>
  526. String.Equals(x, "PDF")
  527. || String.Equals(x, "PNG")
  528. || String.Equals(x, "JPG")
  529. || String.Equals(x, "JPEG")
  530. || String.Equals(x, "BMP")
  531. || String.Equals(x, "TXT")
  532. );
  533. }
  534. private void _pages_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
  535. {
  536. if (_pages.SelectedIndex == 0)
  537. _dataEntryGrid.Refresh(false,true);
  538. else if (_pages.SelectedIndex == 1)
  539. _historyGrid.Refresh(false,true);
  540. }
  541. private void _remove_OnClick(object sender, RoutedEventArgs e)
  542. {
  543. _dataEntryGrid.DoRemove();
  544. }
  545. private void _reopen_OnClick(object sender, RoutedEventArgs e)
  546. {
  547. _historyGrid.DoReopen();
  548. }
  549. private void _changeNote_Click(object sender, RoutedEventArgs e)
  550. {
  551. var notes = _dataEntryGrid.SelectedRows.ToObjects<DataEntryDocument>().Select(x => x.Note).Distinct().ToArray();
  552. var note = notes.Length == 1 ? notes[0] : "";
  553. if(TextBoxDialog.Execute("Enter note:", ref note))
  554. {
  555. _dataEntryGrid.DoChangeNote(note);
  556. }
  557. }
  558. private void _dataEntryGrid_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
  559. {
  560. }
  561. private void _ShowImage_Click(object sender, RoutedEventArgs e)
  562. {
  563. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  564. OpenImageWindow(image);
  565. }
  566. private void RotateDocument(Document doc, int pageNumber)
  567. {
  568. var extension = Path.GetExtension(doc.FileName).ToLower();
  569. if (extension == ".pdf")
  570. {
  571. var loadeddoc = new PdfLoadedDocument(doc.Data);
  572. bool allPages = loadeddoc.PageCount() > 1;
  573. if (allPages)
  574. {
  575. allPages = MessageWindow.New()
  576. .Message("Do you want to rotate all pages in this PDF?")
  577. .Title("Rotate all?")
  578. .AddYesButton("All pages")
  579. .AddNoButton("Just this page")
  580. .Display().Result == MessageWindowResult.Yes;
  581. }
  582. if(allPages)
  583. {
  584. foreach (var page in loadeddoc.GetPages())
  585. {
  586. var rotation = (int)page.Rotation;
  587. rotation = (rotation + 1) % 4;
  588. page.Rotation = (PdfPageRotateAngle)rotation;
  589. }
  590. }
  591. else if(pageNumber <= loadeddoc.PageCount())
  592. {
  593. var page = loadeddoc.GetPage(pageNumber - 1);
  594. var rotation = (int)page.Rotation;
  595. rotation = (rotation + 1) % 4;
  596. page.Rotation = (PdfPageRotateAngle)rotation;
  597. }
  598. doc.Data = loadeddoc.SaveToBytes();
  599. }
  600. else if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp")
  601. {
  602. using var stream = new MemoryStream(doc.Data);
  603. var bitmap = Bitmap.FromStream(stream);
  604. bitmap.RotateFlip(RotateFlipType.Rotate90FlipNone);
  605. using var outStream = new MemoryStream();
  606. bitmap.Save(outStream, extension switch
  607. {
  608. ".jpg" or ".jpeg" => ImageFormat.Jpeg,
  609. ".png" => ImageFormat.Png,
  610. _ => ImageFormat.Bmp
  611. });
  612. doc.Data = outStream.ToArray();
  613. }
  614. else
  615. {
  616. using var stream = new MemoryStream(doc.Data);
  617. var loadeddoc = DataEntryReGroupWindow.RenderToPDF(doc.FileName, stream);
  618. foreach (var page in loadeddoc.GetPages())
  619. {
  620. var rotation = (int)page.Rotation;
  621. rotation = (rotation + 1) % 4;
  622. page.Rotation = (PdfPageRotateAngle)rotation;
  623. }
  624. doc.Data = loadeddoc.SaveToBytes();
  625. }
  626. }
  627. private void _RotateImage_Click(object sender, RoutedEventArgs e)
  628. {
  629. if (sender is not MenuItem item || item.Tag is not ImageSource image) return;
  630. var document = ViewDocuments.FirstOrDefault(x => x.Image == image);
  631. if (document is null)
  632. {
  633. MessageWindow.ShowError("An error occurred", "Document does not exist in ViewDocuments list");
  634. return;
  635. }
  636. var doc = DataEntryCache.Cache.LoadDocuments(CoreUtils.One(document.Document.Document.ID), checkTimestamp: true).First();
  637. try
  638. {
  639. RotateDocument(doc, document.PageNumber);
  640. }
  641. catch(Exception err)
  642. {
  643. MessageWindow.ShowError("Something went wrong while trying to rotate this document.", err);
  644. return;
  645. }
  646. Client.Save(doc, "Rotated by user.");
  647. if (Path.GetExtension(doc.FileName) == ".pdf")
  648. {
  649. document.Document.Thumbnail = ImageUtils.GetPDFThumbnail(doc.Data, 256, 256);
  650. }
  651. new Client<DataEntryDocument>().Save(document.Document, "");
  652. DataEntryCache.Cache.Add(new DataEntryCachedDocument(doc));
  653. UpdateViewList(true);
  654. }
  655. }