PDFEditorControl.xaml.cs 35 KB

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