NCUploadScanDocument.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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(arrayImages: [UIImage], account: String, serverUrl: String) -> UIViewController {
  31. let details = UploadScanDocumentView(arrayImages: arrayImages)
  32. let vc = UIHostingController(rootView: details)
  33. vc.title = NSLocalizedString("_save_settings_", comment: "")
  34. return vc
  35. }
  36. }
  37. class NCUploadScanDocument: ObservableObject {
  38. @Published var isTextRecognition: Bool = false
  39. @Published var urlPreviewFile: URL = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  40. var arrayImages: [UIImage] = []
  41. init() {
  42. createPDF()
  43. }
  44. func createPDF(password: String = "", textRecognition: Bool = false, quality: Double = 2) {
  45. guard !arrayImages.isEmpty else { return }
  46. let pdfData = NSMutableData()
  47. if password.isEmpty {
  48. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  49. } else {
  50. for char in password.unicodeScalars {
  51. if !char.isASCII {
  52. NCActivityIndicator.shared.stop()
  53. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  54. NCContentPresenter.shared.showError(error: error)
  55. return
  56. }
  57. }
  58. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
  59. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  60. }
  61. for var image in self.arrayImages {
  62. image = changeCompressionImage(image, quality: quality)
  63. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  64. if textRecognition {
  65. } else {
  66. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  67. image.draw(in: bounds)
  68. }
  69. }
  70. UIGraphicsEndPDFContext()
  71. do {
  72. if let url = URL(string: NSTemporaryDirectory() + "scandocument.pdf") {
  73. try pdfData.write(to: url, options: .atomic)
  74. }
  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. @ObservedObject var uploadScanDocument = NCUploadScanDocument()
  137. @State var arrayImages: [UIImage] = []
  138. @State var currentValue = 1.0
  139. @State var password: String = ""
  140. @State var isSecured: Bool = true
  141. var body: some View {
  142. GeometryReader { geo in
  143. VStack {
  144. List {
  145. Section(header: Text(NSLocalizedString("_save_path_", comment: ""))) {
  146. HStack {
  147. Label {
  148. Text("/")
  149. .frame(maxWidth: .infinity, alignment: .trailing)
  150. } icon: {
  151. Image("folder")
  152. .renderingMode(.template)
  153. .resizable()
  154. .scaledToFit()
  155. .frame(width: NCBrandSettings.shared.settingsSizeImage, height: NCBrandSettings.shared.settingsSizeImage)
  156. .foregroundColor(Color(NCBrandColor.shared.brand))
  157. }
  158. Spacer()
  159. }
  160. .contentShape(Rectangle())
  161. .onTapGesture {
  162. //
  163. }
  164. }
  165. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  166. VStack {
  167. Text("Current slider value")
  168. Slider(value: $currentValue, in: 0...3, step: 1) { _ in
  169. uploadScanDocument.createPDF(quality: currentValue)
  170. }
  171. .accentColor(Color(NCBrandColor.shared.brand))
  172. }
  173. }
  174. Section(header: Text(NSLocalizedString("_preview_", comment: ""))) {
  175. PDFKitRepresentedView(uploadScanDocument.urlPreviewFile)
  176. .frame(width: .infinity, height: geo.size.height / 3)
  177. }
  178. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  179. HStack {
  180. Group {
  181. Text(NSLocalizedString("_password_", comment: ""))
  182. if isSecured {
  183. SecureField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  184. .multilineTextAlignment(.trailing)
  185. } else {
  186. TextField(NSLocalizedString("_enter_password_", comment: ""), text: $password)
  187. .multilineTextAlignment(.trailing)
  188. }
  189. }
  190. Button(action: {
  191. isSecured.toggle()
  192. }) {
  193. Image(systemName: self.isSecured ? "eye.slash" : "eye")
  194. .accentColor(.gray)
  195. }
  196. }
  197. HStack {
  198. Toggle(NSLocalizedString("_text_recognition_", comment: ""), isOn: $uploadScanDocument.isTextRecognition)
  199. .toggleStyle(SwitchToggleStyle(tint: Color(NCBrandColor.shared.brand)))
  200. .onChange(of: uploadScanDocument.isTextRecognition) { newValue in
  201. }
  202. }
  203. HStack {
  204. Text(NSLocalizedString("_filename_", comment: ""))
  205. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $password)
  206. .multilineTextAlignment(.trailing)
  207. }
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. struct PDFKitRepresentedView: UIViewRepresentable {
  215. let url: URL
  216. init(_ url: URL) {
  217. self.url = url
  218. }
  219. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  220. let pdfView = PDFView()
  221. pdfView.document = PDFDocument(url: self.url)
  222. pdfView.autoScales = true
  223. pdfView.backgroundColor = .clear
  224. pdfView.displayMode = .singlePage
  225. pdfView.displayDirection = .vertical
  226. return pdfView
  227. }
  228. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  229. }
  230. }
  231. struct UploadScanDocumentView_Previews: PreviewProvider {
  232. static var previews: some View {
  233. // let account = (UIApplication.shared.delegate as! AppDelegate).account
  234. UploadScanDocumentView()
  235. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  236. // .previewDisplayName("iPhone 14")
  237. }
  238. }