NCCreateFormUploadScanDocument.swift 34 KB

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