Convert RTF to JPG in Swift
Rich Text Format (RTF) files were created by Microsoft as a data format with the ability to easily transfer documents to Microsoft applications. However, while RTF may interact well with Microsoft programs, it often runs into compatibility issues with other programs or applications; due to this converting RTF to another format is frequently the best move. In this brief tutorial, we will provide an API solution that will allow you to avoid the headache of manually converting an RTF document to a JPG/JPEG image file by automating the process for you.
To run the API in Swift, you will need to input the RTF file and API key into the below example code; there is also an option to set your quality level between 1–100 (default is 75).
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endifvar semaphore = DispatchSemaphore (value: 0)let parameters = [
[
"key": "inputFile",
"src": "/path/to/file",
"type": "file"
]] as [[String : Any]]let boundary = "Boundary-\(UUID().uuidString)"
var body = ""
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if param["contentType"] != nil {
body += "\r\nContent-Type: \(param["contentType"] as! String)"
}
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body += "\r\n\r\n\(paramValue)\r\n"
} else {
let paramSrc = param["src"] as! String
let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
let fileContent = String(data: fileData, encoding: .utf8)!
body += "; filename=\"\(paramSrc)\"\r\n"
+ "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
}
}
}
body += "--\(boundary)--\r\n";
let postData = body.data(using: .utf8)var request = URLRequest(url: URL(string: "https://api.cloudmersive.com/convert/rtf/to/jpg")!,timeoutInterval: Double.infinity)
request.addValue("<integer>", forHTTPHeaderField: "quality")
request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
request.addValue("YOUR-API-KEY-HERE", forHTTPHeaderField: "Apikey")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")request.httpMethod = "POST"
request.httpBody = postDatalet task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print(String(describing: error))
semaphore.signal()
return
}
print(String(data: data, encoding: .utf8)!)
semaphore.signal()
}task.resume()
semaphore.wait()
This hassle-free process will instantly deliver you an array of JPG/JPEG images, one for each page of the document. If you need to retrieve your API key, you can do so by registering for a free account on the Cloudmersive website; this provides 800 calls/month across any of our APIs.