How to access created pdf document on iOS? - ios

My app has an action that creates pdf file. After creating file on simulator I can access the created file on Mac but on iPhone I can not. Even I have searched but couldn't find. On Acrobat Reader neither.
So what can I do with this created pdf file? Should I convert it ePub or something?
This is my code for creating pdf:
func createPdfFromView(_ imageView: UIImageView, saveToDocumentsWithFileName fileName: String)
{
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, imageView.bounds, nil)
UIGraphicsBeginPDFPage()
let pdfContext = UIGraphicsGetCurrentContext()
if (pdfContext == nil)
{
return
}
imageView.layer.render(in: pdfContext!)
UIGraphicsEndPDFContext()
}
#IBAction func createPdfAction(_ sender: UIButton) {
createPdfFromView(ImageDisplay, saveToDocumentsWithFileName: "")
}

Write the PDF Data as a file in local path
private var pdfData: NSMutableData!
private var filPath: NSString!
private var docController: UIDocumentInteractionController!
func writeDataAsFile()
{
//Search for local path
let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let directoryPath = paths[0] as NSString
//Appending file name to be saved in directory path
filPath = directoryPath.appendingPathComponent("TestPDF.pdf") as NSString!
//Check file is already exist in path
let isFileExists = FileManager.default.fileExists(atPath: filPath as String)
if(!isFileExists)
{
//pdfData is NSData/NSMutableData, Write to the filepath
pdfData.write(toFile: filPath as String, atomically: true)
}
}
UIDocumentInteractionController provides in-app support for managing user interactions with files in the local system
#IBAction func goPDF(sender: UIButton) {
docController = UIDocumentInteractionController.init(url: NSURL.fileURL(withPath: filPath as String, isDirectory: true))
docController.delegate = self
docController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)
}
UIDocumentInteractionControllerDelegate to handle document interactions
func documentInteractionController(_ controller: UIDocumentInteractionController, willBeginSendingToApplication application: String?) {
print("willBeginSendingToApplication")
}
func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
print("didEndSendingToApplication")
}
func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
print("documentInteractionControllerDidDismissOpenInMenu")
}
Using delegate in your ViewController should conforms the UIDocumentInteractionControllerDelegate like this, for example, in ViewController
import UIKit
class FirstViewController: UIViewController, UIDocumentInteractionControllerDelegate {
}
For open PDF in iBooks the menu will provide "Import with iBooks" option. This option will lead to open the PDF in iBooks after importing.

Related

Hide or disable share button from uidocumentinteractioncontroller in swift 5

In my application, I'm using the QuickLook framework to view the document files such as pdf, ppt, doc, etc. etc. But due to privacy concerns, I don't want that the user can share this document with others so please let me know how to disable/hide the share button and also the copy-paste option.
I know this question can be asked by a number of times and tried many solutions but nothing works for me
hide share button from QLPreviewController
UIDocumentInteractionController remove Actions Menu
How to hide share button in QLPreviewController using swift?
Hide right button n QLPreviewController?
Please suggest to me to achieve this.
Here is my demo code:
import UIKit
import QuickLook
class ViewController: UIViewController {
lazy var previewItem = NSURL()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func displayLocalFile(_ sender: UIButton){
let previewController = QLPreviewController()
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDf.pdf")
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}
#IBAction func displayFileFromUrl(_ sender: UIButton){
// Download file
self.downloadfile(completion: {(success, fileLocationURL) in
if success {
// Set the preview item to display======
self.previewItem = fileLocationURL! as NSURL
// Display file
let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)
}else{
debugPrint("File can't be downloaded")
}
})
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle.main.path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func downloadfile(completion: #escaping (_ success: Bool,_ fileLocation: URL?) -> Void){
let itemUrl = URL(string: "https://images.apple.com/environment/pdf/Apple_Environmental_Responsibility_Report_2017.pdf")
// then lets create your document folder url
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
// lets create your destination file url
let destinationUrl = documentsDirectoryURL.appendingPathComponent("filename.pdf")
// to check if it exists before downloading it
if FileManager.default.fileExists(atPath: destinationUrl.path) {
debugPrint("The file already exists at path")
completion(true, destinationUrl)
// if the file doesn't exist
} else {
// you can use NSURLSession.sharedSession to download the data asynchronously
URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in
guard let tempLocation = location, error == nil else { return }
do {
// after downloading your file you need to move it to your destination url
try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
print("File moved to documents folder")
completion(true, destinationUrl)
} catch let error as NSError {
print(error.localizedDescription)
completion(false, nil)
}
}).resume()
}
}
}
//MARK:- QLPreviewController Datasource
extension ViewController: QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
controller.navigationItem.rightBarButtonItem = nil
return self.previewItem as QLPreviewItem
}
}
Please provide your suggestion to do so or any other framework to view different file formats.
Here is the image
Find below adopted my approach to your code (with modifications to test locally, but the code should be clear). The idea is
a) to override, which is completely allowed by API, needed classes to intercept modification
b) to use intentionally own UINavigationController, as only one navigation controller can be in stack
So here is code:
// Custom navigation item that just blocks adding right items
class MyUINavigationItem: UINavigationItem {
override func setRightBarButtonItems(_ items: [UIBarButtonItem]?, animated: Bool) {
// forbidden to add anything to right
}
}
// custom preview controller that provides own navigation item
class MyQLPreviewController: QLPreviewController {
private let item = MyUINavigationItem(title: "")
override var navigationItem: UINavigationItem {
get { return item }
}
}
class MyViewController : UIViewController, QLPreviewControllerDataSource {
lazy var previewItem = NSURL()
override func loadView() {
let view = UIView()
view.backgroundColor = .white
// just stub testing code
let button = UIButton(type: .roundedRect)
button.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
button.setTitle("Show", for: .normal)
button.addTarget(self, action:
#selector(displayLocalFile(_:)), for: .touchDown)
view.addSubview(button)
self.view = view
}
#objc func displayLocalFile(_ sender: UIButton){
let previewController = MyQLPreviewController() // << custom preview
// now navigation item is fully customizable
previewController.navigationItem.title = "samplePDF.pdf"
previewController.navigationItem.leftBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .done, target: self,
action: #selector(closePreview(_:)))
// wrap it into navigation controller
let navigationController = UINavigationController(rootViewController: previewController)
// Set the preview item to display
self.previewItem = self.getPreviewItem(withName: "samplePDF.pdf")
previewController.dataSource = self
// present navigation controller with preview
self.present(navigationController, animated: true, completion: nil)
}
#objc func closePreview(_ sender: Any?) {
self.dismiss(animated: true) // << dismiss preview
}
func getPreviewItem(withName name: String) -> NSURL{
// Code to diplay file from the app bundle
let file = name.components(separatedBy: ".")
let path = Bundle(for: type(of: self)).path(forResource: file.first!, ofType: file.last!)
let url = NSURL(fileURLWithPath: path!)
return url
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return self.previewItem as QLPreviewItem
}
}

How to use UIDocumentInteractionController?

I have created a program that loads PDF files. I want when the user is editing that they can publish the file anywhere in PDF format.
Do I use UIDocumentInteractionController or use UIActivityViewController?
Here is the code:
import UIKit
import PDFKit
#available(iOS 11.0, *)
#available(iOS 11.0, *)
class PDFViewControllerEN: UIViewController {
var document: UIDocumentInteractionController!
override func viewDidLoad() {
super.viewDidLoad()
// retrieve URL to file in main bundle`
}
#IBOutlet var pdfview: UIView!
#IBAction func share(_ sender: UIButton) {
}
#IBAction func doAction2(_ sender: UIBarButtonItem) {
document.presentOptionsMenu(from: view.bounds, in: view, animated: true)
}
override func viewWillAppear(_ animated: Bool) {
//Here you are going to display your PdfController
//PDFController that is seprate class you had created to show pdf file being opened
//i.e
//check which button was being selected
switch ButtonSelected.Tag {
case 0:
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN1", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
// document.presentPreview(animated: true)
break
case 1:
//here control when you selected button with tag 0
//here need to open pdf AR2
//set Frame here all bounds
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN2", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
break
case 2:
//here control when you selected button with tag 0
//here need to open pdf AR2
//set Frame here all bounds
var document: UIDocumentInteractionController = {
let pdfView = PDFView(frame: UIScreen.main.bounds)
let url = Bundle.main.url(forResource: "EN3", withExtension: "pdf")
let vc = UIDocumentInteractionController(url: url!)
pdfView.document = PDFDocument(url: url!)
view.addSubview(pdfView)
vc.delegate = self
return vc
}()
break
default:
//Error Case
print("No tag Value Available")
}
}
}
#available(iOS 11.0, *)
extension PDFViewControllerEN: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}
I have tried and explained in detail about UIDocumentInteractionController. Refer this link if you want to check the details.
https://medium.com/if-let-swift-programming/managing-files-in-ios-dfcdfdc1f426
Code
extension ViewController {
/// This function will set all the required properties, and then provide a preview for the document
func share(url: URL) {
documentInteractionController.url = url
documentInteractionController.uti = url.typeIdentifier ?? "public.data, public.content"
documentInteractionController.name = url.localizedName ?? url.lastPathComponent
documentInteractionController.presentPreview(animated: true)
}
/// This function will store your document to some temporary URL and then provide sharing, copying, printing, saving options to the user
func storeAndShare(withURLString: String) {
guard let url = URL(string: withURLString) else { return }
/// START YOUR ACTIVITY INDICATOR HERE
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
let tmpURL = FileManager.default.temporaryDirectory
.appendingPathComponent(response?.suggestedFilename ?? "fileName.png")
do {
try data.write(to: tmpURL)
} catch {
print(error)
}
DispatchQueue.main.async {
/// STOP YOUR ACTIVITY INDICATOR HERE
self.share(url: tmpURL)
}
}.resume()
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
/// If presenting atop a navigation stack, provide the navigation controller in order to animate in a manner consistent with the rest of the platform
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
guard let navVC = self.navigationController else {
return self
}
return navVC
}
}
extension URL {
var typeIdentifier: String? {
return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
}
var localizedName: String? {
return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
}
}
Calling
#IBAction func showOptionsTapped(_ sender: UIButton) {
/// Passing the remote URL of the file, to be stored and then opted with mutliple actions for the user to perform
storeAndShare(withURLString: "https://images5.alphacoders.com/581/581655.jpg")
}
Note
https://www.bignerdranch.com/blog/working-with-the-files-app-in-ios-11/
Before your files can appear in the Files app, you must indicate that your app supports Open in Place and File Sharing Enabled. These options are configured using keys in your Info.plist file.
The first key is UIFileSharingEnabled, which enables iTunes sharing of files in your Documents folder.
The second key is LSSupportsOpeningDocumentsInPlace, which grants the local file provider access to files in your Documents folder.
Add these keys to your Info.plist and set their values to YES.
Using UIDocumentInteractionController is quite easy. You just need to know the url of your file, then you present the menu:
/// Needs to be global, otherwise the controller will be destroyed when the file is handed over to target application
var documentInteractionController: UIDocumentInteractionController!
class MyViewController: UIViewController {
var url: URL
...
#IBAction func share(_ sender: UIBarButtonItem) {
documentInteractionController = UIDocumentInteractionController()
documentInteractionController.url = url
documentInteractionController.uti = url.uti
documentInteractionController.presentOptionsMenu(from: sender, animated: true)
}
}
extension URL {
var uti: String {
return (try? self.resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier ?? "public.data"
}
}
Silly case but might help to someone.
To anyone who can't save files check if your controller is alive. My problem was that my UIDocumentInteractionController was destroyed after it was closed.
Here's how my function looked like:
private func showDocumentInteractionController(url: URL) {
let documentInteractionController = UIDocumentInteractionController(url: url)
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
documentInteractionController.delegate = self
}
The fix is to make sure that UIDocumentInteractionController is alive after it closes:
class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {
private let documentInteractionController = UIDocumentInteractionController()
private func showDocumentInteractionController(url: URL) {
documentInteractionController.url = url
documentInteractionController.presentOptionsMenu(from: view.frame, in: view, animated: true)
documentInteractionController.delegate = self
}
}
This should work which shows a PDF file:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in
guard let path = Bundle.main.url(forResource: "YOUR_PDF_FILE_NAME_WITHOUT_EXTENSION", withExtension: "pdf") else { return }
let documentInteractionController = UIDocumentInteractionController.init(url: path)
documentInteractionController.delegate = self
documentInteractionController.presentPreview(animated: true)
}
}
}
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
}
}

How to display pdf from network in iOS [duplicate]

This question already has answers here:
How to display remote document using QLPreviewController in swift
(2 answers)
Closed 5 years ago.
Currently I am using QuickLook module to open pdf from network, but it shows a blank page with error "Couldn't issue file extension for url: https://testing-xamidea.s3.amazonaws.com/flowchart/20171103182728150973368.pdf" in console. I guess QuickLook can only open locally saved Pdf files. Is is possible to load pdf from network using quicklook? . This is my code so far- {fileURL contains url from which pdf is to be loaded, also ive set the delegates etc)
extension FlowchartVC:QLPreviewControllerDelegate,QLPreviewControllerDataSource {
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let url : NSURL! = NSURL(string : fileURL)
return url
}
func previewControllerWillDismiss(_ controller: QLPreviewController) {
self.dismiss(animated: true, completion: nil)
}
}
You need to save the file to disk first and then you can present the pdf. There is no way to present it with QuickLook if the file is in a remote location. The file is saved in the temporary directory. Here is an example view controller showing how it could be done.
Swift 5:
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
// Remote url pdf I found on google
let itemURL = URL(string: "https://www.ets.org/Media/Tests/GRE/pdf/gre_research_validity_data.pdf")!
var fileURL: URL?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let quickLookController = QLPreviewController()
quickLookController.dataSource = self
do {
// Download the pdf and get it as data
// This should probably be done in the background so we don't
// freeze the app. Done inline here for simplicity
let data = try Data(contentsOf: itemURL)
// Give the file a name and append it to the file path
fileURL = FileManager().temporaryDirectory.appendingPathComponent("sample.pdf")
if let fileUrl = fileURL {
// Write the pdf to disk in the temp directory
try data.write(to: fileUrl, options: .atomic)
}
// Make sure the file can be opened and then present the pdf
if QLPreviewController.canPreview(fileUrl as QLPreviewItem) {
quickLookController.currentPreviewItemIndex = 0
present(quickLookController, animated: true, completion: nil)
}
} catch {
// cant find the url resource
}
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return fileURL! as QLPreviewItem
}
}
Swift 3:
import UIKit
import QuickLook
class ViewController: UIViewController, QLPreviewControllerDataSource {
// Remote url pdf I found on google
let itemURL = URL(string: "https://www.ets.org/Media/Tests/GRE/pdf/gre_research_validity_data.pdf")!
var fileURL = URL(string: "")
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let quickLookController = QLPreviewController()
quickLookController.dataSource = self
do {
// Download the pdf and get it as data
// This should probably be done in the background so we don't
// freeze the app. Done inline here for simplicity
let data = Data(contentsOf: itemURL)
// Give the file a name and append it to the file path
fileURL = FileManager().temporaryDirectory.appendingPathComponent("sample.pdf")
// Write the pdf to disk
try data?.write(to: fileURL!, options: .atomic)
// Make sure the file can be opened and then present the pdf
if QLPreviewController.canPreview(fileUrl as QLPreviewItem) {
quickLookController.currentPreviewItemIndex = 0
present(quickLookController, animated: true, completion: nil)
}
} catch {
// cant find the url resource
}
}
func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return 1
}
func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
return fileURL! as QLPreviewItem
}
}
Here is the file showing in the simulator. Using a sample project with just that code.

Converting uiimageview to pdf - Swift

I am trying to create an iOS app using swift that will let the user either take a photo or choose an image from their gallery, and convert it to a pdf file that they are able to save to their phone. My code currently works to open either the camera or the gallery and choose an image, but I'm unable to convert it to pdf.
Any tips would be really appreciated, thanks!
CameraViewController class
import UIKit
class CameraViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
#IBOutlet weak var myImg: UIImageView!
#IBAction func takePhoto(_ sender: AnyObject) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
myImg.contentMode = .scaleToFill
myImg.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
#IBAction func savePhoto(_ sender: AnyObject) {
let imageData = UIImagePNGRepresentation(myImg.image!)
let compressedImage = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedImage!, nil, nil, nil)
let alert = UIAlertController(title: "Saved", message: "Your image has been saved", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(okAction)
self.present(alert, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
GalleryViewController class
import UIKit
class GalleryViewController: UIViewController {
#IBOutlet weak var myImg: UIImageView!
#IBAction func pickPhoto(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
myImg.contentMode = .scaleToFill
myImg.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Answers Updated:
Since Apple introduced PDFKit to iOS 11.0, you can use the code below to convert uiimage to pdf, I only tried the osx below, but it should work the same way on iOS.
// Create an empty PDF document
let pdfDocument = PDFDocument()
// Load or create your UIImage
let image = UIImage(....)
// Create a PDF page instance from your image
let pdfPage = PDFPage(image: image!)
// Insert the PDF page into your document
pdfDocument.insert(pdfPage!, at: 0)
// Get the raw data of your PDF document
let data = pdfDocument.dataRepresentation()
// The url to save the data to
let url = URL(fileURLWithPath: "/Path/To/Your/PDF")
// Save the data to the url
try! data!.write(to: url)
================================================
Actually there're a lot similar questions and good enough answers. Let me try to answer this again.
Basically generating PDF is similar to the drawing in iOS.
Create a PDF context and push it onto the graphics stack.
Create a page .
Use UIKit or Core Graphics routines to draw the content of the page.
Add links if needed .
Repeat steps 2, 3, and 4 as needed.
End the PDF context to pop the context from the graphics stack and, depending on how the context was created, either write the resulting data to the specified PDF file or store it into the specified NSMutableData object.
So the most simple way would be something like this:
func createPDF(image: UIImage) -> NSData? {
let pdfData = NSMutableData()
let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)
let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
pdfContext.draw(image.cgImage!, in: mediaBox)
pdfContext.endPage()
return pdfData
}
That created all the NSData for the PDF file, then we need to save the data to file:
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("myFileName.pdf")
try createPDF(image: someUIImageFile)?.write(to: docURL, atomically: true)
Read more here: Generating PDF Content
in swift 5 using PDFKit :
First Import PDFKit
Then use this array Extension :
import UIKit
import PDFKit
extension Array where Element: UIImage {
func makePDF()-> PDFDocument? {
let pdfDocument = PDFDocument()
for (index,image) in self.enumerated() {
let pdfPage = PDFPage(image: image)
pdfDocument.insert(pdfPage!, at: index)
}
return pdfDocument
}
}
and use this :
let imageArray = [UIImage(named: "1")!,UIImage(named: "2")!] let yourPDF = imageArray.makePDF()
Swift 5 We will use UIGraphicsPDFRenderer() class and it will work for iOS 10+
let image = results.croppedScan.image
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let docURL = documentDirectory.appendingPathComponent("Scanned-Docs.pdf")
let outputFileURL: URL = docURL
let imageBounds = CGRect(origin: .zero, size: image.size)
let pdfRenderer = UIGraphicsPDFRenderer(bounds: imageBounds)
do {
try pdfRenderer.writePDF(to: outputFileURL) { context in
context.beginPage()
results.croppedScan.image.draw(in: imageBounds)
}
} catch {
print("Could not create PDF file: \(error)")
}
print("save at ===\(outputFileURL)")
//Show PDF in Controller
let dc = UIDocumentInteractionController(url: outputFileURL)
dc.delegate = self
dc.presentPreview(animated: true)
PDF Generator written in swift.it will help to generate PDF with image path, image binary, image ref (CGImage)
https://github.com/sgr-ksmt/PDFGenerator

How do I Save and Load an Image in a UIImageView? [duplicate]

This question already has answers here:
how to load image from local path ios swift (by path)
(8 answers)
Closed 5 years ago.
I am attempting to create a application in xcode 8 swift 3 where the user adds an image using a imagePickerController then when the user clicks either save or exits the imagePickerController I want the image to be saved locally, so next time the app is loaded (for example after a device restart) the image is there. Just to be clear I Do Not want to save the image to the camera roll. Here is my code thus far without any save or load methods, (just the save button reference) any help would be very appreciated as I have been attempting to do this for a long while.
import UIKit
class timetable: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
#IBOutlet var imageviewtimetable: UIImageView!
#IBAction func save(_ sender: Any) {
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func selectImageFromPhotoLibrary(_ sender: Any) {
let imagePickerController = UIImagePickerController()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
dismiss(animated: true, completion:nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
imageviewtimetable.image = selectedImage
dismiss(animated: true,completion:nil)
}
}
For info : click here
Save image in Document Directory
func saveImageDocumentDirectory() {
let fileManager = NSFileManager.defaultManager()
let paths = (getDirectoryPath() as NSString).stringByAppendingPathComponent("apple.jpg")
let image = UIImage(named: "apple.jpg")
print(paths)
let imageData = UIImageJPEGRepresentation(image!, 0.5)
fileManager.createFileAtPath(paths as String, contents: imageData, attributes: nil)
}
Get Document Directory Path
func getDirectoryPath() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
return documentsDirectory
}
get Image from document directory
func getImage(){
let fileManager = NSFileManager.defaultManager()
let imagePath = (self.getDirectoryPath() as NSString).stringByAppendingPathComponent("apple.jpg")
if fileManager.fileExistsAtPath(imagePath){
self.imageView.image = UIImage(contentsOfFile: imagePath)
} else {
print("No Image")
}
}
create Directory
func createDirectory(){
let fileManager = NSFileManager.defaultManager()
let paths = getDirectoryPath() as NSString).stringByAppendingPathComponent("customDirectory")
if !fileManager.fileExistsAtPath(paths){
try! fileManager.createDirectoryAtPath(paths, withIntermediateDirectories: true, attributes: nil)
} else {
print("Already dictionary created.")
}
}

Resources