PDFEditorControl.xaml.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. if (pdfdocument.Any())
  290. {
  291. var doc = new PdfLoadedDocument(pdfdocument);
  292. currentAnnotations.Clear();
  293. var watermark = !_document.Superceded.IsEmpty() ? "SUPERCEDED" : Watermark;
  294. if (!string.IsNullOrWhiteSpace(watermark))
  295. foreach (PdfPageBase page in doc.Pages)
  296. {
  297. var rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  298. var graphics = page.Graphics;
  299. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10,
  300. PdfFontStyle.Bold);
  301. var state = graphics.Save();
  302. graphics.SetTransparency(0.2f);
  303. var format = new PdfStringFormat();
  304. format.Alignment = PdfTextAlignment.Center;
  305. format.LineAlignment = PdfVerticalAlignment.Middle;
  306. var lineheight = (int)Math.Round(font.Height * 2.5);
  307. var lines = new List<string>();
  308. while (lines.Count * lineheight < page.Size.Height)
  309. lines.Add(watermark);
  310. graphics.DrawString(string.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  311. }
  312. //foreach (PdfPageBase page in doc.Pages)
  313. //{
  314. // RectangleF rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  315. // PdfGraphics graphics = page.Graphics;
  316. // PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10, PdfFontStyle.Bold);
  317. // PdfGraphicsState state = graphics.Save();
  318. // graphics.SetTransparency(0.2f);
  319. // PdfStringFormat format = new PdfStringFormat();
  320. // format.Alignment = PdfTextAlignment.Center;
  321. // format.LineAlignment = PdfVerticalAlignment.Middle;
  322. // int lineheight = (int)Math.Round(font.Height * 2.5);
  323. // List<String> lines = new List<string>();
  324. // while (lines.Count * lineheight < page.Size.Height)
  325. // lines.Add("SUPERCEDED");
  326. // graphics.DrawString(String.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  327. //}
  328. var annotations = new Client<EntityDocumentAnnotation>()
  329. .Load(new Filter<EntityDocumentAnnotation>(x => x.EntityDocument).IsEqualTo(_document.ID))
  330. .ToList();
  331. foreach (var annotation in annotations)
  332. try
  333. {
  334. currentAnnotations.Add(annotation.ID);
  335. if (!string.IsNullOrWhiteSpace(annotation.Data))
  336. {
  337. if (annotation.Data.Contains("<freetext") && !annotation.Data.Contains("date=\""))
  338. {
  339. Logger.Send(LogType.Information, ClientFactory.UserID,
  340. string.Format("Annotation #{0} has no date - inserting now..", annotation.ID));
  341. annotation.Data = annotation.Data.Replace("<freetext",
  342. string.Format("<freetext date=\"D:{0:yyyyMMddHHmmss}+08\'00\'\"",
  343. DateTime.Now));
  344. //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>";
  345. //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>";
  346. }
  347. LoadAnnotation(doc, annotation.Data.Replace("&", "+"), annotation.ID);
  348. }
  349. }
  350. catch (Exception e)
  351. {
  352. Logger.Send(LogType.Error, "",
  353. string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  354. }
  355. var ms = new MemoryStream();
  356. doc.Save(ms);
  357. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  358. PdfViewer.Load(ms);
  359. CurrentAnnotations = AnnotationsToString();
  360. }
  361. UpdateButtons(PdfNoneImage);
  362. }
  363. }
  364. private byte[] GhostScriptIt(byte[] data)
  365. {
  366. var input = Path.GetTempFileName();
  367. File.WriteAllBytes(input, data);
  368. byte[] result = { };
  369. var gv = new GhostscriptVersionInfo(
  370. new Version(0, 0, 0),
  371. "gsdll64.dll",
  372. "",
  373. GhostscriptLicense.GPL
  374. );
  375. var gsPipedOutput = new GhostscriptPipedOutput();
  376. // pipe handle format: %handle%hexvalue
  377. var outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
  378. using (var processor = new GhostscriptProcessor(gv, true))
  379. {
  380. var switches = new List<string>();
  381. switches.Add("-empty");
  382. switches.Add("-dQUIET");
  383. switches.Add("-dSAFER");
  384. switches.Add("-dBATCH");
  385. switches.Add("-dNOPAUSE");
  386. switches.Add("-dNOPROMPT");
  387. switches.Add("-dCompatibilityLevel=1.4");
  388. switches.Add("-dPreserveAnnots=false");
  389. switches.Add("-sDEVICE=pdfwrite");
  390. switches.Add("-o" + outputPipeHandle);
  391. switches.Add("-q");
  392. switches.Add("-f");
  393. switches.Add(input);
  394. try
  395. {
  396. processor.StartProcessing(switches.ToArray(), null);
  397. result = gsPipedOutput.Data;
  398. }
  399. catch (Exception ex)
  400. {
  401. Console.WriteLine(ex.Message);
  402. }
  403. finally
  404. {
  405. gsPipedOutput.Dispose();
  406. gsPipedOutput = null;
  407. }
  408. }
  409. File.Delete(input);
  410. return result;
  411. }
  412. private byte[] RasterizePDF(byte[] data)
  413. {
  414. var source = PresentationSource.FromVisual(this);
  415. var dpiX = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M11 : 0.0F;
  416. var dpiY = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M22 : 0.0F;
  417. var gsdata = GhostScriptIt(data);
  418. var doc = new PdfLoadedDocument(gsdata);
  419. Bitmap[] bitmaps = doc.ExportAsImage(0, doc.Pages.Count - 1, (float)dpiX, (float)dpiY);
  420. PdfSection section = null;
  421. var pdf = new PdfDocument();
  422. pdf.PageSettings.Margins.All = 0;
  423. for (var i = 0; i < doc.Pages.Count; i++)
  424. {
  425. var oldpage = doc.Pages[i] as PdfLoadedPage;
  426. if (section == null || section.PageSettings.Size.Height != oldpage.Size.Height ||
  427. section.PageSettings.Size.Width != oldpage.Size.Width)
  428. {
  429. section = pdf.Sections.Add();
  430. section.PageSettings.Size = oldpage.Size;
  431. section.PageSettings.Orientation =
  432. oldpage.Size.Height > oldpage.Size.Width ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
  433. }
  434. var newpage = section.Pages.Add();
  435. var graphics = newpage.Graphics;
  436. var bitmap = new PdfBitmap(bitmaps[i]);
  437. graphics.DrawImage(bitmap, new RectangleF(0, 0, section.PageSettings.Size.Width, section.PageSettings.Size.Height));
  438. }
  439. var ms = new MemoryStream();
  440. pdf.Save(ms);
  441. return ms.GetBuffer();
  442. }
  443. private byte[] FlattenPdf(byte[] data)
  444. {
  445. var doc = new PdfLoadedDocument(data);
  446. foreach (PdfLoadedPage page in doc.Pages)
  447. try
  448. {
  449. foreach (PdfLoadedAnnotation annotation in page.Annotations) annotation.Flatten = true;
  450. }
  451. catch (Exception e)
  452. {
  453. AnnotationError = true;
  454. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("*** Unable to Flatten PDF ***\n{0}", e.Message));
  455. }
  456. var ms = new MemoryStream();
  457. doc.Save(ms);
  458. //doc.Save(filename);
  459. //return File.ReadAllBytes(filename);
  460. return ms.GetBuffer();
  461. }
  462. private void RefreshPDF_Click(object sender, RoutedEventArgs e)
  463. {
  464. UnloadPDF();
  465. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));
  466. if (File.Exists(cachefile))
  467. File.Delete(cachefile);
  468. LoadPDF();
  469. }
  470. #endregion
  471. #region PDF Editing
  472. private Bitmap SizeBitmap()
  473. {
  474. var b = new Bitmap(32, 32);
  475. using (var g = Graphics.FromImage(b))
  476. {
  477. g.SmoothingMode = SmoothingMode.AntiAlias;
  478. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  479. var text = TextSize.ToString();
  480. var font = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
  481. var size = g.MeasureString(text, font);
  482. var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
  483. g.DrawString(text, font, new SolidBrush(Color.DimGray), new RectangleF(4, 6, 24, 20), sf);
  484. var pen = new Pen(Color.DimGray, 2);
  485. g.DrawRectangle(pen, 4, 4, 24, 24);
  486. }
  487. return b;
  488. }
  489. private Bitmap ColorBitmap()
  490. {
  491. var b = new Bitmap(32, 32);
  492. using (var g = Graphics.FromImage(b))
  493. {
  494. g.SmoothingMode = SmoothingMode.AntiAlias;
  495. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  496. var color = ColorTranslator.FromHtml(LineColor);
  497. var brush = new SolidBrush(color);
  498. g.FillRectangle(brush, 4, 4, 24, 24);
  499. var pen = new Pen(Color.Black, 1);
  500. g.DrawRectangle(pen, 4, 4, 24, 24);
  501. }
  502. return b;
  503. }
  504. private void UpdateButtons(Image selected)
  505. {
  506. PDFButtonStack.Width = Document != null && Document.Superceded.IsEmpty() && ButtonsVisible
  507. ? new GridLength(44, GridUnitType.Pixel)
  508. : new GridLength(0, GridUnitType.Pixel);
  509. PdfColorImage.Source = ColorBitmap().AsBitmapImage(32, 32, false);
  510. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(32, 32, false);
  511. PdfPrint.Visibility = Visibility.Collapsed; //PrintAllowed ? Visibility.Visible : Visibility.Collapsed;
  512. PdfSave.Visibility = SaveAllowed ? Visibility.Visible : Visibility.Collapsed;
  513. ColorButton(PdfNoneImage, selected,Wpf.Resources.hand);
  514. ColorButton(PdfInkImage, selected,Wpf.Resources.draw);
  515. ColorButton(PdfLineImage, selected,Wpf.Resources.line);
  516. ColorButton(PdfRectangleImage, selected,Wpf.Resources.square);
  517. ColorButton(PdfCircleImage, selected,Wpf.Resources.circle);
  518. ColorButton(PdfFreeTextImage, selected,Wpf.Resources.text);
  519. ColorButton(PdfOKImage, selected,Wpf.Resources.tick);
  520. ColorButton(PdfWarningImage, selected,Wpf.Resources.warning);
  521. ColorButton(PdfErrorImage, selected,Wpf.Resources.delete);
  522. }
  523. private void ColorButton(Image button, Image selected, Bitmap bitmap)
  524. {
  525. button.Source = selected == button
  526. ? bitmap.ChangeColor(Color.White, Color.Yellow).AsBitmapImage(32, 32, false)
  527. : bitmap.AsBitmapImage(32, 32, false);
  528. }
  529. private void PdfPrint_Click(object sender, RoutedEventArgs e)
  530. {
  531. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  532. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  533. UpdateButtons(PdfNoneImage);
  534. PdfViewer.PrinterSettings.ShowPrintStatusDialog = true;
  535. PdfViewer.PrinterSettings.PageSize = PdfViewerPrintSize.Fit;
  536. //String printer = "";
  537. //if (PrinterSelection.Execute(ref printer))
  538. // PdfViewer.Print(printer);
  539. //PdfViewer.PrintCommand.Execute(PdfViewer);
  540. PrintDialog dialog = new PrintDialog();
  541. if (dialog.ShowDialog() == true)
  542. dialog.PrintDocument(PdfViewer.PrintDocument.DocumentPaginator, "PRS Factory Floor Printout");
  543. //var ms = new MemoryStream();
  544. //PdfViewer.LoadedDocument.Save(ms);
  545. //PdfViewer.Print();
  546. //byte[] data = ms.GetBuffer();
  547. //data = FlattenPdf(data);
  548. //String filename = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "pdf");
  549. //File.WriteAllBytes(filename, data);
  550. ////PdfViewer.Save(filename);
  551. //PDFPreview preview = new PDFPreview(filename);
  552. //preview.ShowDialog();
  553. }
  554. private void PdfSave_Click(object sender, RoutedEventArgs e)
  555. {
  556. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  557. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  558. UpdateButtons(PdfNoneImage);
  559. var dlg = new SaveFileDialog();
  560. dlg.Filter = "PDF Files (*.pdf)|*.pdf";
  561. dlg.FileName = Path.ChangeExtension(Document.DocumentLink.FileName, ".pdf");
  562. if (dlg.ShowDialog() == true)
  563. {
  564. var ms = new MemoryStream();
  565. PdfViewer.LoadedDocument.Save(ms);
  566. var data = ms.GetBuffer();
  567. data = FlattenPdf(data);
  568. var filename = dlg.FileName;
  569. File.WriteAllBytes(filename, data);
  570. var gsProcessInfo = new ProcessStartInfo();
  571. gsProcessInfo.Verb = "open";
  572. gsProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
  573. gsProcessInfo.FileName = filename;
  574. gsProcessInfo.UseShellExecute = true;
  575. Process.Start(gsProcessInfo);
  576. }
  577. }
  578. private void PdfZoomIn_Click(object sender, RoutedEventArgs e)
  579. {
  580. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  581. ;
  582. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  583. UpdateButtons(PdfNoneImage);
  584. PdfViewer.IncreaseZoomCommand.Execute(null);
  585. }
  586. private void PdfZoomWidth_Click(object sender, RoutedEventArgs e)
  587. {
  588. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  589. ;
  590. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  591. UpdateButtons(PdfNoneImage);
  592. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  593. }
  594. private void PdfZoomPage_Click(object sender, RoutedEventArgs e)
  595. {
  596. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  597. ;
  598. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  599. UpdateButtons(PdfNoneImage);
  600. PdfViewer.ZoomMode = ZoomMode.FitPage;
  601. }
  602. private void PdfZoomOut_Click(object sender, RoutedEventArgs e)
  603. {
  604. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  605. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  606. UpdateButtons(PdfNoneImage);
  607. PdfViewer.DecreaseZoomCommand.Execute(null);
  608. }
  609. private void PdfColor_Click(object sender, RoutedEventArgs e)
  610. {
  611. var color = ColorTranslator.FromHtml(LineColor);
  612. if (ColorEdit.Execute("Edit Color", ref color))
  613. {
  614. LineColor = ColorTranslator.ToHtml(color);
  615. PdfColorImage.Source = ColorBitmap().AsBitmapImage(false);
  616. PDFSettingsChanged?.Invoke(this, LineColor, TextSize);
  617. }
  618. }
  619. private void PdfSize_Click(object sender, RoutedEventArgs e)
  620. {
  621. var size = TextSize;
  622. if (NumberEdit.Execute("Edit Font Size", 4, 96, ref size))
  623. {
  624. TextSize = size;
  625. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(false);
  626. }
  627. }
  628. private void PdfNone_Click(object sender, RoutedEventArgs e)
  629. {
  630. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  631. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  632. UpdateButtons(PdfNoneImage);
  633. }
  634. private void PdfInk_Click(object sender, RoutedEventArgs e)
  635. {
  636. PdfViewer.InkAnnotationSettings.InkColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  637. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  638. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Ink;
  639. UpdateButtons(PdfInkImage);
  640. }
  641. private void PdfLine_Click(object sender, RoutedEventArgs e)
  642. {
  643. if(LineColor is null)
  644. {
  645. return;
  646. }
  647. PdfViewer.LineAnnotationSettings.LineColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  648. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  649. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Line;
  650. UpdateButtons(PdfLineImage);
  651. }
  652. private void PdfRectangle_Click(object sender, RoutedEventArgs e)
  653. {
  654. PdfViewer.RectangleAnnotationSettings.RectangleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  655. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  656. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Rectangle;
  657. UpdateButtons(PdfRectangleImage);
  658. }
  659. private void PdfCircle_Click(object sender, RoutedEventArgs e)
  660. {
  661. PdfViewer.CircleAnnotationSettings.CircleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  662. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  663. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Circle;
  664. UpdateButtons(PdfCircleImage);
  665. }
  666. private void PdfFreeText_Click(object sender, RoutedEventArgs e)
  667. {
  668. PdfViewer.FreeTextAnnotationSettings.FontSize = TextSize;
  669. PdfViewer.FreeTextAnnotationSettings.FontColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  670. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  671. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.FreeText;
  672. UpdateButtons(PdfFreeTextImage);
  673. }
  674. private void PdfOKStamp_Click(object sender, RoutedEventArgs e)
  675. {
  676. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  677. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  678. //AnnotationType = EntityDocumentAnnotationType.OKStamp;
  679. //UpdateButtons(PdfOKImage);
  680. }
  681. private void PdfWarningStamp_Click(object sender, RoutedEventArgs e)
  682. {
  683. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  684. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  685. //AnnotationType = EntityDocumentAnnotationType.WarningStamp;
  686. //UpdateButtons(PdfWarningImage);
  687. }
  688. private void PdfErrorStamp_Click(object sender, RoutedEventArgs e)
  689. {
  690. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  691. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  692. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  693. //AnnotationType = EntityDocumentAnnotationType.ErrorStamp;
  694. //UpdateButtons(PdfErrorImage);
  695. }
  696. private EntityDocumentAnnotationType AnnotationType = EntityDocumentAnnotationType.OKStamp;
  697. #endregion
  698. }
  699. }