Home > Net >  Uploading a PDF File From Swift Yields a Blank PDF
Uploading a PDF File From Swift Yields a Blank PDF

Time:10-08

Im trying to upload a PDF generated from a UIImage. I take a picture using my camera framework, uploads all ok but the PDF on S3 is blank. Below is the code I am using:

  1. I use the following class to create the PDF from a UIImage, tested ok.
    // Using PDFKit
    func generatePDF(source: UIImage) -> PDFDocument {
    
      let pdfDocument = PDFDocument()
      let pdfPage = PDFPage(image: source)
      pdfDocument.insert(pdfPage!, at: 0)
      return pdfDocument
    }
  1. I used Alamofire to perform a multipart upload with the pdf, tested ok.
class NetworkManager {
    
    static let shared = NetworkManager()
    
    func upload(document: Data, name: String) {
        
        let filename = "\(name).pdf"
        let urlString = endpoint   "?filename="   filename
        let url = URL(string: urlString)!
        var request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
        request.method = .post
        request.setValue(key, forHTTPHeaderField: api)
        AF.upload(multipartFormData: { multiPart in
            multiPart.append(document, withName: name, fileName: filename, mimeType: "application/pdf")
        }, with: request)
            .uploadProgress(queue: .main, closure: { progress in
                print("Upload Progress: \(progress.fractionCompleted)")
            })
            .responseJSON(completionHandler: { data in
                print("data: \(data)")
            })
    }
}

  1. On AWS I am using the following framework to reconstruct the multipart data back to a PDF

lambda-multipart-parser
Image of Binary Media Types Added

I did a redeploy of my api and everything worked perfect, so in the end it was not a code problem but configuration mistake on AWS.

This blog post was very helpful: AWS SAM Configuration for API Gateway Binary Response / Payloads

Thanks for your help everyone.

  • Related