NCUploadScanDocument.swift 11 KB

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