PDFEditorControl.xaml.cs 36 KB

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