NCCreateFormUploadScanDocument.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. //
  2. // NCCreateFormUploadScanDocument.swift
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 14/11/2018.
  6. // Copyright © 2018 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 Foundation
  24. import WeScan
  25. import NCCommunication
  26. import Vision
  27. class NCCreateFormUploadScanDocument: XLFormViewController, NCSelectDelegate, NCCreateFormUploadConflictDelegate {
  28. enum typeDpiQuality {
  29. case low
  30. case medium
  31. case hight
  32. }
  33. var dpiQuality: typeDpiQuality = typeDpiQuality.medium
  34. var serverUrl = ""
  35. var titleServerUrl = ""
  36. var arrayImages: [UIImage] = []
  37. var fileName = CCUtility.createFileNameDate("scan", extension: "pdf")
  38. var password: String = ""
  39. var fileType = "PDF"
  40. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  41. convenience init(serverUrl: String, arrayImages: [UIImage]) {
  42. self.init()
  43. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  44. titleServerUrl = "/"
  45. } else {
  46. titleServerUrl = (serverUrl as NSString).lastPathComponent
  47. }
  48. self.serverUrl = serverUrl
  49. self.arrayImages = arrayImages
  50. }
  51. // MARK: - View Life Cycle
  52. override func viewDidLoad() {
  53. super.viewDidLoad()
  54. self.title = NSLocalizedString("_save_settings_", comment: "")
  55. let saveButton : UIBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save))
  56. self.navigationItem.rightBarButtonItem = saveButton
  57. self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
  58. // self.tableView.sectionHeaderHeight = 10
  59. // self.tableView.sectionFooterHeight = 10
  60. // self.tableView.backgroundColor = NCBrandColor.sharedInstance.backgroundView
  61. // let row : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  62. // let rowCell = row.cell(forForm: self)
  63. // rowCell.becomeFirstResponder()
  64. // Theming view
  65. NotificationCenter.default.addObserver(self, selector: #selector(changeTheming), name: NSNotification.Name(rawValue: k_notificationCenter_changeTheming), object: nil)
  66. changeTheming()
  67. }
  68. @objc func changeTheming() {
  69. appDelegate.changeTheming(self, tableView: tableView, collectionView: nil, form: true)
  70. initializeForm()
  71. }
  72. //MARK: XLForm
  73. func initializeForm() {
  74. let form : XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor
  75. form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow
  76. var section : XLFormSectionDescriptor
  77. var row : XLFormRowDescriptor
  78. // Section: Destination Folder
  79. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: ""))
  80. form.addFormSection(section)
  81. row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl)
  82. row.action.formSelector = #selector(changeDestinationFolder(_:))
  83. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  84. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "folder")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  85. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue
  86. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  87. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  88. section.addFormRow(row)
  89. // Section: Quality
  90. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_quality_image_title_", comment: ""))
  91. form.addFormSection(section)
  92. row = XLFormRowDescriptor(tag: "compressionQuality", rowType: XLFormRowDescriptorTypeSlider)
  93. row.value = 0.5
  94. row.title = NSLocalizedString("_quality_medium_", comment: "")
  95. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  96. row.cellConfig["slider.minimumTrackTintColor"] = NCBrandColor.sharedInstance.brandElement
  97. row.cellConfig["slider.maximumValue"] = 1
  98. row.cellConfig["slider.minimumValue"] = 0
  99. row.cellConfig["steps"] = 2
  100. row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.center.rawValue
  101. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  102. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  103. section.addFormRow(row)
  104. // Section: Password
  105. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_pdf_password_", comment: ""))
  106. form.addFormSection(section)
  107. row = XLFormRowDescriptor(tag: "password", rowType: XLFormRowDescriptorTypePassword, title: NSLocalizedString("_password_", comment: ""))
  108. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  109. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  110. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  111. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  112. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  113. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  114. section.addFormRow(row)
  115. // Section: Text recognition
  116. if #available(iOS 13.0, *) {
  117. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_text_recognition_", comment: ""))
  118. form.addFormSection(section)
  119. row = XLFormRowDescriptor(tag: "textRecognition", rowType: XLFormRowDescriptorTypeBooleanSwitch, title: NSLocalizedString("_text_recognition_", comment: ""))
  120. row.value = 0
  121. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  122. row.cellConfig["imageView.image"] = CCGraphics.changeThemingColorImage(UIImage(named: "textRecognition")!, width: 50, height: 50, color: NCBrandColor.sharedInstance.brandElement) as UIImage
  123. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  124. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  125. section.addFormRow(row)
  126. }
  127. // Section: File
  128. section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_file_creation_", comment: ""))
  129. form.addFormSection(section)
  130. row = XLFormRowDescriptor(tag: "filetype", rowType: XLFormRowDescriptorTypeSelectorSegmentedControl, title: NSLocalizedString("_file_type_", comment: ""))
  131. if arrayImages.count == 1 {
  132. row.selectorOptions = ["PDF","JPG"]
  133. } else {
  134. row.selectorOptions = ["PDF"]
  135. }
  136. row.value = "PDF"
  137. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  138. row.cellConfig["tintColor"] = NCBrandColor.sharedInstance.brandElement
  139. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  140. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  141. section.addFormRow(row)
  142. row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeAccount, title: NSLocalizedString("_filename_", comment: ""))
  143. row.value = self.fileName
  144. row.cellConfig["backgroundColor"] = NCBrandColor.sharedInstance.backgroundForm
  145. row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0)
  146. row.cellConfig["textLabel.textColor"] = NCBrandColor.sharedInstance.textView
  147. row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue
  148. row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0)
  149. row.cellConfig["textField.textColor"] = NCBrandColor.sharedInstance.textView
  150. section.addFormRow(row)
  151. self.form = form
  152. }
  153. override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) {
  154. super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue)
  155. if formRow.tag == "textRecognition" {
  156. let rowCompressionQuality: XLFormRowDescriptor = self.form.formRow(withTag: "compressionQuality")!
  157. let rowFileTape: XLFormRowDescriptor = self.form.formRow(withTag: "filetype")!
  158. let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  159. let rowPassword: XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  160. self.form.delegate = nil
  161. if newValue as! Int == 1 {
  162. rowFileTape.selectorOptions = ["PDF","TXT"]
  163. rowFileTape.value = "PDF"
  164. fileType = "PDF"
  165. rowPassword.disabled = true
  166. rowCompressionQuality.disabled = true
  167. } else {
  168. if arrayImages.count == 1 {
  169. rowFileTape.selectorOptions = ["PDF","JPG"]
  170. } else {
  171. rowFileTape.selectorOptions = ["PDF"]
  172. }
  173. rowFileTape.value = "PDF"
  174. fileType = "PDF"
  175. rowPassword.disabled = false
  176. rowCompressionQuality.disabled = false
  177. }
  178. rowFileName.value = createFileName(rowFileName.value as? String)
  179. self.updateFormRow(rowFileName)
  180. self.tableView.reloadData()
  181. self.form.delegate = self
  182. }
  183. if formRow.tag == "fileName" {
  184. self.form.delegate = nil
  185. let fileNameNew = newValue as? String
  186. if fileNameNew != nil {
  187. self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew)
  188. } else {
  189. self.fileName = ""
  190. }
  191. formRow.value = self.fileName
  192. self.updateFormRow(formRow)
  193. self.form.delegate = self
  194. }
  195. if formRow.tag == "compressionQuality" {
  196. self.form.delegate = nil
  197. //let row : XLFormRowDescriptor = self.form.formRow(withTag: "descriptionQuality")!
  198. let newQuality = newValue as? NSNumber
  199. let compressionQuality = (newQuality?.doubleValue)!
  200. if compressionQuality >= 0.0 && compressionQuality <= 0.3 {
  201. formRow.title = NSLocalizedString("_quality_low_", comment: "")
  202. dpiQuality = typeDpiQuality.low
  203. } else if compressionQuality > 0.3 && compressionQuality <= 0.6 {
  204. formRow.title = NSLocalizedString("_quality_medium_", comment: "")
  205. dpiQuality = typeDpiQuality.medium
  206. } else if compressionQuality > 0.6 && compressionQuality <= 1.0 {
  207. formRow.title = NSLocalizedString("_quality_high_", comment: "")
  208. dpiQuality = typeDpiQuality.hight
  209. }
  210. self.updateFormRow(formRow)
  211. self.form.delegate = self
  212. }
  213. if formRow.tag == "password" {
  214. let stringPassword = newValue as? String
  215. if stringPassword != nil {
  216. password = stringPassword!
  217. } else {
  218. password = ""
  219. }
  220. }
  221. if formRow.tag == "filetype" {
  222. fileType = newValue as! String
  223. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  224. let rowPassword : XLFormRowDescriptor = self.form.formRow(withTag: "password")!
  225. rowFileName.value = createFileName(rowFileName.value as? String)
  226. self.updateFormRow(rowFileName)
  227. // rowPassword
  228. if fileType == "JPG" || fileType == "TXT" {
  229. rowPassword.value = ""
  230. password = ""
  231. rowPassword.disabled = true
  232. } else {
  233. rowPassword.disabled = false
  234. }
  235. self.updateFormRow(rowPassword)
  236. }
  237. }
  238. override func textFieldDidBeginEditing(_ textField: UITextField) {
  239. let cell = textField.formDescriptorCell()
  240. let tag = cell?.rowDescriptor.tag
  241. if tag == "fileName" {
  242. CCUtility.selectFileName(from: textField)
  243. }
  244. }
  245. func createFileName(_ fileName: String?) -> String {
  246. var name: String = ""
  247. var newFileName: String = ""
  248. if fileName == nil || fileName == "" {
  249. name = CCUtility.createFileNameDate("scan", extension: "pdf") ?? "scan.pdf"
  250. } else {
  251. name = fileName!
  252. }
  253. let ext = (name as NSString).pathExtension.uppercased()
  254. if (ext == "") {
  255. newFileName = name + "." + fileType.lowercased()
  256. } else {
  257. newFileName = (name as NSString).deletingPathExtension + "." + fileType.lowercased()
  258. }
  259. return newFileName
  260. }
  261. // MARK: - Action
  262. func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, buttonType: String, overwrite: Bool) {
  263. if serverUrl != nil {
  264. self.serverUrl = serverUrl!
  265. if serverUrl == CCUtility.getHomeServerUrlActiveUrl(appDelegate.activeUrl) {
  266. self.titleServerUrl = "/"
  267. } else {
  268. self.titleServerUrl = (serverUrl! as NSString).lastPathComponent
  269. }
  270. // Update
  271. let row : XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")!
  272. row.title = self.titleServerUrl
  273. self.updateFormRow(row)
  274. }
  275. }
  276. @objc func save() {
  277. let rowFileName : XLFormRowDescriptor = self.form.formRow(withTag: "fileName")!
  278. guard let name = rowFileName.value else {
  279. return
  280. }
  281. if name as! String == "" {
  282. return
  283. }
  284. let ext = (name as! NSString).pathExtension.uppercased()
  285. var fileNameSave = ""
  286. if (ext == "") {
  287. fileNameSave = name as! String + "." + fileType.lowercased()
  288. } else {
  289. fileNameSave = (name as! NSString).deletingPathExtension + "." + fileType.lowercased()
  290. }
  291. //Create metadata for upload
  292. let metadataForUpload = NCManageDatabase.sharedInstance.createMetadata(account: appDelegate.activeAccount, fileName: fileNameSave, ocId: UUID().uuidString, serverUrl: serverUrl, url: "", contentType: "")
  293. metadataForUpload.session = NCCommunicationCommon.shared.sessionIdentifierBackground
  294. metadataForUpload.sessionSelector = selectorUploadFile
  295. metadataForUpload.status = Int(k_metadataStatusWaitUpload)
  296. if NCUtility.sharedInstance.getMetadataConflict(account: appDelegate.activeAccount, serverUrl: serverUrl, fileName: fileNameSave) != nil {
  297. guard let conflictViewController = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return }
  298. conflictViewController.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "")
  299. conflictViewController.serverUrl = serverUrl
  300. conflictViewController.metadatasUploadInConflict = [metadataForUpload]
  301. conflictViewController.delegate = self
  302. self.present(conflictViewController, animated: true, completion: nil)
  303. } else {
  304. dismissAndUpload(metadataForUpload)
  305. }
  306. }
  307. func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) {
  308. if metadatas != nil && metadatas!.count > 0 {
  309. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  310. self.dismissAndUpload(metadatas![0])
  311. }
  312. }
  313. }
  314. func dismissAndUpload(_ metadata: tableMetadata) {
  315. guard let fileNameGenerateExport = CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView) else {
  316. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorCreationFile), forced: true)
  317. return
  318. }
  319. // Text Recognition TXT
  320. if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  321. var textFile = ""
  322. for image in self.arrayImages {
  323. if #available(iOS 13.0, *) {
  324. let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
  325. let request = VNRecognizeTextRequest { (request, error) in
  326. guard let observations = request.results as? [VNRecognizedTextObservation] else {
  327. return
  328. }
  329. for currentObservation in observations {
  330. let topCandidate = currentObservation.topCandidates(1)
  331. if let recognizedText = topCandidate.first {
  332. textFile += recognizedText.string
  333. textFile += "\n"
  334. }
  335. }
  336. }
  337. request.recognitionLevel = .accurate
  338. request.usesLanguageCorrection = true
  339. try? requestHandler.perform([request])
  340. }
  341. }
  342. do {
  343. try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL , atomically: true, encoding: .utf8)
  344. } catch {
  345. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorCreationFile), forced: true)
  346. return
  347. }
  348. }
  349. /*
  350. #if GOOGLEMOBILEVISION
  351. // Text Recognition TXT
  352. if fileType == "TXT" && self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  353. var textFile = ""
  354. for image in self.arrayImages {
  355. guard let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] else {
  356. continue
  357. }
  358. for textBlock in features {
  359. guard let text = textBlock.value else {
  360. continue
  361. }
  362. textFile = textFile + text + "\n\n"
  363. }
  364. do {
  365. try textFile.write(to: NSURL(fileURLWithPath: fileNameGenerateExport) as URL , atomically: true, encoding: .utf8)
  366. } catch {
  367. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorCreationFile), forced: true)
  368. return
  369. }
  370. }
  371. }
  372. #endif
  373. */
  374. if fileType == "PDF" {
  375. let pdfData = NSMutableData()
  376. if password.count > 0 {
  377. let info: [AnyHashable: Any] = [kCGPDFContextUserPassword as String : password, kCGPDFContextOwnerPassword as String : password]
  378. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, info)
  379. } else {
  380. UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
  381. }
  382. let context = UIGraphicsGetCurrentContext()
  383. for var image in self.arrayImages {
  384. if #available(iOS 13.0, *) {
  385. if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  386. let requestHandler = VNImageRequestHandler(cgImage: image.cgImage!, options: [:])
  387. let request = VNRecognizeTextRequest { (request, error) in
  388. guard let observations = request.results as? [VNRecognizedTextObservation] else {
  389. return
  390. }
  391. for currentObservation in observations {
  392. let topCandidate = currentObservation.topCandidates(1)
  393. if let recognizedText = topCandidate.first {
  394. }
  395. }
  396. }
  397. request.recognitionLevel = .accurate
  398. request.usesLanguageCorrection = true
  399. try? requestHandler.perform([request])
  400. } else {
  401. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  402. image = changeCompressionImage(image, dpiQuality: dpiQuality)
  403. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  404. UIImageView.init(image:image).layer.render(in: context!)
  405. }
  406. } else {
  407. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  408. image = changeCompressionImage(image, dpiQuality: dpiQuality)
  409. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  410. UIImageView.init(image:image).layer.render(in: context!)
  411. }
  412. /*
  413. #if GOOGLEMOBILEVISION
  414. if self.form.formRow(withTag: "textRecognition")!.value as! Int == 1 {
  415. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  416. UIImageView.init(image:image).layer.render(in: context!)
  417. if let features = self.textDetector?.features(in: image, options: nil) as? [GMVTextBlockFeature] {
  418. for textBlock in features {
  419. for textLine in textBlock.lines {
  420. let bounds = textLine.bounds
  421. let text = textLine.value!
  422. var fontColor = UIColor.clear
  423. #if targetEnvironment(simulator)
  424. fontColor = UIColor.red
  425. #endif
  426. //print(text)
  427. let font = UIFont.systemFont(ofSize: bounds.size.height, weight: .regular)
  428. let bestFittingFont = NCUtility.sharedInstance.bestFittingFont(for: text, in: bounds, fontDescriptor: font.fontDescriptor)
  429. text.draw(in: bounds, withAttributes: [NSAttributedString.Key.font: bestFittingFont, NSAttributedString.Key.foregroundColor: fontColor])
  430. }
  431. }
  432. }
  433. } else {
  434. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  435. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  436. UIImageView.init(image:image).layer.render(in: context!)
  437. }
  438. #else
  439. image = changeImageFromQuality(image, dpiQuality: dpiQuality)
  440. image = changeCompressionImage(image, dpiQuality: dpiQuality)
  441. UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), nil)
  442. UIImageView.init(image:image).layer.render(in: context!)
  443. #endif
  444. */
  445. }
  446. UIGraphicsEndPDFContext();
  447. do {
  448. try pdfData.write(toFile: fileNameGenerateExport, options: .atomic)
  449. } catch {
  450. print("error catched")
  451. }
  452. }
  453. if fileType == "JPG" {
  454. let image = changeImageFromQuality(self.arrayImages[0], dpiQuality: dpiQuality)
  455. guard let data = image.jpegData(compressionQuality: CGFloat(0.5)) else {
  456. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorCreationFile), forced: true)
  457. return
  458. }
  459. do {
  460. try data.write(to: NSURL.fileURL(withPath: fileNameGenerateExport), options: .atomic)
  461. } catch {
  462. NCContentPresenter.shared.messageNotification("_error_", description: "_error_creation_file_", delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.info, errorCode: Int(k_CCErrorCreationFile), forced: true)
  463. return
  464. }
  465. }
  466. NCManageDatabase.sharedInstance.addMetadata(metadata)
  467. appDelegate.networkingAutoUpload.startProcess()
  468. // Request delete all image scanned
  469. let alertController = UIAlertController(title: "", message: NSLocalizedString("_delete_all_scanned_images_", comment: ""), preferredStyle: .alert)
  470. let actionYes = UIAlertAction(title: NSLocalizedString("_yes_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  471. let path = CCUtility.getDirectoryScan()!
  472. do {
  473. let filePaths = try FileManager.default.contentsOfDirectory(atPath: path)
  474. for filePath in filePaths {
  475. try FileManager.default.removeItem(atPath: path + "/" + filePath)
  476. }
  477. } catch let error as NSError {
  478. print("Error: \(error.debugDescription)")
  479. }
  480. self.dismiss(animated: true, completion: nil)
  481. }
  482. let actionNo = UIAlertAction(title: NSLocalizedString("_no_delete_", comment: ""), style: .default) { (action:UIAlertAction) in
  483. self.dismiss(animated: true, completion: nil)
  484. }
  485. alertController.addAction(actionYes)
  486. alertController.addAction(actionNo)
  487. self.present(alertController, animated: true, completion:nil)
  488. }
  489. func cancel() {
  490. self.dismiss(animated: true, completion: nil)
  491. }
  492. @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) {
  493. self.deselectFormRow(sender)
  494. let storyboard = UIStoryboard(name: "NCSelect", bundle: nil)
  495. let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController
  496. let viewController = navigationController.topViewController as! NCSelect
  497. viewController.delegate = self
  498. viewController.hideButtonCreateFolder = false
  499. viewController.includeDirectoryE2EEncryption = true
  500. viewController.includeImages = false
  501. viewController.layoutViewSelect = k_layout_view_move
  502. viewController.selectFile = false
  503. viewController.titleButtonDone = NSLocalizedString("_select_", comment: "")
  504. viewController.type = ""
  505. navigationController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
  506. self.present(navigationController, animated: true, completion: nil)
  507. }
  508. func changeImageFromQuality(_ image: UIImage, dpiQuality: typeDpiQuality) -> UIImage {
  509. let imageWidthInPixels = image.size.width * image.scale
  510. let imageHeightInPixels = image.size.height * image.scale
  511. switch dpiQuality {
  512. case typeDpiQuality.low: // 72 DPI
  513. if imageWidthInPixels > 595 || imageHeightInPixels > 842 {
  514. return CCGraphics.scale(image, to: CGSize(width: 595, height: 842), isAspectRation: true)
  515. }
  516. case typeDpiQuality.medium: // 150 DPI
  517. if imageWidthInPixels > 1240 || imageHeightInPixels > 1754 {
  518. return CCGraphics.scale(image, to: CGSize(width: 1240, height: 1754), isAspectRation: true)
  519. }
  520. case typeDpiQuality.hight: // 200 DPI
  521. if imageWidthInPixels > 1654 || imageHeightInPixels > 2339 {
  522. return CCGraphics.scale(image, to: CGSize(width: 1654, height: 2339), isAspectRation: true)
  523. }
  524. }
  525. return image
  526. }
  527. func changeCompressionImage(_ image: UIImage, dpiQuality: typeDpiQuality) -> UIImage {
  528. var compressionQuality: CGFloat = 0.5
  529. switch dpiQuality {
  530. case typeDpiQuality.low:
  531. compressionQuality = 0.1
  532. case typeDpiQuality.medium:
  533. compressionQuality = 0.5
  534. case typeDpiQuality.hight:
  535. compressionQuality = 0.9
  536. }
  537. guard let data = image.jpegData(compressionQuality: compressionQuality) else { return image }
  538. guard let imageCompressed = UIImage.init(data: data) else { return image }
  539. return imageCompressed
  540. }
  541. }
  542. class NCCreateScanDocument : NSObject, ImageScannerControllerDelegate {
  543. @objc static let sharedInstance: NCCreateScanDocument = {
  544. let instance = NCCreateScanDocument()
  545. return instance
  546. }()
  547. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  548. var viewController: UIViewController?
  549. func openScannerDocument(viewController: UIViewController) {
  550. self.viewController = viewController
  551. let scannerVC = ImageScannerController()
  552. scannerVC.imageScannerDelegate = self
  553. self.viewController?.present(scannerVC, animated: true, completion: nil)
  554. }
  555. func imageScannerController(_ scanner: ImageScannerController, didFinishScanningWithResults results: ImageScannerResults) {
  556. let fileName = CCUtility.createFileName("scan.png", fileDate: Date(), fileType: PHAssetMediaType.image, keyFileName: k_keyFileNameMask, keyFileNameType: k_keyFileNameType, keyFileNameOriginal: k_keyFileNameOriginal)!
  557. let fileNamePath = CCUtility.getDirectoryScan() + "/" + fileName
  558. let image: UIImage?
  559. if results.doesUserPreferEnhancedScan {
  560. image = results.enhancedScan?.image
  561. } else {
  562. image = results.croppedScan.image
  563. }
  564. if image != nil {
  565. do {
  566. try image!.pngData()?.write(to: NSURL.fileURL(withPath: fileNamePath))
  567. } catch { }
  568. }
  569. scanner.dismiss(animated: true, completion: {
  570. if self.viewController is DragDropViewController {
  571. (self.viewController as! DragDropViewController).loadImage()
  572. } else {
  573. let storyboard = UIStoryboard(name: "Scan", bundle: nil)
  574. let controller = storyboard.instantiateInitialViewController()!
  575. controller.modalPresentationStyle = UIModalPresentationStyle.pageSheet
  576. self.viewController?.present(controller, animated: true, completion: nil)
  577. }
  578. })
  579. }
  580. func imageScannerControllerDidCancel(_ scanner: ImageScannerController) {
  581. scanner.dismiss(animated: true, completion: nil)
  582. }
  583. func imageScannerController(_ scanner: ImageScannerController, didFailWithError error: Error) {
  584. NCContentPresenter.shared.messageNotification("_error_", description: error.localizedDescription, delay: TimeInterval(k_dismissAfterSecond), type: NCContentPresenter.messageType.error, errorCode: Int(k_CCErrorInternalError))
  585. }
  586. }