PDFEditorControl.xaml.cs 34 KB

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