I can create pdf file but I can't find the created file on iPhone device. When I run it on simulator it's possible to find directory where it saved. Where do I have to save it to preview on iPhone?
This is the code for creating pdf file:
func createPDF() {
let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
let fmt = UIMarkupTextPrintFormatter(markupText: html)
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAtIndex: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = CGRectInset(page, 0, 0)
render.setValue(NSValue(CGRect: page), forKey: "paperRect")
render.setValue(NSValue(CGRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil)
for i in 1...render.numberOfPages() {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPageAtIndex(i - 1, inRect: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
pdfData.writeToFile("\(documentsPath)/file.pdf", atomically: true)
}
If you want to preview it, you need to either renter in in your own view in your own app, or otherwise share that pdf to other app, like share it via email, whatsapp, pages app or any other app.
For sharing that pdf, you can use UIActivityViewController.
Here, I am adding code for using the same with objective-c, you can convert it into swift as it is needed.
NSString *pdfFilePath = [documentsPath stringByAppendingPathComponent:#"file.pdf"];
NSURL *URL = [NSURL fileURLWithPath:pdfFilePath];
UIActivityViewController *activityViewController =
[[UIActivityViewController alloc] initWithActivityItems:#[#"My PDF File", URL]
applicationActivities:nil];
[self presentViewController:activityViewController
animated:YES
completion:^{
}];
Swift 3.0 code will be like:
let pdfFilePath = "path to file.pdf";
let url = NSURL.fileURL(withPath: pdfFilePath);
let activityVC = UIActivityViewController(activityItems: ["My Pdf File",url], applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil);
Use
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/file.pdf"
let myRequest = URLRequest(url: URL(fileURLWithPath: documentsPath))
webView.loadRequest(myRequest)
You can display the contents of the pdf in UIWebView.
Related
My Scenario, I am trying to save UITextView Text with Three format .pdf, .doc and .txt. Here, formate option user can choose based on alert option. Once Its saved need to show in Preview controller for file sharing. How to achieve this?
func createPDF(text:String, filename:String) {
// 1. Create Print Formatter with input text.
let formatter = UIMarkupTextPrintFormatter(markupText: text)
// 2. Add formatter with pageRender
let render = UIPrintPageRenderer()
render.addPrintFormatter(formatter, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let rect = CGRect.zero
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, rect, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
pdfData.write(toFile: "\(documentsPath)/\(filename).pdf", atomically: true)
print("saved success:\(documentsPath)\(filename)")
listFiles()
}
Try the following code :)
let txtData = Data(textView.txt.utf8)
do {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath = (documentsPath as NSString).appendingPathComponent("\(filename).pdf")
let url = URL(fileURLWithPath: filePath)
// pdfData created by your code above
// txtData for ".txt"
pdfData.write(to: url)
let activityVC = UIActivityViewController(activityItems: [url], applicationActivities: nil)
// Use your desired viewController here, or just use the rootViewController
UIApplication.shared.keyWindow?.rootViewController?.presentViewController(activityVC, animated: true, completion: nil)
} catch (let error) {
print("\(error)")
}
If i understand correct you need show documents
You can do this with QLPreviewController
More info in -
https://developer.apple.com/documentation/quicklook
https://developer.apple.com/documentation/quicklook/qlpreviewcontroller#//apple_ref/occ/cl/QLPreviewController
https://medium.com/#garg.vivek/quick-display-documents-with-qlpreviewcontroller-eaca97928c7a
QLPreviewController have sharing control
My app creates a pdf file when I hit enter button. I do this by the code below. At the moment I want to open the saved file automatically after saving.
The code for saving:
#IBAction func EnterButtonAction(_ sender: AnyObject) {
let html = "PDF FILE TITLE"
let fmt = UIMarkupTextPrintFormatter(markupText: html)
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 1000) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext();
// Save PDF file
let path = "\(NSTemporaryDirectory())MyAppFile.pdf"
pdfData.write(toFile: path, atomically: true)
print("open \(path)") // command to open the generated file
}
You can open your PDF file using UIDocumentInteractionController and find the below code:
func showFileWithPath(path: String){
let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreviewAnimated(true)
}
}
pdfData.write(toFile: path, atomically: true); is synchronous call, so you can write code to open file directly after this line, but first check if file is written successfully .
var success = pdfData.write(toFile: path, atomically: true);
if success {
//Write code to open file in Webview or UIDocumentInteractionController
}
I have an app that can view a PDF that is already stored within the project. I want to be able to create a new PDF document and store it in the app directory to later view in the already existing viewer. The PDF would be created from an array var todoList: [String] = [] that is displayed on a UITableView. I know to create a PDF, I have to create a file name, path, and directory. I don't know how to do this. I saw online reference to URL and URL request, but I'm not sure if this is the correct avenue for what I want to do. Can someone please give me some advice and guidance? Everything I can find is for Objective-C.
I used this code to create and save the file (using HTML)
func createPDF() {
let html = "<b>Hello <i>World!</i></b> <p>Generate PDF file from HTML in Swift</p>"
let fmt = UIMarkupTextPrintFormatter(markupText: html)
// 2. Assign print formatter to UIPrintPageRenderer
let render = UIPrintPageRenderer()
render.addPrintFormatter(fmt, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
pdfData.write(toFile: "\(documentsPath)/file.pdf", atomically: true)
}
Then I loaded it into UIWebView from the documents directory with this code:
func loadPDF(filename: String) {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = URL(fileURLWithPath: documentsPath, isDirectory: true).appendingPathComponent(filename).appendingPathExtension("pdf")
let urlRequest = URLRequest(url: url)
webView.loadRequest(urlRequest)
}
For Swift 3:
createPdf() {
// 1. Create Print Formatter with input text.
let formatter = UIMarkupTextPrintFormatter(markupText: textView.text)
// 2. Add formatter with pageRender
let render = UIPrintPageRenderer()
render.addPrintFormatter(formatter, startingAtPageAt: 0)
// 3. Assign paperRect and printableRect
let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi
let printable = page.insetBy(dx: 0, dy: 0)
render.setValue(NSValue(cgRect: page), forKey: "paperRect")
render.setValue(NSValue(cgRect: printable), forKey: "printableRect")
// 4. Create PDF context and draw
let rect = CGRect.zero
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, rect, nil)
for i in 1...render.numberOfPages {
UIGraphicsBeginPDFPage();
let bounds = UIGraphicsGetPDFContextBounds()
render.drawPage(at: i - 1, in: bounds)
}
UIGraphicsEndPDFContext();
// 5. Save PDF file
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
pdfData.write(toFile: "\(documentsPath)/new.pdf", atomically: true)
print("saved success")
}
I need to generate a report as pdf an print it. Im generating a view with all the information and converting it to pdf and then showing the pdf file in a UIWebView. But when I see the Pdf file in the UIWebView, the file is not complete (a big part of the right area and the bot area are cut). I don't know if my UIView is too big when I'm converting it to Pdf or the UIWebView is cutting it.
PDF Function
func createPDFfromUIView(aView: UIView) //-> UIImage
{
let pdfData = NSMutableData()
UIGraphicsBeginPDFContextToData(pdfData, aView.frame, nil)
UIGraphicsBeginPDFPage()
let pdfContext = UIGraphicsGetCurrentContext();
aView.layer.renderInContext(pdfContext!)
UIGraphicsEndPDFContext();
let documentsDirectory: NSString = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask,true)[0] as NSString
let dataPath = documentsDirectory.stringByAppendingPathComponent("/JamaWEpdf")
if (!NSFileManager.defaultManager().fileExistsAtPath(dataPath as String)) {
do{
try NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil)
}
catch _{}
}
let filePath = "\(dataPath)entry\(entry1.entryId)pdf.pdf"
pdfData.writeToFile(filePath, atomically: true)
let webView = UIWebView()
webView.loadRequest(NSURLRequest(URL: NSURL(fileURLWithPath: filePath)))
webView.frame = self.view.frame
self.view.addSubview(webView)
}
I don't know if my approach is right. The UIView size is w: 2480 h: 3508.
I was generating the view programmatically so when this line was executed:
UIGraphicsBeginPDFContextToData(pdfData, aView.frame, nil)
the frame was not rendered or something. So instead I use a CGRect with the size I wanted and it work:
UIGraphicsBeginPDFContextToData(pdfData, CGRect(x: 0, y: 0, width: 2480, height: 3508), nil)
I need to send an image from my app with a text, I know how to send just an image or just a text, but I don't know how to combine both of them.
Just an Image:
let image = UIImage(named: "Image") // replace that with your UIImage
let filename = "myimage.wai"
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, false)[0] as! NSString
let destinationPath = documentsPath.stringByAppendingString("/" + filename).stringByExpandingTildeInPath
UIImagePNGRepresentation(image).writeToFile(destinationPath, atomically: false)
let fileUrl = NSURL(fileURLWithPath: destinationPath)! as NSURL
documentController = UIDocumentInteractionController(URL: fileUrl)
documentController.delegate = self
documentController.UTI = "net.whatsapp.image"
documentController.presentOpenInMenuFromRect(CGRectZero, inView: self.view, animated: false)
Just a text:
var whatsappURL = NSURL(string: "whatsapp://send?text=hello,%20world")
if UIApplication.sharedApplication().canOpenURL(whatsappURL!) {
UIApplication.sharedApplication().openURL(whatsappURL!)
}
How can I send an image with a text?
EDIT #1
I found a code that share an image with text to whatsapp but it's in java, can you translate it to swift?
Intent whatsappIntent = new Intent(android.content.Intent.ACTION_SEND);
whatsappIntent.setType("image/*");
whatsappIntent.putExtra(Intent.EXTRA_TEXT, "Hello World");
whatsappIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file)); //add image path
startActivity(Intent.createChooser(share, "Share image using"));
try {
activity.startActivity(whatsappIntent);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(activity, "Whatsapp have not been installed.", Toast.LENGTH_SHORT).show();
}
You can post Image or Text on WhatsApp. However you can't post both at a time as whatsapp does not provide any API that you can add caption and post image with text.
Now there is an api available for interacting with WhatsApp:
http://www.whatsapp.com/faq/en/iphone/23559013
Also Find below helpful answer:
You can use the UIDocumentInteractionController as mentioned in the 2nd answer to this question as of August 4, 2014: Share image/text through WhatsApp in an iOS app
Hope this will help.
A version of your share image code for swift 3:
let image = myUIImageVariable
let filename = "myimage.wai"
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, false)[0] as NSString
var destinationPath = documentsPath.appending("/" + filename) as NSString
destinationPath = destinationPath.expandingTildeInPath as NSString
let fileUrl = NSURL(fileURLWithPath: destinationPath as String) as NSURL
do{
try UIImagePNGRepresentation(image!)?.write(to: fileUrl as URL, options: Data.WritingOptions.atomic)
}
catch {}
let documentController = UIDocumentInteractionController(url: fileUrl as URL)
documentController.delegate = self
documentController.uti = "net.whatsapp.image"
documentController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: false)
Still does not seem work even for just sharing an image, but may save someone's time