Convert a DOCX File to JPG in Swift
While Word documents are a great format for creating a wide variety of material, their internal composition ensures that they are are never easy to perform a manual document conversion on. If a project or application requires the conversion of DOCX files into the JPG/JPEG image format, we have a tool that can simplify the process. The following API can be used in Swift to convert a Word document to a JPG/JPEG image array, and even allows for customization of image quality by setting a quality level between 1 (highest compression) and 100 (lowest compression).
Now, all we need to call the function is the target DOCX file, your API key, and the quality level (default is 75) to input into the following code:
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/docx/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()
Your new JPG/JPEG file will be delivered in seconds, cutting your processing time down and allowing you to focus on other tasks. To retrieve your API key, visit the Cloudmersive website to register for a free account; this provides 800 monthly calls across our library of APIs.