NCUploadScanDocument.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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 size: Int64 = 0
  41. @Published var url: URL = Bundle.main.url(forResource: "Reasons to use Nextcloud", withExtension: "pdf")!
  42. let fileNameDefault = NSTemporaryDirectory() + "scandocument.pdf"
  43. var images: [UIImage] = []
  44. init(images: [UIImage]) {
  45. self.images = images
  46. createPDF()
  47. }
  48. func createPDF(preview: Bool = true, password: String = "", textRecognition: Bool = false, quality: Double = 1) {
  49. guard !images.isEmpty else { return }
  50. let pdfData = NSMutableData()
  51. if password.isEmpty {
  52. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  53. } else {
  54. for char in password.unicodeScalars {
  55. if !char.isASCII {
  56. NCActivityIndicator.shared.stop()
  57. let error = NKError(errorCode: NCGlobal.shared.errorForbidden, errorDescription: "_password_ascii_")
  58. NCContentPresenter.shared.showError(error: error)
  59. return
  60. }
  61. }
  62. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String: password, kCGPDFContextOwnerPassword as String: password]
  63. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  64. }
  65. if preview {
  66. if var image = images.first {
  67. image = changeCompressionImage(image, quality: quality)
  68. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  69. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  70. image.draw(in: bounds)
  71. }
  72. } else {
  73. for var image in images {
  74. image = changeCompressionImage(image, quality: quality)
  75. let bounds = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
  76. if textRecognition {
  77. } else {
  78. UIGraphicsBeginPDFPageWithInfo(bounds, nil)
  79. image.draw(in: bounds)
  80. }
  81. }
  82. }
  83. UIGraphicsEndPDFContext()
  84. do {
  85. url = URL(fileURLWithPath: fileNameDefault)
  86. try pdfData.write(to: url, options: .atomic)
  87. } catch {
  88. print("error catched")
  89. }
  90. size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNameDefault)
  91. }
  92. func changeCompressionImage(_ image: UIImage, quality: Double) -> UIImage {
  93. var compressionQuality: CGFloat = 0.5
  94. var baseHeight: Float = 595.2 // A4
  95. var baseWidth: Float = 841.8 // A4
  96. switch quality {
  97. case 0:
  98. baseHeight *= 1
  99. baseWidth *= 1
  100. compressionQuality = 0.3
  101. case 1:
  102. baseHeight *= 2
  103. baseWidth *= 2
  104. compressionQuality = 0.6
  105. case 2:
  106. baseHeight *= 4
  107. baseWidth *= 4
  108. compressionQuality = 0.8
  109. case 3:
  110. baseHeight *= 6
  111. baseWidth *= 6
  112. compressionQuality = 0.9
  113. case 4:
  114. baseHeight *= 8
  115. baseWidth *= 8
  116. compressionQuality = 1
  117. default:
  118. break
  119. }
  120. var newHeight = Float(image.size.height)
  121. var newWidth = Float(image.size.width)
  122. var imgRatio: Float = newWidth / newHeight
  123. let baseRatio: Float = baseWidth / baseHeight
  124. if newHeight > baseHeight || newWidth > baseWidth {
  125. if imgRatio < baseRatio {
  126. imgRatio = baseHeight / newHeight
  127. newWidth = imgRatio * newWidth
  128. newHeight = baseHeight
  129. } else if imgRatio > baseRatio {
  130. imgRatio = baseWidth / newWidth
  131. newHeight = imgRatio * newHeight
  132. newWidth = baseWidth
  133. } else {
  134. newHeight = baseHeight
  135. newWidth = baseWidth
  136. }
  137. }
  138. let rect = CGRect(x: 0.0, y: 0.0, width: CGFloat(newWidth), height: CGFloat(newHeight))
  139. UIGraphicsBeginImageContext(rect.size)
  140. image.draw(in: rect)
  141. let img = UIGraphicsGetImageFromCurrentImageContext()
  142. let imageData = img?.jpegData(compressionQuality: CGFloat(compressionQuality))
  143. UIGraphicsEndImageContext()
  144. return UIImage(data: imageData!) ?? image
  145. }
  146. }
  147. extension NCUploadScanDocument: NCSelectDelegate {
  148. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) {
  149. }
  150. }
  151. extension NCUploadScanDocument: NCCreateFormUploadConflictDelegate {
  152. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  153. }
  154. }
  155. // MARK: - Preview / Test
  156. struct UploadScanDocumentView: View {
  157. @State var quality = 2.0
  158. @State var password: String = ""
  159. @State var filename: String = ""
  160. @State var isSecured: Bool = true
  161. @ObservedObject var uploadScanDocument: NCUploadScanDocument
  162. init(_ uploadScanDocument: NCUploadScanDocument) {
  163. self.uploadScanDocument = uploadScanDocument
  164. }
  165. var body: some View {
  166. GeometryReader { geo in
  167. List {
  168. Section(header: Text(NSLocalizedString("_file_creation_", comment: ""))) {
  169. HStack {
  170. Label {
  171. Text("/")
  172. .frame(maxWidth: .infinity, alignment: .trailing)
  173. } icon: {
  174. Image("folder")
  175. .renderingMode(.template)
  176. .resizable()
  177. .scaledToFit()
  178. .frame(width: NCBrandSettings.shared.settingsSizeImage, height: NCBrandSettings.shared.settingsSizeImage)
  179. .foregroundColor(Color(NCBrandColor.shared.brand))
  180. }
  181. Spacer()
  182. }
  183. .contentShape(Rectangle())
  184. .onTapGesture {
  185. //
  186. }
  187. .complexModifier { view in
  188. if #available(iOS 16, *) {
  189. view.alignmentGuide(.listRowSeparatorLeading) { _ in
  190. return 0
  191. }
  192. }
  193. }
  194. HStack {
  195. Text(NSLocalizedString("_filename_", comment: ""))
  196. TextField(NSLocalizedString("_enter_filename_", comment: ""), text: $filename)
  197. .multilineTextAlignment(.trailing)
  198. }
  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. }
  224. Section(header: Text(NSLocalizedString("_quality_image_title_", comment: ""))) {
  225. VStack {
  226. Slider(value: $quality, in: 0...4, step: 1).onChange(of: quality, perform: { quality in
  227. uploadScanDocument.createPDF(quality: quality)
  228. })
  229. .accentColor(Color(NCBrandColor.shared.brand))
  230. }
  231. PDFKitRepresentedView(uploadScanDocument.url)
  232. .frame(maxWidth: .infinity, minHeight: geo.size.height / 2.7)
  233. }.complexModifier { view in
  234. if #available(iOS 15, *) {
  235. view.listRowSeparator(.hidden)
  236. }
  237. }
  238. Button(NSLocalizedString("_save_", comment: "")) {
  239. print("ciao")
  240. }
  241. .buttonStyle(NCButton())
  242. .frame(maxWidth: .infinity, alignment: .center)
  243. .listRowBackground(Color(UIColor.systemGroupedBackground))
  244. }
  245. }
  246. .background(Color(UIColor.systemGroupedBackground))
  247. }
  248. }
  249. struct NCButton: ButtonStyle {
  250. func makeBody(configuration: Configuration) -> some View {
  251. configuration.label
  252. .padding(.horizontal, 50)
  253. .padding(.vertical, 10)
  254. .background(Color(NCBrandColor.shared.brand))
  255. .foregroundColor(.white)
  256. .clipShape(Capsule())
  257. }
  258. }
  259. struct PDFKitRepresentedView: UIViewRepresentable {
  260. let url: URL
  261. init(_ url: URL) {
  262. self.url = url
  263. }
  264. func makeUIView(context: UIViewRepresentableContext<PDFKitRepresentedView>) -> PDFKitRepresentedView.UIViewType {
  265. let pdfView = PDFView()
  266. pdfView.document = PDFDocument(url: self.url)
  267. pdfView.autoScales = true
  268. pdfView.backgroundColor = .clear
  269. pdfView.displayMode = .singlePage
  270. pdfView.displayDirection = .vertical
  271. return pdfView
  272. }
  273. func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<PDFKitRepresentedView>) {
  274. }
  275. }
  276. struct UploadScanDocumentView_Previews: PreviewProvider {
  277. static var previews: some View {
  278. let uploadScanDocument = NCUploadScanDocument(images: [])
  279. UploadScanDocumentView(uploadScanDocument)
  280. // .previewDevice(PreviewDevice(rawValue: "iPhone 14 Pro"))
  281. // .previewDisplayName("iPhone 14")
  282. }
  283. }