将Swift UIImage转换为PDF

3

我的应用需要将iPad相册中的UIImage出售并转换为PDF格式并保存在服务器端。

我可以选择图片并将其发送到服务器端,但后端说PDF为空(数据为null)。

我还在控制台中看到警告/错误:[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

我做错了什么?

谢谢您提前!

我尝试的代码:

//Opens gallery to select Image
func clickImage() {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    self.present(image, animated: true, completion: nil)

}

//image picker function
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
         scannedPhoto.image = image
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)

    uploadAttachment()

}

//Convert UIImage to PDF
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
}

// custom body of HTTP request to upload pdf file
func createBody(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {

    let body = NSMutableData()

    if parameters != nil {
        for (key, value) in parameters! {
            body.appendString("--\(boundary)\r\n")
            body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.appendString("\(value)\r\n")
        }
    }

    let filename = "ava.pdf"

    let mimetype = "pdf"

    body.appendString("--\(boundary)\r\n")
    body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
    body.append(imageDataKey)
    body.appendString("\r\n")

    body.appendString("--\(boundary)--\r\n")

    return body as Data

}
//Function to send converted pdf server side
func uploadAttachment() {


    let pdfdata = createPDF(image: scannedPhoto.image!)


    // url path to php file
    let url = URL(string: "\(Config.path)/uploadAva.php")!

    // declare request to this file
    var request = URLRequest(url: url)

    // declare method of passign inf to this file
    request.httpMethod = "POST"

    // param to be sent in body of request
    let param = ["AppId":Config.AppID , "uuid":Config.uuid , "Id" : userId]

    // body
    let boundary = "Boundary-\(UUID().uuidString)"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    // ... body
    request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: pdfdata! as Data, boundary: boundary) 

    // launc session
    // warning I receive here
    URLSession.shared.dataTask(with: request) { data, response, error in
        //do anything here
    }
}

请检查参数名称,使用服务器密钥,确保它是“file”,正如您所提到的。 - Van
尝试将内容类型设置为"application/pdf"而不是"pdf"。 - Van
好的,我看漏了,因为您正在使用CGContext创建图像,所以您需要更改逻辑以创建PDF。 - Van
@Van,你有没有想过如何创建PDF文件? - swift_USer
1
这个回答解决了你的问题吗?将UIImageView转换为PDF - Swift - HangarRash
显示剩余2条评论
2个回答

10

创建PDF文件数据如下:

func createPDFDataFromImage(image: UIImage) -> NSMutableData {
    let pdfData = NSMutableData()
    let imgView = UIImageView.init(image: image)
    let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
    UIGraphicsBeginPDFContextToData(pdfData, imageRect, nil)
    UIGraphicsBeginPDFPage()
    let context = UIGraphicsGetCurrentContext()
    imgView.layer.render(in: context!)
    UIGraphicsEndPDFContext()

    //try saving in doc dir to confirm:
    let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last
    let path = dir?.appendingPathComponent("file.pdf")

    do {
            try pdfData.write(to: path!, options: NSData.WritingOptions.atomic)
    } catch {
        print("error catched")
    }

    return pdfData
}

输入图像描述


0
     func exportToPDF(_ uiImage:UIImage) {
    let outputFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("testing" + ".pdf")
    let pageSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
        
    let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size:  uiImage.size))
    DispatchQueue.main.async {
        do {
            let imageBounds = CGRect(origin: .zero, size: uiImage.size)
            try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
                context.beginPage()
                uiImage.draw(in: imageBounds)
              
            })
            print("wrote file to: \(outputFileURL.path)")
            var documentoPath = outputFileURL.path
            let fileManager = FileManager.default
            if fileManager.fileExists(atPath: documentoPath){
                            let documento = NSData(contentsOfFile: documentoPath)
                            let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [documento!], applicationActivities: nil)
                UIApplication.shared.windows.first?.rootViewController?.present(activityViewController, animated: true, completion: nil)
                        }
                        else {
                            print("wrote file to: No Document \(outputFileURL.path)")
                        }
        } catch {
            print("Could not create PDF file: \(error.localizedDescription)")
        }
        
       
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接