xcode 将 uiimageview 转换为 pdf - Swift
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43912774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting uiimageview to pdf - Swift
提问by btoohey
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!
我正在尝试使用 swift 创建一个 iOS 应用程序,它可以让用户拍照或从他们的图库中选择一个图像,并将其转换为他们能够保存到手机的 pdf 文件。我的代码目前可以打开相机或图库并选择图像,但我无法将其转换为 pdf。任何提示将不胜感激,谢谢!
CameraViewController class
CameraViewController 类
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
GalleryViewController 类
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.
}
}
回答by XueYu
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.
由于苹果在 iOS 11.0 中引入了 PDFKit,你可以使用下面的代码将 uiimage 转换为 pdf,我只尝试了下面的 osx,但它应该在 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.
基本上生成PDF类似于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.
- 创建一个 PDF 上下文并将其推送到图形堆栈上。
- 创建一个页面 。
- 使用 UIKit 或 Core Graphics 例程来绘制页面的内容。
- 如果需要,添加链接。
- 根据需要重复步骤 2、3 和 4。
- 结束 PDF 上下文以从图形堆栈中弹出上下文,并根据上下文的创建方式,将结果数据写入指定的 PDF 文件或将其存储到指定的 NSMutableData 对象中。
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:
这为 PDF 文件创建了所有 NSData,然后我们需要将数据保存到文件:
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
在此处阅读更多信息:生成 PDF 内容
回答by Itachi Uchiha
PDF Generator written in swift.it will help to generate PDF with image path, image binary, image ref (CGImage)
用 swift 编写的 PDF 生成器。它将帮助生成带有图像路径、图像二进制、图像引用 (CGImage) 的 PDF
回答by Ekramul Hoque
in swift 5using PDFKit : First Import PDFKit
在使用 PDFKit 的swift 5中:首先导入 PDFKit
tan use this array Extension :
tan 使用此数组扩展名:
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 usethis :
并使用这个:
let imageArray = [UIImage(named: "1")!,UIImage(named: "2")!]
let yourPDF = imageArray.makePDF()
let imageArray = [UIImage(named: "1")!,UIImage(named: "2")!]
let yourPDF = imageArray.makePDF()