NCUploadScanDocument.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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(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. for var image in images {
  63. image = changeCompressionImage(image, quality: quality)
  64. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  65. if textRecognition {
  66. } else {
  67. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  68. image.draw(in: bounds)
  69. }
  70. }
  71. UIGraphicsEndPDFContext()
  72. do {
  73. url = URL(fileURLWithPath: NSTemporaryDirectory() + "scandocument.pdf")
  74. try pdfData.write(to: url, options: .atomic)
  75. } catch {
  76. print("error catched")
  77. }
  78. }
  79. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  80. var compressionQuality: CGFloat = 0.5
  81. var baseHeight: Float = 595.2 // A4
  82. var baseWidth: Float = 841.8 // A4
  83. switch quality {
  84. case 0:
  85. baseHeight *= 1
  86. baseWidth *= 1
  87. compressionQuality = 0.3
  88. case 1:
  89. baseHeight *= 2
  90. baseWidth *= 2
  91. compressionQuality = 0.6
  92. case 2:
  93. baseHeight *= 4
  94. baseWidth *= 4
  95. compressionQuality = 0.9
  96. default:
  97. break
  98. }
  99. var newHeight = Float(image.size.height)
  100. var newWidth = Float(image.size.width)
  101. var imgRatio: Float = newWidth / newHeight
  102. let baseRatio: Float = baseWidth / baseHeight
  103. if newHeight > baseHeight || newWidth > baseWidth {
  104. if imgRatio < baseRatio {
  105. imgRatio = baseHeight / newHeight
  106. newWidth = imgRatio * newWidth
  107. newHeight = baseHeight
  108. } else if imgRatio > baseRatio {
  109. imgRatio = baseWidth / newWidth
  110. newHeight = imgRatio * newHeight
  111. newWidth = baseWidth
  112. } else {
  113. newHeight = baseHeight
  114. newWidth = baseWidth
  115. }
  116. }
  117. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  118. UIGraphicsBeginImageContext(rect.size)
  119. image.draw(in: rect)
  120. let img = UIGraphicsGetImageFromCurrentImageContext()
  121. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  122. UIGraphicsEndImageContext()
  123. return UIImage(data: imageData!) ?? image
  124. }
  125. }
  126. extension NCUploadScanDocument: NCSelectDelegate {
  127. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  128. }
  129. }
  130. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  131. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  132. }
  133. }
  134. // MARK: - Preview / Test
  135. struct UploadScanDocumentView: View {
  136. @State var quality = 1.0
  137. @State var password: String = ""
  138. @State var filename: 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: $quality, in: 0...2, step: 1) { _ in
  172. uploadScanDocument.createPDF(quality: quality)
  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.5)
  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: $filename)
  212. .multilineTextAlignment(.trailing)
  213. }
  214. }
  215. }
  216. }
  217. }
  218. }
  219. }
  220. struct PDFKitRepresentedView: UIViewRepresentable {
  221. let url: URL
  222. init(_ url: URL) {
  223. self.url = url
  224. }
  225. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  226. let pdfView = PDFView()
  227. pdfView.document = PDFDocument(url: self.url)
  228. pdfView.autoScales = true
  229. pdfView.backgroundColor = .clear
  230. pdfView.displayMode = .singlePage
  231. pdfView.displayDirection = .vertical
  232. return pdfView
  233. }
  234. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  235. }
  236. }
  237. struct UploadScanDocumentView_Previews: PreviewProvider {
  238. static var previews: some View {
  239. let uploadScanDocument = NCUploadScanDocument(images: [])
  240. UploadScanDocumentView(uploadScanDocument)
  241. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  242. // .previewDisplayName("iPhone 14")
  243. }
  244. }