How can I make a PDF file using base64 string ? Swift

12,838

Yes, you have to convert it to Data and then save it to the documents directory on the device. A function like this would work:

func saveBase64StringToPDF(_ base64String: String) {

    guard
        var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
        let convertedData = Data(base64Encoded: base64String)
        else {
        //handle error when getting documents URL
        return
    }

    //name your file however you prefer
    documentsURL.appendPathComponent("yourFileName.pdf")

    do {
        try convertedData.write(to: documentsURL)
    } catch {
        //handle write error here
    }

    //if you want to get a quick output of where your 
    //file was saved from the simulator on your machine
    //just print the documentsURL and go there in Finder
    print(documentsURL)
}
Share:
12,838

Related videos on Youtube

Elizabeth Hernandez
Author by

Elizabeth Hernandez

Updated on June 19, 2022

Comments

  • Elizabeth Hernandez
    Elizabeth Hernandez almost 2 years

    I'm looking for a way to save a PDF file on my project directory, I've received a base 64 pdf string from a Web Service yet. Do I have to convert it to NSData or something like that?

    I'm new at coding in Swift but I can follow your instructions.

    I hope you can help me. Thanks

    • GetSwifty
      GetSwifty over 7 years
      Decode the base 64 string into Data, then save the data
  • Rahul
    Rahul about 7 years
    this is working. I tried in swift 3.0
  • Sergio
    Sergio over 4 years
    how can we open the pdf from the app?
  • Anees
    Anees almost 4 years
    how to display this PDF file later, from document directory in PDFView