swiftcgpdfdocument

Convert String back to PDF


I'm receiving a response containing a String from our RPC server. This String is a PDF converted to a String. In my app I need to convert this string back to a PDF file. I tried a couple of solutions here on Stack but they didn't work form me.

The problem is that my function keeps throwing because it fails to convert my string to a CGPDFDocument. What am I doing wrong here?

This is the code I currently have.

final class PdfGenerator: PdfGeneratorInterface {

// MARK: PdfGeneratorProtocol
func generatePdf(string: String) throws -> CGPDFDocument {

    guard let
        data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false),
        cfData = CFDataCreate(kCFAllocatorDefault, UnsafePointer<UInt8>(data.bytes), data.length)
    else {
        throw PdfGeneratorException.UnsupportedFormatException
    }

    let cgDataProvider =  CGDataProviderCreateWithCFData(cfData)

    guard let cgPDFDocument = CGPDFDocumentCreateWithProvider(cgDataProvider) else {
        throw PdfGeneratorException.UnsupportedFormatException
    }

    return cgPDFDocument
}

}

PDF String content:

https://gist.github.com/Combidi/fa53f2d74e7ae177bb3885d5d640c13c

Thanks


Solution

  • It looks as if the string you linked to is base64 encoded. If you decode that, the result should be a "%PDF" string that you can use.