NCUploadScanDocument.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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(preview: Bool = true, 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. if preview {
  64. if var image = images.first {
  65. image = changeCompressionImage(image, quality: quality)
  66. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  67. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  68. image.draw(in: bounds)
  69. }
  70. } else {
  71. for var image in images {
  72. image = changeCompressionImage(image, quality: quality)
  73. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  74. if textRecognition {
  75. } else {
  76. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  77. image.draw(in: bounds)
  78. }
  79. }
  80. }
  81. UIGraphicsEndPDFContext()
  82. do {
  83. url = URL(fileURLWithPath: NSTemporaryDirectory() + "scandocument.pdf")
  84. try pdfData.write(to: url, options: .atomic)
  85. } catch {
  86. print("error catched")
  87. }
  88. }
  89. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  90. var compressionQuality: CGFloat = 0.5
  91. var baseHeight: Float = 595.2 // A4
  92. var baseWidth: Float = 841.8 // A4
  93. switch quality {
  94. case 0:
  95. baseHeight *= 1
  96. baseWidth *= 1
  97. compressionQuality = 0.3
  98. case 1:
  99. baseHeight *= 2
  100. baseWidth *= 2
  101. compressionQuality = 0.6
  102. case 2:
  103. baseHeight *= 4
  104. baseWidth *= 4
  105. compressionQuality = 0.9
  106. default:
  107. break
  108. }
  109. var newHeight = Float(image.size.height)
  110. var newWidth = Float(image.size.width)
  111. var imgRatio: Float = newWidth / newHeight
  112. let baseRatio: Float = baseWidth / baseHeight
  113. if newHeight > baseHeight || newWidth > baseWidth {
  114. if imgRatio < baseRatio {
  115. imgRatio = baseHeight / newHeight
  116. newWidth = imgRatio * newWidth
  117. newHeight = baseHeight
  118. } else if imgRatio > baseRatio {
  119. imgRatio = baseWidth / newWidth
  120. newHeight = imgRatio * newHeight
  121. newWidth = baseWidth
  122. } else {
  123. newHeight = baseHeight
  124. newWidth = baseWidth
  125. }
  126. }
  127. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  128. UIGraphicsBeginImageContext(rect.size)
  129. image.draw(in: rect)
  130. let img = UIGraphicsGetImageFromCurrentImageContext()
  131. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  132. UIGraphicsEndImageContext()
  133. return UIImage(data: imageData!) ?? image
  134. }
  135. }
  136. extension NCUploadScanDocument: NCSelectDelegate {
  137. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  138. }
  139. }
  140. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  141. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  142. }
  143. }
  144. // MARK: - Preview / Test
  145. struct UploadScanDocumentView: View {
  146. @State var quality = 1.0
  147. @State var password: String = ""
  148. @State var filename: String = ""
  149. @State var isSecured: Bool = true
  150. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  151. init(_ uploadScanDocument: NCUploadScanDocument) {
  152. self.uploadScanDocument = uploadScanDocument
  153. }
  154. var body: some View {
  155. GeometryReader { geo in
  156. VStack {
  157. List {
  158. Section(header: Text(NSLocalizedString("_save_path_", comment: ""))) {
  159. HStack {
  160. Label {
  161. Text("/")
  162. .frame(maxWidth: .infinity, alignment: .trailing)
  163. } icon: {
  164. Image("folder")
  165. .renderingMode(.template)
  166. .resizable()
  167. .scaledToFit()
  168. .frame(width: NCBrandSettings.shared.settingsSizeImage, height: NCBrandSettings.shared.settingsSizeImage)
  169. .foregroundColor(Color(NCBrandColor.shared.brand))
  170. }
  171. Spacer()
  172. }
  173. .contentShape(Rectangle())
  174. .onTapGesture {
  175. //
  176. }
  177. }
  178. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  179. VStack {
  180. switch quality {
  181. case 0:
  182. Text(NSLocalizedString("_quality_low_", comment: ""))
  183. case 1:
  184. Text(NSLocalizedString("_quality_medium_", comment: ""))
  185. case 2:
  186. Text(NSLocalizedString("_quality_high_", comment: ""))
  187. default:
  188. Text("")
  189. }
  190. Slider(value: $quality, in: 0...2, step: 1).onChange(of: quality, perform: { quality in
  191. uploadScanDocument.createPDF(quality: quality)
  192. })
  193. .accentColor(Color(NCBrandColor.shared.brand))
  194. }
  195. }
  196. Section(header: Text(NSLocalizedString("_preview_", comment: ""))) {
  197. PDFKitRepresentedView(uploadScanDocument.url)
  198. .frame(maxWidth: .infinity, minHeight: geo.size.height / 3.5)
  199. }
  200. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  201. HStack {
  202. Group {
  203. Text(NSLocalizedString("_password_", comment: ""))
  204. if isSecured {
  205. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  206. .multilineTextAlignment(.trailing)
  207. } else {
  208. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  209. .multilineTextAlignment(.trailing)
  210. }
  211. }
  212. Button(action: {
  213. isSecured.toggle()
  214. }) {
  215. Image(systemName: self.isSecured ? "eye.slash" : "eye")
  216. .accentColor(.gray)
  217. }
  218. }
  219. HStack {
  220. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $uploadScanDocument.isTextRecognition)
  221. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  222. .onChange(of: uploadScanDocument.isTextRecognition) { newValue in
  223. }
  224. }
  225. HStack {
  226. Text(NSLocalizedString("_filename_", comment: ""))
  227. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $filename)
  228. .multilineTextAlignment(.trailing)
  229. }
  230. }
  231. }
  232. }
  233. }
  234. }
  235. }
  236. struct PDFKitRepresentedView: UIViewRepresentable {
  237. let url: URL
  238. init(_ url: URL) {
  239. self.url = url
  240. }
  241. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  242. let pdfView = PDFView()
  243. pdfView.document = PDFDocument(url: self.url)
  244. pdfView.autoScales = true
  245. pdfView.backgroundColor = .clear
  246. pdfView.displayMode = .singlePage
  247. pdfView.displayDirection = .vertical
  248. return pdfView
  249. }
  250. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  251. }
  252. }
  253. struct UploadScanDocumentView_Previews: PreviewProvider {
  254. static var previews: some View {
  255. let uploadScanDocument = NCUploadScanDocument(images: [])
  256. UploadScanDocumentView(uploadScanDocument)
  257. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  258. // .previewDisplayName("iPhone 14")
  259. }
  260. }