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