JavaScriptAction.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using GrapeCity.Documents.Pdf;
  9. using GrapeCity.Documents.Text;
  10. using GrapeCity.Documents.Drawing;
  11. using GrapeCity.Documents.Pdf.Annotations;
  12. using GrapeCity.Documents.Pdf.Actions;
  13.  
  14. namespace DsPdfWeb.Demos.Basics
  15. {
  16. // Shows how to associate a PDF action with a JavaScript script.
  17. // In this example the script is associated with a link on a page.
  18. // Note that JavaScript may not work in some PDF viewers (e.g. built-in browser viewers).
  19. // See JavaScript for Acrobat for details.
  20. public class JavaScriptAction
  21. {
  22. const string js =
  23. "var cChoice = app.popUpMenu(\"Introduction\", \" - \", \"Chapter 1\",\r\n" +
  24. "[ \"Chapter 2\", \"Chapter 2 Start\", \"Chapter 2 Middle\",\r\n" +
  25. "[\"Chapter 2 End\", \"The End\"]]);\r\n" +
  26. "app.alert(\"You chose the '\" + cChoice + \"' menu item\");";
  27.  
  28. public int CreatePDF(Stream stream)
  29. {
  30. var doc = new GcPdfDocument();
  31. var g = doc.NewPage().Graphics;
  32. var jsAction = new ActionJavaScript(js);
  33. var tf = new TextFormat()
  34. {
  35. Font = StandardFonts.Times,
  36. FontSize = 14
  37. };
  38. // Draw the link string in a rectangle:
  39. var text = "Click this to show the popup menu.";
  40. var rect = new RectangleF(new PointF(72, 72), g.MeasureString(text, tf));
  41. g.FillRectangle(rect, Color.LightGoldenrodYellow);
  42. g.DrawString(text, tf, rect);
  43. var result = new LinkAnnotation(rect, jsAction);
  44. doc.Pages.Last.Annotations.Add(result);
  45. // Add warning about this possibly not working in a browser:
  46. Common.Util.AddNote(
  47. "Note that JavaScript may not work in some PDF viewers such as built-in browser viewers.",
  48. doc.Pages.Last, new RectangleF(rect.X, rect.Bottom + 36, 400, 400));
  49. // Done:
  50. doc.Save(stream);
  51. return doc.Pages.Count;
  52. }
  53. }
  54. }
  55.