PDFPassword.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // PDFPassword.swift
  3. // PDFGenerator
  4. //
  5. // Created by Suguru Kishimoto on 2016/07/08.
  6. //
  7. //
  8. import Foundation
  9. import UIKit
  10. public struct PDFPassword {
  11. static let NoPassword = ""
  12. fileprivate static let PasswordLengthMax = 32
  13. let userPassword: String
  14. let ownerPassword: String
  15. public init(user userPassword: String, owner ownerPassword: String) {
  16. self.userPassword = userPassword
  17. self.ownerPassword = ownerPassword
  18. }
  19. public init(_ password: String) {
  20. self.init(user: password, owner: password)
  21. }
  22. func toDocumentInfo() -> [AnyHashable : Any] {
  23. var info: [AnyHashable : Any] = [:]
  24. if userPassword != type(of: self).NoPassword {
  25. info[String(kCGPDFContextUserPassword)] = userPassword
  26. }
  27. if ownerPassword != type(of: self).NoPassword {
  28. info[String(kCGPDFContextOwnerPassword)] = ownerPassword
  29. }
  30. return info
  31. }
  32. func verify() throws {
  33. guard userPassword.canBeConverted(to: String.Encoding.ascii) else {
  34. throw PDFGenerateError.invalidPassword(userPassword)
  35. }
  36. guard userPassword.characters.count <= type(of: self).PasswordLengthMax else {
  37. throw PDFGenerateError.tooLongPassword(userPassword.characters.count)
  38. }
  39. guard ownerPassword.canBeConverted(to: String.Encoding.ascii) else {
  40. throw PDFGenerateError.invalidPassword(ownerPassword)
  41. }
  42. guard ownerPassword.characters.count <= type(of: self).PasswordLengthMax else {
  43. throw PDFGenerateError.tooLongPassword(ownerPassword.characters.count)
  44. }
  45. }
  46. }
  47. extension PDFPassword: ExpressibleByStringLiteral {
  48. public init(unicodeScalarLiteral value: String) {
  49. self.init(value)
  50. }
  51. public init(extendedGraphemeClusterLiteral value: String) {
  52. self.init(value)
  53. }
  54. public init(stringLiteral value: String) {
  55. self.init(value)
  56. }
  57. }