NCCreateFormUploadScanDocument.swift 34 KB

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