PDFEditorControl.xaml.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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 PdfLoadedPopupAnnotation)
  157. return EntityDocumentAnnotationType.Popup;
  158. if (annotation is PdfLoadedRubberStampAnnotation)
  159. {
  160. if (!string.IsNullOrWhiteSpace(annotation.Subject))
  161. {
  162. if (annotation.Subject.Equals("Warning"))
  163. return EntityDocumentAnnotationType.WarningStamp;
  164. if (annotation.Subject.Equals("Error"))
  165. return EntityDocumentAnnotationType.ErrorStamp;
  166. }
  167. return EntityDocumentAnnotationType.OKStamp;
  168. }
  169. throw new Exception("Unknown Annotation: " + annotation.GetType().Name);
  170. }
  171. public string SaveAnnotation(PdfLoadedDocument doc, PdfLoadedAnnotation annotation)
  172. {
  173. annotation.Author = CoreUtils.FullGuid.ToString();
  174. var ms = new MemoryStream();
  175. var collection = new PdfExportAnnotationCollection();
  176. collection.Add(annotation);
  177. doc.ExportAnnotations(ms, AnnotationDataFormat.XFdf, collection);
  178. var result = Encoding.UTF8.GetString(ms.GetBuffer());
  179. return result;
  180. }
  181. public void LoadAnnotation(PdfLoadedDocument doc, string encoded, Guid id)
  182. {
  183. //PdfLoadedAnnotation annot = new PdfLoadedAnnotation();
  184. var data = encoded.Replace(CoreUtils.FullGuid.ToString(), id.ToString());
  185. var buffer = Encoding.UTF8.GetBytes(data);
  186. var ms = new MemoryStream(buffer);
  187. doc.ImportAnnotations(ms, AnnotationDataFormat.XFdf);
  188. }
  189. private void UnloadPDF()
  190. {
  191. if (_document != null)
  192. try
  193. {
  194. UnloadPDFAnnotations();
  195. PdfViewer.Unload(true);
  196. }
  197. catch (Exception e)
  198. {
  199. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  200. }
  201. }
  202. #endregion
  203. #region Reload / Preprocess PDF Document
  204. private bool DownloadNeeded(Guid id)
  205. {
  206. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", id.ToString()));
  207. if (!File.Exists(cachefile))
  208. return true;
  209. var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
  210. if (!File.Exists(indexfile))
  211. return true;
  212. var json = File.ReadAllText(indexfile);
  213. var index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
  214. if (!index.ContainsKey(id))
  215. return true;
  216. var entry = new Client<Document>().Query(
  217. new Filter<Document>(x => x.ID).IsEqualTo(id),
  218. Columns.None<Document>().Add(x => x.CRC)
  219. ).Rows.FirstOrDefault();
  220. if (entry == null)
  221. return true;
  222. if (!String.Equals(entry.Get<Document, string>(x => x.CRC),index[id]))
  223. {
  224. Dispatcher.BeginInvoke(() =>
  225. {
  226. MessageBox.Show("This PDF has been revised, and will now refresh.\n\nPlease check the drawing for any applicable changes.");
  227. });
  228. return true;
  229. }
  230. return false;
  231. }
  232. private bool AnnotationError;
  233. private void LoadPDF()
  234. {
  235. if (_document == null)
  236. return;
  237. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));
  238. using (new WaitCursor())
  239. {
  240. if (DownloadNeeded(_document.DocumentLink.ID))
  241. {
  242. CoreTable table = new Client<Document>().Query(new Filter<Document>(x => x.ID).IsEqualTo(_document.DocumentLink.ID));
  243. if (!table.Rows.Any())
  244. {
  245. MessageBox.Show("Unable to Load File!");
  246. return;
  247. }
  248. var dbdoc = table.Rows.FirstOrDefault().ToObject<Document>();
  249. var indexfile = Path.Combine(CoreUtils.GetPath(), "pdfindex.json");
  250. var index = new Dictionary<Guid, string>();
  251. if (File.Exists(indexfile))
  252. {
  253. var json = File.ReadAllText(indexfile);
  254. index = Serialization.Deserialize<Dictionary<Guid, string>>(json);
  255. }
  256. index[_document.DocumentLink.ID] = dbdoc.CRC;
  257. File.WriteAllText(indexfile, Serialization.Serialize(index));
  258. AnnotationError = false;
  259. pdfdocument = dbdoc.Data;
  260. try
  261. {
  262. pdfdocument = GhostScriptIt(pdfdocument);
  263. }
  264. catch (Exception eGhostscript)
  265. {
  266. Logger.Send(LogType.Information, "", "Ghostscript: " + eGhostscript.Message + "\n" + eGhostscript.StackTrace);
  267. }
  268. try
  269. {
  270. pdfdocument = FlattenPdf(pdfdocument);
  271. }
  272. catch (Exception eFlatten)
  273. {
  274. Logger.Send(LogType.Error, "", "Flatten Error: " + eFlatten.Message + "\n" + eFlatten.StackTrace);
  275. }
  276. try
  277. {
  278. if (AnnotationError)
  279. pdfdocument = RasterizePDF(pdfdocument);
  280. }
  281. catch (Exception eRasterize)
  282. {
  283. Logger.Send(LogType.Error, "", "Rasterize Error: " + eRasterize.Message + "\n" + eRasterize.StackTrace);
  284. }
  285. File.WriteAllBytes(cachefile, pdfdocument);
  286. }
  287. else
  288. {
  289. pdfdocument = File.ReadAllBytes(cachefile);
  290. }
  291. if (pdfdocument.Any())
  292. {
  293. var doc = new PdfLoadedDocument(pdfdocument);
  294. currentAnnotations.Clear();
  295. var watermark = !_document.Superceded.IsEmpty() ? "SUPERCEDED" : Watermark;
  296. if (!string.IsNullOrWhiteSpace(watermark))
  297. foreach (PdfPageBase page in doc.Pages)
  298. {
  299. var rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  300. var graphics = page.Graphics;
  301. PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10,
  302. PdfFontStyle.Bold);
  303. var state = graphics.Save();
  304. graphics.SetTransparency(0.2f);
  305. var format = new PdfStringFormat();
  306. format.Alignment = PdfTextAlignment.Center;
  307. format.LineAlignment = PdfVerticalAlignment.Middle;
  308. var lineheight = (int)Math.Round(font.Height * 2.5);
  309. var lines = new List<string>();
  310. while (lines.Count * lineheight < page.Size.Height)
  311. lines.Add(watermark);
  312. graphics.DrawString(string.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  313. }
  314. //foreach (PdfPageBase page in doc.Pages)
  315. //{
  316. // RectangleF rect = new RectangleF(0, 0, page.Size.Width, page.Size.Height);
  317. // PdfGraphics graphics = page.Graphics;
  318. // PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, page.Size.Width / 10, PdfFontStyle.Bold);
  319. // PdfGraphicsState state = graphics.Save();
  320. // graphics.SetTransparency(0.2f);
  321. // PdfStringFormat format = new PdfStringFormat();
  322. // format.Alignment = PdfTextAlignment.Center;
  323. // format.LineAlignment = PdfVerticalAlignment.Middle;
  324. // int lineheight = (int)Math.Round(font.Height * 2.5);
  325. // List<String> lines = new List<string>();
  326. // while (lines.Count * lineheight < page.Size.Height)
  327. // lines.Add("SUPERCEDED");
  328. // graphics.DrawString(String.Join("\n\n", lines), font, PdfBrushes.Red, rect, format);
  329. //}
  330. var annotations = new Client<EntityDocumentAnnotation>()
  331. .Load(new Filter<EntityDocumentAnnotation>(x => x.EntityDocument).IsEqualTo(_document.ID))
  332. .ToList();
  333. foreach (var annotation in annotations)
  334. try
  335. {
  336. currentAnnotations.Add(annotation.ID);
  337. if (!string.IsNullOrWhiteSpace(annotation.Data))
  338. {
  339. if (annotation.Data.Contains("<freetext") && !annotation.Data.Contains("date=\""))
  340. {
  341. Logger.Send(LogType.Information, ClientFactory.UserID,
  342. string.Format("Annotation #{0} has no date - inserting now..", annotation.ID));
  343. annotation.Data = annotation.Data.Replace("<freetext",
  344. string.Format("<freetext date=\"D:{0:yyyyMMddHHmmss}+08\'00\'\"",
  345. DateTime.Now));
  346. //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>";
  347. //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>";
  348. }
  349. LoadAnnotation(doc, annotation.Data.Replace("&", "+"), annotation.ID);
  350. }
  351. }
  352. catch (Exception e)
  353. {
  354. Logger.Send(LogType.Error, "",
  355. string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  356. }
  357. var ms = new MemoryStream();
  358. doc.Save(ms);
  359. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  360. PdfViewer.Load(ms);
  361. CurrentAnnotations = AnnotationsToString();
  362. }
  363. UpdateButtons(PdfNoneImage);
  364. }
  365. }
  366. private byte[] GhostScriptIt(byte[] data)
  367. {
  368. var input = Path.GetTempFileName();
  369. File.WriteAllBytes(input, data);
  370. byte[] result = { };
  371. var gv = new GhostscriptVersionInfo(
  372. new Version(0, 0, 0),
  373. "gsdll64.dll",
  374. "",
  375. GhostscriptLicense.GPL
  376. );
  377. var gsPipedOutput = new GhostscriptPipedOutput();
  378. // pipe handle format: %handle%hexvalue
  379. var outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
  380. using (var processor = new GhostscriptProcessor(gv, true))
  381. {
  382. var switches = new List<string>();
  383. switches.Add("-empty");
  384. switches.Add("-dQUIET");
  385. switches.Add("-dSAFER");
  386. switches.Add("-dBATCH");
  387. switches.Add("-dNOPAUSE");
  388. switches.Add("-dNOPROMPT");
  389. switches.Add("-dCompatibilityLevel=1.4");
  390. switches.Add("-dPreserveAnnots=false");
  391. switches.Add("-sDEVICE=pdfwrite");
  392. switches.Add("-o" + outputPipeHandle);
  393. switches.Add("-q");
  394. switches.Add("-f");
  395. switches.Add(input);
  396. try
  397. {
  398. processor.StartProcessing(switches.ToArray(), null);
  399. result = gsPipedOutput.Data;
  400. }
  401. catch (Exception ex)
  402. {
  403. Console.WriteLine(ex.Message);
  404. }
  405. finally
  406. {
  407. gsPipedOutput.Dispose();
  408. gsPipedOutput = null;
  409. }
  410. }
  411. File.Delete(input);
  412. return result;
  413. }
  414. private byte[] RasterizePDF(byte[] data)
  415. {
  416. var source = PresentationSource.FromVisual(this);
  417. var dpiX = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M11 : 0.0F;
  418. var dpiY = source != null ? 96.0 * source.CompositionTarget.TransformToDevice.M22 : 0.0F;
  419. var gsdata = GhostScriptIt(data);
  420. var doc = new PdfLoadedDocument(gsdata);
  421. Bitmap[] bitmaps = doc.ExportAsImage(0, doc.Pages.Count - 1, (float)dpiX, (float)dpiY);
  422. PdfSection section = null;
  423. var pdf = new PdfDocument();
  424. pdf.PageSettings.Margins.All = 0;
  425. for (var i = 0; i < doc.Pages.Count; i++)
  426. {
  427. var oldpage = doc.Pages[i] as PdfLoadedPage;
  428. if (section == null || section.PageSettings.Size.Height != oldpage.Size.Height ||
  429. section.PageSettings.Size.Width != oldpage.Size.Width)
  430. {
  431. section = pdf.Sections.Add();
  432. section.PageSettings.Size = oldpage.Size;
  433. section.PageSettings.Orientation =
  434. oldpage.Size.Height > oldpage.Size.Width ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
  435. }
  436. var newpage = section.Pages.Add();
  437. var graphics = newpage.Graphics;
  438. var bitmap = new PdfBitmap(bitmaps[i]);
  439. graphics.DrawImage(bitmap, new RectangleF(0, 0, section.PageSettings.Size.Width, section.PageSettings.Size.Height));
  440. }
  441. var ms = new MemoryStream();
  442. pdf.Save(ms);
  443. return ms.GetBuffer();
  444. }
  445. private byte[] FlattenPdf(byte[] data)
  446. {
  447. var doc = new PdfLoadedDocument(data);
  448. foreach (PdfLoadedPage page in doc.Pages)
  449. try
  450. {
  451. foreach (PdfLoadedAnnotation annotation in page.Annotations) annotation.Flatten = true;
  452. }
  453. catch (Exception e)
  454. {
  455. AnnotationError = true;
  456. Logger.Send(LogType.Error, ClientFactory.UserID, string.Format("*** Unable to Flatten PDF ***\n{0}", e.Message));
  457. }
  458. var ms = new MemoryStream();
  459. doc.Save(ms);
  460. //doc.Save(filename);
  461. //return File.ReadAllBytes(filename);
  462. return ms.GetBuffer();
  463. }
  464. private void RefreshPDF_Click(object sender, RoutedEventArgs e)
  465. {
  466. UnloadPDF();
  467. var cachefile = Path.Combine(CoreUtils.GetPath(), string.Format("{0}.ffd", _document.DocumentLink.ID.ToString()));
  468. if (File.Exists(cachefile))
  469. File.Delete(cachefile);
  470. LoadPDF();
  471. }
  472. #endregion
  473. #region PDF Editing
  474. private Bitmap SizeBitmap()
  475. {
  476. var b = new Bitmap(32, 32);
  477. using (var g = Graphics.FromImage(b))
  478. {
  479. g.SmoothingMode = SmoothingMode.AntiAlias;
  480. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  481. var text = TextSize.ToString();
  482. var font = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
  483. var size = g.MeasureString(text, font);
  484. var sf = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
  485. g.DrawString(text, font, new SolidBrush(Color.DimGray), new RectangleF(4, 6, 24, 20), sf);
  486. var pen = new Pen(Color.DimGray, 2);
  487. g.DrawRectangle(pen, 4, 4, 24, 24);
  488. }
  489. return b;
  490. }
  491. private Bitmap ColorBitmap()
  492. {
  493. var b = new Bitmap(32, 32);
  494. using (var g = Graphics.FromImage(b))
  495. {
  496. g.SmoothingMode = SmoothingMode.AntiAlias;
  497. g.FillRectangle(new SolidBrush(Color.White), 0, 0, 32, 32);
  498. var color = ColorTranslator.FromHtml(LineColor);
  499. var brush = new SolidBrush(color);
  500. g.FillRectangle(brush, 4, 4, 24, 24);
  501. var pen = new Pen(Color.Black, 1);
  502. g.DrawRectangle(pen, 4, 4, 24, 24);
  503. }
  504. return b;
  505. }
  506. private void UpdateButtons(Image selected)
  507. {
  508. PDFButtonStack.Width = Document != null && Document.Superceded.IsEmpty() && ButtonsVisible
  509. ? new GridLength(44, GridUnitType.Pixel)
  510. : new GridLength(0, GridUnitType.Pixel);
  511. PdfColorImage.Source = ColorBitmap().AsBitmapImage(32, 32, false);
  512. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(32, 32, false);
  513. PdfPrint.Visibility = Visibility.Collapsed; //PrintAllowed ? Visibility.Visible : Visibility.Collapsed;
  514. PdfSave.Visibility = SaveAllowed ? Visibility.Visible : Visibility.Collapsed;
  515. ColorButton(PdfNoneImage, selected,Wpf.Resources.hand);
  516. ColorButton(PdfInkImage, selected,Wpf.Resources.draw);
  517. ColorButton(PdfLineImage, selected,Wpf.Resources.line);
  518. ColorButton(PdfRectangleImage, selected,Wpf.Resources.square);
  519. ColorButton(PdfCircleImage, selected,Wpf.Resources.circle);
  520. ColorButton(PdfFreeTextImage, selected,Wpf.Resources.text);
  521. ColorButton(PdfOKImage, selected,Wpf.Resources.tick);
  522. ColorButton(PdfWarningImage, selected,Wpf.Resources.warning);
  523. ColorButton(PdfErrorImage, selected,Wpf.Resources.delete);
  524. }
  525. private void ColorButton(Image button, Image selected, Bitmap bitmap)
  526. {
  527. button.Source = selected == button
  528. ? bitmap.ChangeColor(Color.White, Color.Yellow).AsBitmapImage(32, 32, false)
  529. : bitmap.AsBitmapImage(32, 32, false);
  530. }
  531. private void PdfPrint_Click(object sender, RoutedEventArgs e)
  532. {
  533. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  534. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  535. UpdateButtons(PdfNoneImage);
  536. PdfViewer.PrinterSettings.ShowPrintStatusDialog = true;
  537. PdfViewer.PrinterSettings.PageSize = PdfViewerPrintSize.Fit;
  538. //String printer = "";
  539. //if (PrinterSelection.Execute(ref printer))
  540. // PdfViewer.Print(printer);
  541. //PdfViewer.PrintCommand.Execute(PdfViewer);
  542. PrintDialog dialog = new PrintDialog();
  543. if (dialog.ShowDialog() == true)
  544. dialog.PrintDocument(PdfViewer.PrintDocument.DocumentPaginator, "PRS Factory Floor Printout");
  545. //var ms = new MemoryStream();
  546. //PdfViewer.LoadedDocument.Save(ms);
  547. //PdfViewer.Print();
  548. //byte[] data = ms.GetBuffer();
  549. //data = FlattenPdf(data);
  550. //String filename = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(), "pdf");
  551. //File.WriteAllBytes(filename, data);
  552. ////PdfViewer.Save(filename);
  553. //PDFPreview preview = new PDFPreview(filename);
  554. //preview.ShowDialog();
  555. }
  556. private void PdfSave_Click(object sender, RoutedEventArgs e)
  557. {
  558. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  559. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  560. UpdateButtons(PdfNoneImage);
  561. var dlg = new SaveFileDialog();
  562. dlg.Filter = "PDF Files (*.pdf)|*.pdf";
  563. dlg.FileName = Path.ChangeExtension(Document.DocumentLink.FileName, ".pdf");
  564. if (dlg.ShowDialog() == true)
  565. {
  566. var ms = new MemoryStream();
  567. PdfViewer.LoadedDocument.Save(ms);
  568. var data = ms.GetBuffer();
  569. data = FlattenPdf(data);
  570. var filename = dlg.FileName;
  571. File.WriteAllBytes(filename, data);
  572. var gsProcessInfo = new ProcessStartInfo();
  573. gsProcessInfo.Verb = "open";
  574. gsProcessInfo.WindowStyle = ProcessWindowStyle.Normal;
  575. gsProcessInfo.FileName = filename;
  576. gsProcessInfo.UseShellExecute = true;
  577. Process.Start(gsProcessInfo);
  578. }
  579. }
  580. private void PdfZoomIn_Click(object sender, RoutedEventArgs e)
  581. {
  582. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  583. ;
  584. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  585. UpdateButtons(PdfNoneImage);
  586. PdfViewer.IncreaseZoomCommand.Execute(null);
  587. }
  588. private void PdfZoomWidth_Click(object sender, RoutedEventArgs e)
  589. {
  590. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  591. ;
  592. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  593. UpdateButtons(PdfNoneImage);
  594. PdfViewer.ZoomMode = ZoomMode.FitWidth;
  595. }
  596. private void PdfZoomPage_Click(object sender, RoutedEventArgs e)
  597. {
  598. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  599. ;
  600. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  601. UpdateButtons(PdfNoneImage);
  602. PdfViewer.ZoomMode = ZoomMode.FitPage;
  603. }
  604. private void PdfZoomOut_Click(object sender, RoutedEventArgs e)
  605. {
  606. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  607. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  608. UpdateButtons(PdfNoneImage);
  609. PdfViewer.DecreaseZoomCommand.Execute(null);
  610. }
  611. private void PdfColor_Click(object sender, RoutedEventArgs e)
  612. {
  613. var color = ColorTranslator.FromHtml(LineColor);
  614. if (ColorEdit.Execute("Edit Color", ref color))
  615. {
  616. LineColor = ColorTranslator.ToHtml(color);
  617. PdfColorImage.Source = ColorBitmap().AsBitmapImage(false);
  618. PDFSettingsChanged?.Invoke(this, LineColor, TextSize);
  619. }
  620. }
  621. private void PdfSize_Click(object sender, RoutedEventArgs e)
  622. {
  623. var size = TextSize;
  624. if (NumberEdit.Execute("Edit Font Size", 4, 96, ref size))
  625. {
  626. TextSize = size;
  627. PdfSizeImage.Source = SizeBitmap().AsBitmapImage(false);
  628. }
  629. }
  630. private void PdfNone_Click(object sender, RoutedEventArgs e)
  631. {
  632. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  633. PdfViewer.CursorMode = PdfViewerCursorMode.HandTool;
  634. UpdateButtons(PdfNoneImage);
  635. }
  636. private void PdfInk_Click(object sender, RoutedEventArgs e)
  637. {
  638. PdfViewer.InkAnnotationSettings.InkColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  639. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  640. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Ink;
  641. UpdateButtons(PdfInkImage);
  642. }
  643. private void PdfLine_Click(object sender, RoutedEventArgs e)
  644. {
  645. if(LineColor is null)
  646. {
  647. return;
  648. }
  649. PdfViewer.LineAnnotationSettings.LineColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  650. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  651. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Line;
  652. UpdateButtons(PdfLineImage);
  653. }
  654. private void PdfRectangle_Click(object sender, RoutedEventArgs e)
  655. {
  656. PdfViewer.RectangleAnnotationSettings.RectangleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  657. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  658. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Rectangle;
  659. UpdateButtons(PdfRectangleImage);
  660. }
  661. private void PdfCircle_Click(object sender, RoutedEventArgs e)
  662. {
  663. PdfViewer.CircleAnnotationSettings.CircleColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  664. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  665. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.Circle;
  666. UpdateButtons(PdfCircleImage);
  667. }
  668. private void PdfFreeText_Click(object sender, RoutedEventArgs e)
  669. {
  670. PdfViewer.FreeTextAnnotationSettings.FontSize = TextSize;
  671. PdfViewer.FreeTextAnnotationSettings.FontColor = (System.Windows.Media.Color)ColorConverter.ConvertFromString(LineColor);
  672. PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  673. PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.FreeText;
  674. UpdateButtons(PdfFreeTextImage);
  675. }
  676. private void PdfOKStamp_Click(object sender, RoutedEventArgs e)
  677. {
  678. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  679. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  680. //AnnotationType = EntityDocumentAnnotationType.OKStamp;
  681. //UpdateButtons(PdfOKImage);
  682. }
  683. private void PdfWarningStamp_Click(object sender, RoutedEventArgs e)
  684. {
  685. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  686. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  687. //AnnotationType = EntityDocumentAnnotationType.WarningStamp;
  688. //UpdateButtons(PdfWarningImage);
  689. }
  690. private void PdfErrorStamp_Click(object sender, RoutedEventArgs e)
  691. {
  692. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  693. //PdfViewer.AnnotationMode = PdfDocumentView.PdfViewerAnnotationMode.None;
  694. //PdfViewer.CursorMode = PdfViewerCursorMode.SelectTool;
  695. //AnnotationType = EntityDocumentAnnotationType.ErrorStamp;
  696. //UpdateButtons(PdfErrorImage);
  697. }
  698. private EntityDocumentAnnotationType AnnotationType = EntityDocumentAnnotationType.OKStamp;
  699. #endregion
  700. }
  701. }