How to generate a PDF with SimplePDF in Swift - swift

I've got a problem regarding how to use SimplePDF.
I would like to export a PDF file from my application when I press a simple UIButton.
Now I try to use the standard code give by SimplePDF but I still have a problem :
The code :
let a4PaperSize = CGSize(width: 210, height: 297)
let pdf = SimplePDF(pageSize: a4PaperSize)
pdf.setContentAlignment(.center)
// add logo image
let logoImage = UIImage(named:"train-icon180.png")!
pdf.addImage(logoImage)
// [...]
// Generate PDF data and save to a local file.
// Here is where I've got a problem
if let documentDirectories = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let fileName = "\(ReceptionOuvertureLigne).pdf"
let documentsFileName = documentDirectories + "/" + fileName
let pdfData = pdf.generatePDFdata()
do{
try pdfData.writeToFile(documentsFileName, options: .DataWritingAtomic)
print("\nThe generated pdf can be found at:")
print("\n\t\(documentsFileName)\n")
}catch{
print(error)
}
In fact the line : try pdfData.writeToFile(documentsFileName, options: .DataWritingAtomic) in the PDF generating part result by an error :
Value of type 'Data' has no member 'writeToFile'
I don't know how to solve it ...

Related

swift save file after download Alamofire

download and save file
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
// var fileURL = self.createFolder(folderName: downloadFolderName)
var fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = URL(string : currentFile.link )
fileURL = fileURL.appendingPathComponent((fileName?.lastPathComponent)!)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(currentDownloadedFile.link , to: destination).response(completionHandler: { (DefaultDownloadResponse) in
print("res ",DefaultDownloadResponse.destinationURL!);
completion(true)
})
but when i wont to check file in this dirrectory i get nil
let filemanager:FileManager = FileManager()
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = filemanager.enumerator(atPath: fileURL.absoluteString) // = nil
while let file = files?.nextObject() {
print(file)
}
if i save local path to file and after reload app wont to share it -> "share" app cant send file (mb cant found it)
can u pls help me. how it works ? why when i print all files he didnt find it? how to save file who after reboot app it will be saved in same link
You are using the wrong API
For file system URLs use always path, absoluteString returns the full string including the scheme (e. g. file:// or http://)
let files = filemanager.enumerator(atPath: fileURL.path)

How to share Image in Swift

I tried to share a image that I generate by my own. However when I tried to share the image it doesn't works well.
here is the code to share
func shareQR(){
//mainImage is the view that hold the image I want to share
let tempImage = view.mainImage.image
let imageToShare = [ tempImage ]
let activityViewController = UIActivityViewController(activityItems: imageToShare as! [UIImage], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = self.view
activityViewController.excludedActivityTypes = [ UIActivityType.airDrop ]
self.present(activityViewController, animated: true, completion: nil)
}
So I tried to debug and the result is my tempImage value is the same with the one I want to share. And then I tried to hardcode the image and become let tempImage = UIImage(named: "image.png")
and tap share button, and it works perfectly.
So I figured out, did I have to save my image to local file first and then called it ?
If yes how ? I tried use this code but failed.
// Create path.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let filePath = "\(paths[0])/temp.png"
// Save image.
UIImagePNGRepresentation(image!)?.write(to: filePath)
the error is : cannot convert value of type 'String' to expected
argument type 'URL' in this line
UIImagePNGRepresentation(tempImage!)?.write(to: filePath)
Or maybe I dont need to save image? how ?
Thank you
It seems like your variable image is a String variable instead of a UIImage (hence the error that you have posted). To confirm this theory, add the following line in your code
print(tempImage)
after
let tempImage = view.mainImageimage
If it prints the image name, then your variable is a String variable. If it prints something along the lines of UIImage, then it's an actual image and we can further investigate the issue. Let me know what you get in result
Edit:
To store a file locally, use the following code
if let data = UIImagePNGRepresentation(tempImage) {
let filename = getDocumentsDirectory().appendingPathComponent("copy.png")
try? data.write(to: filename)
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}

Swift3 : How to load html file to WKWebview from document directory

Can anyone explain how to load local html file to WKWebView?
I tried with the below code works well in simulator but not on device
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath: String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath + "/" + "\(NameF.fileName)/\(NameF.Languages)/page_\(i + 1 ).html")
print("D2\(destinationURLForFile)")
let request = NSURLRequest(url: destinationURLForFile)
webView!.load(request as URLRequest)
Any suggestions would be helpful!
Thank you for your response guys and for who tried my question.Finally found the answer by opening the local file and read its content and then send that string into a WKWebview
And the piece of code is
do{
let fileName = try String(contentsOf: destinationURLForFile)
print("fileName is equal to\(fileName)")
webView.loadHTMLString(fileName, baseURL: destinationURLForFile)
}catch{
}

Issue with loading file from disk

Ok so this one has had me scratching my head for a while.
I have a png file that I write out to disk. I get the data by:
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
I do a try catch and everything seems to work. The resulting filename is:
file:///var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png
The problem comes when I try to load that image back from the disk.
When I get a list of all files in the documents directory I get:
[file:///private/var/mobile/Containers/Data/Application/C6B796E8-2DB6-45A4-9B18-EF808B8CA3CA/Documents/580420d51800cd826a7e217c.png]
The only difference I can see is the 'private' part of the filepath. When I try to check to see if the file exists using the filepath I get back from appending the filename (the one without the private part) I get false.
What am I missing?
Swift 3/4 code
Let us assume the method getDocumentsDirectory() is defined as follows
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
In order to save the image
let data = UIImagePNGRepresentation(scaledImage!)
let filename = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png")
try? data?.write(to: filename)
And your image is saved in Documents Directory
Now in order to load it back
let imagePath = getDocumentsDirectory().appendingPathComponent("\(record.uid!).png").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: imagePath){
print("Image Present")
//load it in some imageView
}else {
print("No Image")
}

how to convert .pdf file to base64 string in swift 2.0?

I have to upload document in swift , I have to do this using the iCloud , so that I can upload file to my server using icloud
Swift 3.x
let filePath = ... //URL of the PDF
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
Drag the pdf file to the project or five the path before to hold
let url1 = Bundle.main.url(forResource: "pdffilename without extension", withExtension: "pdf")
let one1 = NSData(contentsOf: url1!)
let pdfstring:String = one1!.base64EncodedString(options: .endLineWithLineFeed)
print(pdfstring)
let filePath = "" // real path of the pdf file
let fileData = NSData(contentsOfFile: path)
let fileStream = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) // base64 string
Where would you pick the file, That file path has to be given:
First generate the base64 string you can use it
Then generate the bytes
Which one comfortable could use it.
do {
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let decodeData = Data(base64Encoded: fileStream, options: .ignoreUnknownCharacters)
body.append(decodeData!)
}
catch { }