NoPassGetPageInfo.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.  
  11. namespace DsPdfWeb.Demos
  12. {
  13. // This example shows how to load a password protected PDF and get its page count and page sizes.
  14. // For reference, the loaded PDF is protected with the owner password 'owner' and user password 'user'.
  15. public class NoPassGetPageInfo
  16. {
  17. public int CreatePDF(Stream stream)
  18. {
  19. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands-password-user.pdf"));
  20. // Set up DecryptionOptions to allow loading password protected PDFs without password:
  21. var dopt = new DecryptionOptions() { ThrowExceptionIfInvalidPassword = false };
  22. var docSrc = new GcPdfDocument();
  23. docSrc.Load(fs, dopt);
  24.  
  25. // The PDF to hold the results:
  26. var doc = new GcPdfDocument();
  27. var page = doc.NewPage();
  28. // Set up a TextLayout to format the results:
  29. var tl = page.Graphics.CreateTextLayout();
  30. tl.DefaultFormat.Font = StandardFonts.Courier;
  31. tl.DefaultFormat.FontSize = 14;
  32. tl.MaxWidth = doc.PageSize.Width;
  33. tl.MaxHeight = doc.PageSize.Height;
  34. tl.MarginAll = tl.Resolution;
  35. var captionFmt = new TextFormat(tl.DefaultFormat) { Font = StandardFonts.CourierBold };
  36.  
  37. // Get and print some of the source PDF stats:
  38. tl.AppendLine($"The source PDF contains {docSrc.Pages.Count} page(s).", captionFmt);
  39. foreach (var pg in docSrc.Pages)
  40. {
  41. tl.AppendLine($" Page at index {pg.Index}:", captionFmt);
  42. var sz = pg.GetRenderSize();
  43. tl.AppendLine($" Page size is {sz.Width}x{sz.Height}.");
  44. tl.AppendLine($" Page has {(pg.Landscape ? "landscape" : "portrait")} orientation.");
  45. tl.AppendLine($" Page paper kind is '{pg.PaperKind}'.");
  46. }
  47.  
  48. // Render the results:
  49. tl.PerformLayout(true);
  50. while (true)
  51. {
  52. var splitResult = tl.Split(null, out TextLayout rest);
  53. page.Graphics.DrawTextLayout(tl, PointF.Empty);
  54. if (splitResult != SplitResult.Split)
  55. break;
  56. tl = rest;
  57. tl.MarginTop = tl.Resolution;
  58. page = doc.Pages.Add();
  59. }
  60.  
  61. // Done:
  62. doc.Save(stream);
  63. return doc.Pages.Count;
  64. }
  65. }
  66. }
  67.