NoPassAddAnnotation.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.Pdf.Annotations;
  10.  
  11. namespace DsPdfWeb.Demos
  12. {
  13. // This example shows how to load a password protected PDF without specifying the password,
  14. // and add a square annotation (a red border along the sides of the page) to the first page of the PDF.
  15. // The modified PDF is saved and re-opened with the password so that we can show it in the demo.
  16. public class NoPassAddAnnotation
  17. {
  18. public int CreatePDF(Stream stream)
  19. {
  20. using var fsSrc = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands-password-user.pdf"));
  21. // Set up DecryptionOptions to allow loading password protected PDFs without password:
  22. var dopt = new DecryptionOptions() { ThrowExceptionIfInvalidPassword = false };
  23. var docSrc = new GcPdfDocument();
  24. docSrc.Load(fsSrc, dopt);
  25.  
  26. // Add a square annotation to the first page of the PDF:
  27. var page = docSrc.Pages[0];
  28. var pageSize = page.Size;
  29. var sa = new SquareAnnotation()
  30. {
  31. Page = page,
  32. Rect = new RectangleF(36, 36, pageSize.Width - 72, pageSize.Height - 72),
  33. Color = Color.Red,
  34. };
  35. // Note: we must remove the UserName, as it is initialized by default which will cause an exception
  36. // when the document is saved, because strings cannot be encrypted:
  37. sa.UserName = null;
  38.  
  39. // Demo site specific:
  40. // We save the modified password protected document to a temp file,
  41. // and load it again with the password, so that the demo site can show it
  42. // without asking the user for a password (the block is to delete the temp file):
  43. var fn = Path.GetTempFileName();
  44. {
  45. docSrc.Save(fn);
  46. var doc = new GcPdfDocument();
  47. using var fs = File.OpenRead(fn);
  48. doc.Load(fs, "user");
  49. doc.Save(stream);
  50. }
  51. File.Delete(fn);
  52. return docSrc.Pages.Count;
  53. }
  54. }
  55. }
  56.