Friday, November 6, 2026
HomeiOS Developmentios - Unable to avoid wasting pdf after signature

ios – Unable to avoid wasting pdf after signature

[ad_1]

I’m able to signal a pdf, However after I tried to saved it, Its not saving the up to date pdf file.

Code

override func viewDidAppear(_ animated: Bool) {
    pdfContainerView.usePageViewController(true, withViewOptions: nil)
    
    guard let signatureImage = signatureImage, let web page = pdfContainerView.currentPage else { return }
    let pageBounds = web page.bounds(for: .cropBox)
    let imageBounds = CGRect(x: pageBounds.midX, y: pageBounds.midY, width: 200, peak: 100)
    let imageStamp = ImageStampAnnotation(with: signatureImage, forBounds: imageBounds, withProperties: nil)
    web page.addAnnotation(imageStamp)
    btnSaveSign.isHidden = false

}
func setupPdfView(url:String) {
         if let documentURL = URL(string: url),
        
        let information = attempt? Knowledge(contentsOf: documentURL),
        let doc = PDFDocument(information: information) {
        
        // Set doc to the view, heart it, and set background shade
        //pdfContainerView.displayMode = .singlePageContinuous
        pdfContainerView.doc = doc
        pdfContainerView.autoScales = true
        pdfContainerView.displayDirection = .horizontal
        pdfContainerView.backgroundColor = UIColor.white
        btnNewSign.isHidden = false
        lblPlaceholder.isHidden = true
        let panAnnotationGesture = UIPanGestureRecognizer(goal: self, motion: #selector(didPanAnnotation(sender:)))
        pdfContainerView.addGestureRecognizer(panAnnotationGesture)
        
    }
}

@objc func didPanAnnotation(sender: UIPanGestureRecognizer) {
    let touchLocation = sender.location(in: pdfContainerView)
    
    guard let web page = pdfContainerView.web page(for: touchLocation, nearest: true)
        else {
            return
    }
    let locationOnPage = pdfContainerView.convert(touchLocation, to: web page)
    
    swap sender.state {
    case .started:
        
        guard let annotation = web page.annotation(at: locationOnPage) else {
            return
        }
        
        if annotation.isKind(of: ImageStampAnnotation.self) {
            currentlySelectedAnnotation = annotation
        }
        
    case .modified:
        
        guard let annotation = currentlySelectedAnnotation else {
            return
        }
        let initialBounds = annotation.bounds
        // Set the middle of the annotation to the spot of our finger
        annotation.bounds = CGRect(x: locationOnPage.x - (initialBounds.width / 2), y: locationOnPage.y - (initialBounds.peak / 2), width: initialBounds.width, peak: initialBounds.peak)
        
        
        //print("transfer to (locationOnPage)")
    case .ended, .cancelled, .failed:
        currentlySelectedAnnotation = nil
    default:
        break
    }
}
   

@objc func clickButton(){
    let importMenu = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .import)
    importMenu.delegate = self
    importMenu.modalPresentationStyle = .formSheet
    self.current(importMenu, animated: true, completion: nil)
}



public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let myURL = urls.first else {
        return
    }
    print("import outcome : (myURL)")
    self.pdfURLToSave = "(myURL)"
    let pdfView = PDFView(body: view.body)
    
    title = "My PDF Viewer"
    setupPdfView(url:"(myURL)")
    
}

func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    return self//or use return self.navigationController for fetching app navigation bar color
}


public func documentMenu(_ documentMenu:UIDocumentPickerViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
    documentPicker.delegate = self
    current(documentPicker, animated: true, completion: nil)
}

Code snippet for save file-

    @IBAction func btnSaveAction(_ sender: Any) {
            if let documentURL = URL(string: self.pdfURLToSave),
       
       let information = attempt? Knowledge(contentsOf: documentURL),
       let doc = PDFDocument(information: information) {
        
        if let information = doc.dataRepresentation(){
            
            let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
            let documentsDirectory = paths[0] // Get paperwork folder
            let folderPathUrl = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("SignApp.pdf")
            if FileManager.default.fileExists(atPath: folderPathUrl.path){
                attempt? FileManager.default.removeItem(at: folderPathUrl)
                
            }
            pdfContainerView.doc?.write(toFile: "(folderPathUrl)")
            
        }
    }
    
        }

ImageStampAnnotation Class

class ImageStampAnnotation: PDFAnnotation {
    
    var picture: UIImage!
    
    // A customized init that units the kind to Stamp on default and assigns our Picture variable
    init(with picture: UIImage!, forBounds bounds: CGRect, withProperties properties: [AnyHashable : Any]?) {
        tremendous.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp, withProperties: properties)
        
        self.picture = picture
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been carried out")
    }
    
    
    override func draw(with field: PDFDisplayBox, in context: CGContext) {
        
        // Get the CGImage of our picture
        guard let cgImage = self.picture.cgImage else { return }
        
        // Draw our CGImage within the context of our PDFAnnotation bounds
        context.draw(cgImage, in: self.bounds)
        
    }
}

Error-

CGPDFContextCreate: didn't create PDF context delegate..

App display shots-

enter image description here
enter image description here
enter image description here

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments