NCUploadScanDocument.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. //
  2. // NCUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 28/12/22.
  6. // Copyright © 2022 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. import SwiftUI
  24. import NextcloudKit
  25. import Vision
  26. import VisionKit
  27. import Photos
  28. import PDFKit
  29. class NCHostingUploadScanDocumentView: NSObject {
  30. @objc func makeShipDetailsUI(images: [UIImage], account: String, serverUrl: String) -> UIViewController {
  31. let uploadScanDocument = NCUploadScanDocument(images: images)
  32. let details = UploadScanDocumentView(uploadScanDocument)
  33. let vc = UIHostingController(rootView: details)
  34. vc.title = NSLocalizedString("_save_settings_", comment: "")
  35. return vc
  36. }
  37. }
  38. class NCUploadScanDocument: ObservableObject {
  39. @Published var isTextRecognition: Bool = false
  40. @Published var url: URL = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  41. var images: [UIImage] = []
  42. init(images: [UIImage]) {
  43. self.images = images
  44. createPDF()
  45. }
  46. func createPDF(password: String = "", textRecognition: Bool = false, quality: Double = 1) {
  47. guard !images.isEmpty else { return }
  48. let pdfData = NSMutableData()
  49. if password.isEmpty {
  50. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  51. } else {
  52. for char in password.unicodeScalars {
  53. if !char.isASCII {
  54. NCActivityIndicator.shared.stop()
  55. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  56. NCContentPresenter.shared.showError(error: error)
  57. return
  58. }
  59. }
  60. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
  61. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  62. }
  63. for var image in images {
  64. image = changeCompressionImage(image, quality: quality)
  65. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  66. if textRecognition {
  67. } else {
  68. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  69. image.draw(in: bounds)
  70. }
  71. }
  72. UIGraphicsEndPDFContext()
  73. do {
  74. url = URL(fileURLWithPath: NSTemporaryDirectory() + "scandocument.pdf")
  75. try pdfData.write(to: url, options: .atomic)
  76. } catch {
  77. print("error catched")
  78. }
  79. }
  80. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  81. var compressionQuality: CGFloat = 0.5
  82. var baseHeight: Float = 595.2 // A4
  83. var baseWidth: Float = 841.8 // A4
  84. switch quality {
  85. case 0:
  86. baseHeight *= 1
  87. baseWidth *= 1
  88. compressionQuality = 0.3
  89. case 1:
  90. baseHeight *= 2
  91. baseWidth *= 2
  92. compressionQuality = 0.6
  93. case 2:
  94. baseHeight *= 4
  95. baseWidth *= 4
  96. compressionQuality = 0.9
  97. default:
  98. break
  99. }
  100. var newHeight = Float(image.size.height)
  101. var newWidth = Float(image.size.width)
  102. var imgRatio: Float = newWidth / newHeight
  103. let baseRatio: Float = baseWidth / baseHeight
  104. if newHeight > baseHeight || newWidth > baseWidth {
  105. if imgRatio < baseRatio {
  106. imgRatio = baseHeight / newHeight
  107. newWidth = imgRatio * newWidth
  108. newHeight = baseHeight
  109. } else if imgRatio > baseRatio {
  110. imgRatio = baseWidth / newWidth
  111. newHeight = imgRatio * newHeight
  112. newWidth = baseWidth
  113. } else {
  114. newHeight = baseHeight
  115. newWidth = baseWidth
  116. }
  117. }
  118. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  119. UIGraphicsBeginImageContext(rect.size)
  120. image.draw(in: rect)
  121. let img = UIGraphicsGetImageFromCurrentImageContext()
  122. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  123. UIGraphicsEndImageContext()
  124. return UIImage(data: imageData!) ?? image
  125. }
  126. }
  127. extension NCUploadScanDocument: NCSelectDelegate {
  128. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  129. }
  130. }
  131. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  132. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  133. }
  134. }
  135. // MARK: - Preview / Test
  136. struct UploadScanDocumentView: View {
  137. @State var currentValue = 1.0
  138. @State var password: String = ""
  139. @State var isSecured: Bool = true
  140. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  141. init(_ uploadScanDocument: NCUploadScanDocument) {
  142. self.uploadScanDocument = uploadScanDocument
  143. }
  144. var body: some View {
  145. GeometryReader { geo in
  146. VStack {
  147. List {
  148. Section(header: Text(NSLocalizedString("_save_path_", comment: ""))) {
  149. HStack {
  150. Label {
  151. Text("/")
  152. .frame(maxWidth: .infinity, alignment: .trailing)
  153. } icon: {
  154. Image("folder")
  155. .renderingMode(.template)
  156. .resizable()
  157. .scaledToFit()
  158. .frame(width: NCBrandSettings.shared.settingsSizeImage, height: NCBrandSettings.shared.settingsSizeImage)
  159. .foregroundColor(Color(NCBrandColor.shared.brand))
  160. }
  161. Spacer()
  162. }
  163. .contentShape(Rectangle())
  164. .onTapGesture {
  165. //
  166. }
  167. }
  168. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  169. VStack {
  170. Text("Current slider value")
  171. Slider(value: $currentValue, in: 0...2, step: 1) { _ in
  172. uploadScanDocument.createPDF(quality: currentValue)
  173. }
  174. // Slider(value: $currentValue, in: 0...2, step: 1).onChange(of: currentValue, perform: { currentValue in
  175. // uploadScanDocument.createPDF(quality: currentValue)
  176. // })
  177. .accentColor(Color(NCBrandColor.shared.brand))
  178. }
  179. }
  180. Section(header: Text(NSLocalizedString("_preview_", comment: ""))) {
  181. PDFKitRepresentedView(uploadScanDocument.url)
  182. .frame(maxWidth: .infinity, minHeight: geo.size.height / 3)
  183. }
  184. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  185. HStack {
  186. Group {
  187. Text(NSLocalizedString("_password_", comment: ""))
  188. if isSecured {
  189. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  190. .multilineTextAlignment(.trailing)
  191. } else {
  192. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  193. .multilineTextAlignment(.trailing)
  194. }
  195. }
  196. Button(action: {
  197. isSecured.toggle()
  198. }) {
  199. Image(systemName: self.isSecured ? "eye.slash" : "eye")
  200. .accentColor(.gray)
  201. }
  202. }
  203. HStack {
  204. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $uploadScanDocument.isTextRecognition)
  205. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  206. .onChange(of: uploadScanDocument.isTextRecognition) { newValue in
  207. }
  208. }
  209. HStack {
  210. Text(NSLocalizedString("_filename_", comment: ""))
  211. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $password)
  212. .multilineTextAlignment(.trailing)
  213. }
  214. }
  215. }
  216. }
  217. }
  218. .background(Color(UIColor.systemGroupedBackground))
  219. }
  220. }
  221. struct PDFKitRepresentedView: UIViewRepresentable {
  222. let url: URL
  223. init(_ url: URL) {
  224. self.url = url
  225. }
  226. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  227. let pdfView = PDFView()
  228. pdfView.document = PDFDocument(url: self.url)
  229. pdfView.autoScales = true
  230. pdfView.backgroundColor = .clear
  231. pdfView.displayMode = .singlePage
  232. pdfView.displayDirection = .vertical
  233. return pdfView
  234. }
  235. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  236. }
  237. }
  238. struct UploadScanDocumentView_Previews: PreviewProvider {
  239. static var previews: some View {
  240. let uploadScanDocument = NCUploadScanDocument(images: [])
  241. UploadScanDocumentView(uploadScanDocument)
  242. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  243. // .previewDisplayName("iPhone 14")
  244. }
  245. }