PDFEditorControl.xaml.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Drawing.Drawing2D;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using Ghostscript.NET;
  12. using Ghostscript.NET.Processor;
  13. using InABox.Clients;
  14. using InABox.Core;
  15. using InABox.WPF;
  16. using Microsoft.Win32;
  17. using Syncfusion.Pdf;
  18. using Syncfusion.Pdf.Graphics;
  19. using Syncfusion.Pdf.Interactive;
  20. using Syncfusion.Pdf.Parsing;
  21. using Syncfusion.Windows.PdfViewer;
  22. using ColorConverter = System.Windows.Media.ColorConverter;
  23. using Image = System.Windows.Controls.Image;
  24. namespace InABox.DynamicGrid
  25. {
  26. public delegate void PDFSettingsChangedEvent(object sender, string linecolor, int fontsize);
  27. public delegate void PDFDocumentLoadedEvent(object sender, IEntityDocument document);
  28. /// <summary>
  29. /// Interaction logic for PDFEditorControl.xaml
  30. /// </summary>
  31. public partial class PDFEditorControl : UserControl, IDocumentEditor
  32. {
  33. private IEntityDocument _document;
  34. //private PdfDocumentView PdfViewer = null;
  35. private readonly List<Guid> currentAnnotations = new();
  36. private byte[] pdfdocument;
  37. public PDFEditorControl()
  38. {
  39. InitializeComponent();
  40. SaveAllowed = false;
  41. ButtonsVisible = true;
  42. PdfViewer.ReferencePath =
  43. AppDomain.CurrentDomain.BaseDirectory; // System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "pdfium");
  44. PdfViewer.PrinterSettings.PageSize = PdfViewerPrintSize.Fit;
  45. }
  46. public string LineColor { get; set; }
  47. public int TextSize { get; set; }
  48. //public bool PrintAllowed { get; set; }
  49. public bool SaveAllowed { get; set; }
  50. public bool ButtonsVisible { get; set; }
  51. public string Watermark { get; set; }
  52. public PDFSettingsChangedEvent PDFSettingsChanged { get; set; }
  53. public PDFDocumentLoadedEvent PDFDocumentLoaded { get; set; }
  54. public IEntityDocument? Document
  55. {
  56. get => _document;
  57. set
  58. {
  59. UnloadPDF();
  60. _document = value;
  61. LoadPDF();
  62. PDFDocumentLoaded?.Invoke(this, value);
  63. }
  64. }
  65. #region Unload / Save PDF Document
  66. private void UnloadCurrentPDF()
  67. {
  68. UnloadPDFAnnotations();
  69. pdfdocument = null;
  70. }
  71. private string CurrentAnnotations = "";
  72. private string AnnotationsToString()
  73. {
  74. var ms1 = new MemoryStream();
  75. PdfViewer.LoadedDocument.Save(ms1);
  76. ms1.Position = 0;
  77. var doc = new PdfLoadedDocument(ms1);
  78. var sb = new StringBuilder();
  79. for (var i = 0; i < doc.Pages.Count; i++)
  80. {
  81. var page = doc.Pages[i] as PdfLoadedPage;
  82. try
  83. {
  84. foreach (PdfLoadedAnnotation a in page.Annotations)
  85. sb.Append(SaveAnnotation(doc, a));
  86. }
  87. catch (Exception e)
  88. {
  89. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("*** Unable to retreive Annotations ***\n{0}", e.StackTrace));
  90. }
  91. }
  92. return sb.ToString();
  93. }
  94. private void UnloadPDFAnnotations()
  95. {
  96. try
  97. {
  98. if (_document != null && PdfViewer.IsDocumentEdited)
  99. //if ((PdfViewer != null) && (documentid != Guid.Empty) && (pdfdocument != null) && (PdfViewer.Visibility == Visibility.Visible) && (PdfViewer.IsDocumentEdited))
  100. {
  101. var ms1 = new MemoryStream();
  102. PdfViewer.LoadedDocument.Save(ms1);
  103. ms1.Position = 0;
  104. var doc = new PdfLoadedDocument(ms1);
  105. //SetoutDocument document = documents.FirstOrDefault(x => x.DocumentLink.ID.Equals(documentid));
  106. if (_document != null)
  107. {
  108. var annotations = new Client<EntityDocumentAnnotation>()
  109. .Load(new Filter<EntityDocumentAnnotation>(x => x.EntityDocument).IsEqualTo(_document.ID)).ToList();
  110. for (var i = 0; i < doc.Pages.Count; i++)
  111. {
  112. var page = doc.Pages[i] as PdfLoadedPage;
  113. foreach (PdfLoadedAnnotation a in page.Annotations)
  114. {
  115. var a_id = Guid.Empty;
  116. if (!string.IsNullOrWhiteSpace(a.Author))
  117. Guid.TryParse(a.Author, out a_id);
  118. if (currentAnnotations.Contains(a_id))
  119. currentAnnotations.Remove(a_id);
  120. var annotation = a_id.Equals(Guid.Empty) ? null : annotations.FirstOrDefault(x => x.ID.Equals(a_id));
  121. if (annotation == null)
  122. {
  123. annotation = new EntityDocumentAnnotation { EntityDocument = _document.ID };
  124. annotations.Add(annotation);
  125. }
  126. annotation.Page = i;
  127. annotation.Type = GetAnnotationType(a);
  128. annotation.Data = SaveAnnotation(doc, a);
  129. }
  130. }
  131. new Client<EntityDocumentAnnotation>().Save(annotations.Where(x => x.IsChanged()), "");
  132. foreach (var annotation in annotations.Where(x => currentAnnotations.Contains(x.ID)))
  133. new Client<EntityDocumentAnnotation>().Delete(annotation, "");
  134. }
  135. }
  136. }
  137. catch (Exception e)
  138. {
  139. MessageBox.Show("Unable to Save Annotations: " + e.Message + "\n" + e.StackTrace);
  140. }
  141. }
  142. public EntityDocumentAnnotationType GetAnnotationType(PdfAnnotation annotation)
  143. {
  144. if (annotation is PdfLoadedLineAnnotation)
  145. return EntityDocumentAnnotationType.Line;
  146. if (annotation is PdfLoadedEllipseAnnotation)
  147. return EntityDocumentAnnotationType.Ellipse;
  148. if (annotation is PdfLoadedRectangleAnnotation)
  149. return EntityDocumentAnnotationType.Rectangle;
  150. if (annotation is PdfLoadedSquareAnnotation)
  151. return EntityDocumentAnnotationType.Rectangle;
  152. if (annotation is PdfLoadedFreeTextAnnotation)
  153. return EntityDocumentAnnotationType.Text;
  154. if (annotation is PdfLoadedInkAnnotation)
  155. return EntityDocumentAnnotationType.Ink;
  156. if (annotation is PdfLoadedRubberStampAnnotation)
  157. {
  158. if (!string.IsNullOrWhiteSpace(annotation.Subject))
  159. {
  160. if (annotation.Subject.Equals("Warning"))
  161. return EntityDocumentAnnotationType.WarningStamp;
  162. if (annotation.Subject.Equals("Error"))
  163. return EntityDocumentAnnotationType.ErrorStamp;
  164. }
  165. return EntityDocumentAnnotationType.OKStamp;
  166. }
  167. throw new Exception("Unknown Annotation: " + annotation.GetType().Name);
  168. }
  169. public string SaveAnnotation(PdfLoadedDocument doc, PdfLoadedAnnotation annotation)
  170. {
  171. annotation.Author = CoreUtils.FullGuid.ToString();
  172. var ms = new MemoryStream();
  173. var collection = new PdfExportAnnotationCollection();
  174. collection.Add(annotation);
  175. doc.ExportAnnotations(ms, AnnotationDataFormat.XFdf, collection);
  176. var result = Encoding.UTF8.GetString(ms.GetBuffer());
  177. return result;
  178. }
  179. public void LoadAnnotation(PdfLoadedDocument doc, string encoded, Guid id)
  180. {
  181. //PdfLoadedAnnotation annot = new PdfLoadedAnnotation();
  182. var data = encoded.Replace(CoreUtils.FullGuid.ToString(), id.ToString());
  183. var buffer = Encoding.UTF8.GetBytes(data);
  184. var ms = new MemoryStream(buffer);
  185. doc.ImportAnnotations(ms, AnnotationDataFormat.XFdf);
  186. }
  187. private void UnloadPDF()
  188. {
  189. if (_document != null)
  190. try
  191. {
  192. UnloadPDFAnnotations();
  193. PdfViewer.Unload(true);
  194. }
  195. catch (Exception e)
  196. {
  197. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  198. }
  199. }
  200. #endregion
  201. #region Reload / Preprocess PDF Document
  202. private bool DownloadNeeded(Guid id)
  203. {
  204. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", id.ToString()));
  205. if (!File.Exists(cachefile))
  206. return true;
  207. var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
  208. if (!File.Exists(indexfile))
  209. return true;
  210. var json = File.ReadAllText(indexfile);
  211. var index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
  212. if (!index.ContainsKey(id))
  213. return true;
  214. var entry = new Client<Document>().Query(
  215. new Filter<Document>(x => x.ID).IsEqualTo(id),
  216. new Columns<Document>(x => x.CRC)
  217. ).Rows.FirstOrDefault();
  218. if (entry == null)
  219. return true;
  220. if (!String.Equals(entry.Get<Document, string>(x => x.CRC),index[id]))
  221. {
  222. Dispatcher.BeginInvoke(() =>
  223. {
  224. MessageBox.Show("This PDF has been revised, and will now refresh.\n\nPlease check the drawing for any applicable changes.");
  225. });
  226. return true;
  227. }
  228. return false;
  229. }
  230. private bool AnnotationError;
  231. private void LoadPDF()
  232. {
  233. if (_document == null)
  234. return;
  235. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));
  236. using (new WaitCursor())
  237. {
  238. if (DownloadNeeded(_document.DocumentLink.ID))
  239. {
  240. CoreTable table = new Client<Document>().Query(new Filter<Document>(x => x.ID).IsEqualTo(_document.DocumentLink.ID));
  241. if (!table.Rows.Any())
  242. {
  243. MessageBox.Show("Unable to Load File!");
  244. return;
  245. }
  246. var dbdoc = table.Rows.FirstOrDefault().ToObject<Document>();
  247. var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
  248. var index = new Dictionary<Guid, string>();
  249. if (File.Exists(indexfile))
  250. {
  251. var json = File.ReadAllText(indexfile);
  252. index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
  253. }
  254. index[_document.DocumentLink.ID] = dbdoc.CRC;
  255. File.WriteAllText(indexfile, Serialization.Serialize(index));
  256. AnnotationError = false;
  257. pdfdocument = dbdoc.Data;
  258. try
  259. {
  260. pdfdocument = GhostScriptIt(pdfdocument);
  261. }
  262. catch (Exception eGhostscript)
  263. {
  264. Logger.Send(LogType.Information, "", "Ghostscript: " + eGhostscript.Message + "\n" + eGhostscript.StackTrace);
  265. }
  266. try
  267. {
  268. pdfdocument = FlattenPdf(pdfdocument);
  269. }
  270. catch (Exception eFlatten)
  271. {
  272. Logger.Send(LogType.Error, "", "Flatten Error: " + eFlatten.Message + "\n" + eFlatten.StackTrace);
  273. }
  274. try
  275. {
  276. if (AnnotationError)
  277. pdfdocument = RasterizePDF(pdfdocument);
  278. }
  279. catch (Exception eRasterize)
  280. {
  281. Logger.Send(LogType.Error, "", "Rasterize Error: " + eRasterize.Message + "\n" + eRasterize.StackTrace);
  282. }
  283. File.WriteAllBytes(cachefile, pdfdocument);
  284. }
  285. else
  286. {
  287. pdfdocument = File.ReadAllBytes(cachefile);
  288. }
  289. var doc = new PdfLoadedDocument(pdfdocument);
  290. currentAnnotations.Clear();
  291. var watermark = !_document.Superceded.IsEmpty() ? "SUPERCEDED" : Watermark;
  292. if (!string.IsNullOrWhiteSpace(watermark))
  293. foreach (PdfPageBase page in doc.Pages)
  294. {
  295. var rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  296. var graphics = page.Graphics;
  297. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10, PdfFontStyle.Bold);
  298. var state = graphics.Save();
  299. graphics.SetTransparency(0.2f);
  300. var format = new PdfStringFormat();
  301. format.Alignment = PdfTextAlignment.Center;
  302. format.LineAlignment = PdfVerticalAlignment.Middle;
  303. var lineheight = (int)Math.Round(font.Height * 2.5);
  304. var lines = new List<string>();
  305. while (lines.Count * lineheight < page.Size.Height)
  306. lines.Add(watermark);
  307. graphics.DrawString(string.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  308. }
  309. //foreach (PdfPageBase page in doc.Pages)
  310. //{
  311. // RectangleF rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  312. // PdfGraphics graphics = page.Graphics;
  313. // PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10, PdfFontStyle.Bold);
  314. // PdfGraphicsState state = graphics.Save();
  315. // graphics.SetTransparency(0.2f);
  316. // PdfStringFormat format = new PdfStringFormat();
  317. // format.Alignment = PdfTextAlignment.Center;
  318. // format.LineAlignment = PdfVerticalAlignment.Middle;
  319. // int lineheight = (int)Math.Round(font.Height * 2.5);
  320. // List<String> lines = new List<string>();
  321. // while (lines.Count * lineheight < page.Size.Height)
  322. // lines.Add("SUPERCEDED");
  323. // graphics.DrawString(String.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  324. //}
  325. var annotations = new Client<EntityDocumentAnnotation>()
  326. .Load(new Filter<EntityDocumentAnnotation>(x => x.EntityDocument).IsEqualTo(_document.ID)).ToList();
  327. foreach (var annotation in annotations)
  328. try
  329. {
  330. currentAnnotations.Add(annotation.ID);
  331. if (!string.IsNullOrWhiteSpace(annotation.Data))
  332. {
  333. if (annotation.Data.Contains("<freetext") && !annotation.Data.Contains("date=\""))
  334. {
  335. Logger.Send(LogType.Information, ClientFactory.UserID,
  336. string.Format("Annotation #{0} has no date - inserting now..", annotation.ID));
  337. annotation.Data = annotation.Data.Replace("<freetext",
  338. string.Format("<freetext date=\"D:{0:yyyyMMddHHmmss}+08\'00\'\"", DateTime.Now));
  339. //annotation.Data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\">\r\n <annots>\r\n <freetext page=\"0\" rect=\"635.782,231.8206,812.7407,282.311\" rotation=\"0\" color=\"#FFFFFF\" title=\"ffffffff-ffff-ffff-ffff-ffffffffffff\" subject=\"Free Text\" date=\"D:20220715001146+08'00'\" name=\"800eae13-14f4-4db9-a60e-6d5d2d2adb55\" fringe=\"0,0,0,0\" border=\"0,0,1\" q=\"0\" IT=\"FreeTextCallout\" head=\"None\">\r\n <defaultappearance>0.2901961 0.5647059 0.8862745 rg </defaultappearance>\r\n <defaultstyle>font:Arial 8pt;style:Regular;color:#FF0000</defaultstyle>\r\n <contents-richtext><body xmlns=\"http://www.w3.org/1999/xhtml\"><p dir=\"ltr\">MC'd by BW\r\nTrolley H18\r\n8 July 2022\r\nNOTE: 3032 Doorleaf is also on Trolley H18</p></body></contents-richtext>\r\n <contents>MC'd by BW\r\nTrolley H18\r\n8 July 2022\r\nNOTE: 3032 Doorleaf is also on Trolley H18</contents>\r\n </freetext>\r\n </annots>\r\n <f href=\"\" />\r\n</xfdf>";
  340. //annotation.Data = "<?xml version =\"1.0\" encoding=\"utf-8\"?>\r\n<xfdf xmlns=\"http://ns.adobe.com/xfdf/\" xml:space=\"preserve\">\r\n <annots>\r\n <freetext page=\"0\" rect=\"768.7103,558.5799,898.9603,642.3299\" rotation=\"0\" color=\"#FFFFFF\" title=\"ffffffff-ffff-ffff-ffff-ffffffffffff\" subject=\"Free Text\" date=\"D:20220715001146+08'00'\" flags=\"print\" name=\"690a16b1-647b-45a9-80a5-17f83f63bc93\" fringe=\"18,2,20,16.5\" border=\"0,0,1.5\" justification=\"0\" IT=\"FreeTextCallout\" head=\"OpenArrow\" callout=\"786.7103,625.8299,768.7103,593.2049,786.7103,593.2049\">\r\n <defaultappearance>0.2901961 0.5647059 0.8862745 rg </defaultappearance>\r\n <defaultstyle>font:Arial 12pt;style:Regular;color:#FF0000</defaultstyle>\r\n <contents-richtext><body xmlns=\"http://www.w3.org/1999/xhtml\"><p dir=\"ltr\">Hi Thjere\r\n\r\nawd.flae\r\nsdfgljsdlkfg</p></body></contents-richtext>\r\n <contents>Hi Thjere\r\n\r\nawd.flae\r\nsdfgljsdlkfg</contents>\r\n </freetext>\r\n </annots>\r\n <f href=\"\" />\r\n</xfdf>";
  341. }
  342. LoadAnnotation(doc, annotation.Data.Replace("&", "+"), annotation.ID);
  343. }
  344. }
  345. catch (Exception e)
  346. {
  347. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  348. }
  349. var ms = new MemoryStream();
  350. doc.Save(ms);
  351. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  352. PdfViewer.Load(ms);
  353. UpdateButtons(PdfNoneImage);
  354. CurrentAnnotations = AnnotationsToString();
  355. }
  356. }
  357. private byte[] GhostScriptIt(byte[] data)
  358. {
  359. var input = Path.GetTempFileName();
  360. File.WriteAllBytes(input, data);
  361. byte[] result = { };
  362. var gv = new GhostscriptVersionInfo(
  363. new Version(0, 0, 0),
  364. "gsdll64.dll",
  365. "",
  366. GhostscriptLicense.GPL
  367. );
  368. var gsPipedOutput = new GhostscriptPipedOutput();
  369. // pipe handle format: %handle%hexvalue
  370. var outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
  371. using (var processor = new GhostscriptProcessor(gv, true))
  372. {
  373. var switches = new List<string>();
  374. switches.Add("-empty");
  375. switches.Add("-dQUIET");
  376. switches.Add("-dSAFER");
  377. switches.Add("-dBATCH");
  378. switches.Add("-dNOPAUSE");
  379. switches.Add("-dNOPROMPT");
  380. switches.Add("-dCompatibilityLevel=1.4");
  381. switches.Add("-dPreserveAnnots=false");
  382. switches.Add("-sDEVICE=pdfwrite");
  383. switches.Add("-o" + outputPipeHandle);
  384. switches.Add("-q");
  385. switches.Add("-f");
  386. switches.Add(input);
  387. try
  388. {
  389. processor.StartProcessing(switches.ToArray(), null);
  390. result = gsPipedOutput.Data;
  391. }
  392. catch (Exception ex)
  393. {
  394. Console.WriteLine(ex.Message);
  395. }
  396. finally
  397. {
  398. gsPipedOutput.Dispose();
  399. gsPipedOutput = null;
  400. }
  401. }
  402. File.Delete(input);
  403. return result;
  404. }
  405. private byte[] RasterizePDF(byte[] data)
  406. {
  407. var source = PresentationSource.FromVisual(this);
  408. var dpiX = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M11 : 0.0F;
  409. var dpiY = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M22 : 0.0F;
  410. var gsdata = GhostScriptIt(data);
  411. var doc = new PdfLoadedDocument(gsdata);
  412. Bitmap[] bitmaps = doc.ExportAsImage(0, doc.Pages.Count - 1, (float)dpiX, (float)dpiY);
  413. PdfSection section = null;
  414. var pdf = new PdfDocument();
  415. pdf.PageSettings.Margins.All = 0;
  416. for (var i = 0; i < doc.Pages.Count; i++)
  417. {
  418. var oldpage = doc.Pages[i] as PdfLoadedPage;
  419. if (section == null || section.PageSettings.Size.Height != oldpage.Size.Height ||
  420. section.PageSettings.Size.Width != oldpage.Size.Width)
  421. {
  422. section = pdf.Sections.Add();
  423. section.PageSettings.Size = oldpage.Size;
  424. section.PageSettings.Orientation =
  425. oldpage.Size.Height > oldpage.Size.Width ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
  426. }
  427. var newpage = section.Pages.Add();
  428. var graphics = newpage.Graphics;
  429. var bitmap = new PdfBitmap(bitmaps[i]);
  430. graphics.DrawImage(bitmap, new RectangleF(0, 0, section.PageSettings.Size.Width, section.PageSettings.Size.Height));
  431. }
  432. var ms = new MemoryStream();
  433. pdf.Save(ms);
  434. return ms.GetBuffer();
  435. }
  436. private byte[] FlattenPdf(byte[] data)
  437. {
  438. var doc = new PdfLoadedDocument(data);
  439. foreach (PdfLoadedPage page in doc.Pages)
  440. try
  441. {
  442. foreach (PdfLoadedAnnotation annotation in page.Annotations) annotation.Flatten = true;
  443. }
  444. catch (Exception e)
  445. {
  446. AnnotationError = true;
  447. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("*** Unable to Flatten PDF ***\n{0}", e.Message));
  448. }
  449. var ms = new MemoryStream();
  450. doc.Save(ms);
  451. //doc.Save(filename);
  452. //return File.ReadAllBytes(filename);
  453. return ms.GetBuffer();
  454. }
  455. private void RefreshPDF_Click(object sender, RoutedEventArgs e)
  456. {
  457. UnloadPDF();
  458. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));
  459. if (File.Exists(cachefile))
  460. File.Delete(cachefile);
  461. LoadPDF();
  462. }
  463. #endregion
  464. #region PDF Editing
  465. private Bitmap SizeBitmap()
  466. {
  467. var b = new Bitmap(32, 32);
  468. using (var g = Graphics.FromImage(b))
  469. {
  470. g.SmoothingMode = SmoothingMode.AntiAlias;
  471. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  472. var text = TextSize.ToString();
  473. var font = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
  474. var size = g.MeasureString(text, font);
  475. var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
  476. g.DrawString(text, font, new SolidBrush(Color.DimGray), new RectangleF(4, 6, 24, 20), sf);
  477. var pen = new Pen(Color.DimGray, 2);
  478. g.DrawRectangle(pen, 4, 4, 24, 24);
  479. }
  480. return b;
  481. }
  482. private Bitmap ColorBitmap()
  483. {
  484. var b = new Bitmap(32, 32);
  485. using (var g = Graphics.FromImage(b))
  486. {
  487. g.SmoothingMode = SmoothingMode.AntiAlias;
  488. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  489. var color = ColorTranslator.FromHtml(LineColor);
  490. var brush = new SolidBrush(color);
  491. g.FillRectangle(brush, 4, 4, 24, 24);
  492. var pen = new Pen(Color.Black, 1);
  493. g.DrawRectangle(pen, 4, 4, 24, 24);
  494. }
  495. return b;
  496. }
  497. private void UpdateButtons(Image selected)
  498. {
  499. PDFButtonStack.Width = Document != null && Document.Superceded.IsEmpty() && ButtonsVisible
  500. ? new GridLength(44, GridUnitType.Pixel)
  501. : new GridLength(0, GridUnitType.Pixel);
  502. PdfColorImage.Source = ColorBitmap().AsBitmapImage(32, 32, false);
  503. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(32, 32, false);
  504. PdfPrint.Visibility = Visibility.Collapsed; //PrintAllowed ? Visibility.Visible : Visibility.Collapsed;
  505. PdfSave.Visibility = SaveAllowed ? Visibility.Visible : Visibility.Collapsed;
  506. ColorButton(PdfNoneImage, selected,Wpf.Resources.hand);
  507. ColorButton(PdfInkImage, selected,Wpf.Resources.draw);
  508. ColorButton(PdfLineImage, selected,Wpf.Resources.line);
  509. ColorButton(PdfRectangleImage, selected,Wpf.Resources.square);
  510. ColorButton(PdfCircleImage, selected,Wpf.Resources.circle);
  511. ColorButton(PdfFreeTextImage, selected,Wpf.Resources.text);
  512. ColorButton(PdfOKImage, selected,Wpf.Resources.tick);
  513. ColorButton(PdfWarningImage, selected,Wpf.Resources.warning);
  514. ColorButton(PdfErrorImage, selected,Wpf.Resources.delete);
  515. }
  516. private void ColorButton(Image button, Image selected, Bitmap bitmap)
  517. {
  518. button.Source = selected == button
  519. ? bitmap.ChangeColor(Color.White, Color.Yellow).AsBitmapImage(32, 32, false)
  520. : bitmap.AsBitmapImage(32, 32, false);
  521. }
  522. private void PdfPrint_Click(object sender, RoutedEventArgs e)
  523. {
  524. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  525. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  526. UpdateButtons(PdfNoneImage);
  527. PdfViewer.PrinterSettings.ShowPrintStatusDialog = true;
  528. PdfViewer.PrinterSettings.PageSize = PdfViewerPrintSize.Fit;
  529. //String printer = "";
  530. //if (PrinterSelection.Execute(ref printer))
  531. // PdfViewer.Print(printer);
  532. //PdfViewer.PrintCommand.Execute(PdfViewer);
  533. PrintDialog dialog = new PrintDialog();
  534. if (dialog.ShowDialog() == true)
  535. dialog.PrintDocument(PdfViewer.PrintDocument.DocumentPaginator, "PRS Factory Floor Printout");
  536. //var ms = new MemoryStream();
  537. //PdfViewer.LoadedDocument.Save(ms);
  538. //PdfViewer.Print();
  539. //byte[] data = ms.GetBuffer();
  540. //data = FlattenPdf(data);
  541. //String filename = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "pdf");
  542. //File.WriteAllBytes(filename, data);
  543. ////PdfViewer.Save(filename);
  544. //PDFPreview preview = new PDFPreview(filename);
  545. //preview.ShowDialog();
  546. }
  547. private void PdfSave_Click(object sender, RoutedEventArgs e)
  548. {
  549. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  550. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  551. UpdateButtons(PdfNoneImage);
  552. var dlg = new SaveFileDialog();
  553. dlg.Filter = "PDF Files (*.pdf)|*.pdf";
  554. dlg.FileName = Path.ChangeExtension(Document.DocumentLink.FileName, ".pdf");
  555. if (dlg.ShowDialog() == true)
  556. {
  557. var ms = new MemoryStream();
  558. PdfViewer.LoadedDocument.Save(ms);
  559. var data = ms.GetBuffer();
  560. data = FlattenPdf(data);
  561. var filename = dlg.FileName;
  562. File.WriteAllBytes(filename, data);
  563. var gsProcessInfo = new ProcessStartInfo();
  564. gsProcessInfo.Verb = "open";
  565. gsProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
  566. gsProcessInfo.FileName = filename;
  567. gsProcessInfo.UseShellExecute = true;
  568. Process.Start(gsProcessInfo);
  569. }
  570. }
  571. private void PdfZoomIn_Click(object sender, RoutedEventArgs e)
  572. {
  573. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  574. ;
  575. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  576. UpdateButtons(PdfNoneImage);
  577. PdfViewer.IncreaseZoomCommand.Execute(null);
  578. }
  579. private void PdfZoomWidth_Click(object sender, RoutedEventArgs e)
  580. {
  581. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  582. ;
  583. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  584. UpdateButtons(PdfNoneImage);
  585. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  586. }
  587. private void PdfZoomPage_Click(object sender, RoutedEventArgs e)
  588. {
  589. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  590. ;
  591. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  592. UpdateButtons(PdfNoneImage);
  593. PdfViewer.ZoomMode = ZoomMode.FitPage;
  594. }
  595. private void PdfZoomOut_Click(object sender, RoutedEventArgs e)
  596. {
  597. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  598. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  599. UpdateButtons(PdfNoneImage);
  600. PdfViewer.DecreaseZoomCommand.Execute(null);
  601. }
  602. private void PdfColor_Click(object sender, RoutedEventArgs e)
  603. {
  604. var color = ColorTranslator.FromHtml(LineColor);
  605. if (ColorEdit.Execute("Edit Color", ref color))
  606. {
  607. LineColor = ColorTranslator.ToHtml(color);
  608. PdfColorImage.Source = ColorBitmap().AsBitmapImage(false);
  609. PDFSettingsChanged?.Invoke(this, LineColor, TextSize);
  610. }
  611. }
  612. private void PdfSize_Click(object sender, RoutedEventArgs e)
  613. {
  614. var size = TextSize;
  615. if (NumberEdit.Execute("Edit Font Size", 4, 96, ref size))
  616. {
  617. TextSize = size;
  618. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(false);
  619. }
  620. }
  621. private void PdfNone_Click(object sender, RoutedEventArgs e)
  622. {
  623. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  624. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  625. UpdateButtons(PdfNoneImage);
  626. }
  627. private void PdfInk_Click(object sender, RoutedEventArgs e)
  628. {
  629. PdfViewer.InkAnnotationSettings.InkColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  630. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  631. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Ink;
  632. UpdateButtons(PdfInkImage);
  633. }
  634. private void PdfLine_Click(object sender, RoutedEventArgs e)
  635. {
  636. if(LineColor is null)
  637. {
  638. return;
  639. }
  640. PdfViewer.LineAnnotationSettings.LineColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  641. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  642. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Line;
  643. UpdateButtons(PdfLineImage);
  644. }
  645. private void PdfRectangle_Click(object sender, RoutedEventArgs e)
  646. {
  647. PdfViewer.RectangleAnnotationSettings.RectangleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  648. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  649. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Rectangle;
  650. UpdateButtons(PdfRectangleImage);
  651. }
  652. private void PdfCircle_Click(object sender, RoutedEventArgs e)
  653. {
  654. PdfViewer.CircleAnnotationSettings.CircleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  655. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  656. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Circle;
  657. UpdateButtons(PdfCircleImage);
  658. }
  659. private void PdfFreeText_Click(object sender, RoutedEventArgs e)
  660. {
  661. PdfViewer.FreeTextAnnotationSettings.FontSize = TextSize;
  662. PdfViewer.FreeTextAnnotationSettings.FontColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  663. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  664. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.FreeText;
  665. UpdateButtons(PdfFreeTextImage);
  666. }
  667. private void PdfOKStamp_Click(object sender, RoutedEventArgs e)
  668. {
  669. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  670. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  671. //AnnotationType = EntityDocumentAnnotationType.OKStamp;
  672. //UpdateButtons(PdfOKImage);
  673. }
  674. private void PdfWarningStamp_Click(object sender, RoutedEventArgs e)
  675. {
  676. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  677. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  678. //AnnotationType = EntityDocumentAnnotationType.WarningStamp;
  679. //UpdateButtons(PdfWarningImage);
  680. }
  681. private void PdfErrorStamp_Click(object sender, RoutedEventArgs e)
  682. {
  683. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  684. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  685. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  686. //AnnotationType = EntityDocumentAnnotationType.ErrorStamp;
  687. //UpdateButtons(PdfErrorImage);
  688. }
  689. private EntityDocumentAnnotationType AnnotationType = EntityDocumentAnnotationType.OKStamp;
  690. #endregion
  691. }
  692. }