Create pdf file from scrollview in swift

Viewed 114

I am trying to create pdf from scrollview. The pdf is created successfully. But there is no padding on the top and bottom of the pdf file. i want the padding in each page of the pdf file.can anyone help me to resolve it? if the pdf file is consists on two or more page so parts are not visible as there is no padding

class CreatePDF {
    
    func PDFWithScrollView(scrollview: UIScrollView) -> NSData {
       
        let pageDimensions = scrollview.bounds
        
        let pageSize = pageDimensions.size
        let totalSize = scrollview.contentSize
        
        let numberOfPagesThatFitHorizontally = Int(ceil(totalSize.width / pageSize.width))
//        let numberOfPagesThatFitVertically = 1
        let numberOfPagesThatFitVertically = Int(ceil(totalSize.height / pageSize.height))
        
       
        let outputData = NSMutableData()
        
        UIGraphicsBeginPDFContextToData(outputData, pageDimensions, nil)
       
        let savedContentOffset = scrollview.contentOffset
        let savedContentInset = scrollview.contentInset
        
        scrollview.contentInset = UIEdgeInsets.zero
       
        
        if let context = UIGraphicsGetCurrentContext()
        {
            for indexHorizontal in 0 ..< numberOfPagesThatFitHorizontally
            {
                for indexVertical in 0 ..< numberOfPagesThatFitVertically
                {
                  
                    
                    UIGraphicsBeginPDFPage()
                  
                    
                    let offsetHorizontal = CGFloat(indexHorizontal) * pageSize.width
                    let offsetVertical = CGFloat(indexVertical) * pageSize.height
                    
                    scrollview.contentOffset = CGPoint(x: offsetHorizontal, y: offsetVertical)
                    context.translateBy(x: -offsetHorizontal, y: -offsetVertical) 
                    
                  
                    
                    scrollview.layer.render(in: context)
                }
            }
        }
        
               UIGraphicsEndPDFContext()
      
        
        scrollview.contentInset = savedContentInset
        scrollview.contentOffset = savedContentOffset
       
        return outputData
    }
}




 let snapshotter = CreatePDF()
 let data = snapshotter.PDFWithScrollView(scrollview: scrollView)

0 Answers
Related