iOS 13.2.3 pdfViewGestureRecognize and PDFkit

Here is my Code it work perfectly in iOS 12 but for iOS 13 code can't give exactly values





let pdfViewGestureRecognizer = PDFViewGestureRecognizer()



pdfView.autoScales = true

pdfView.displayMode = .singlePage

pdfView.displayDirection = .horizontal

pdfView.usePageViewController(true, withViewOptions: [UIPageViewControllerOptionInterPageSpacingKey: 20])

pdfView.addGestureRecognizer(pdfViewGestureRecognizer)

pdfView.document = pdfDocument







here is first problem is not go here I adding great delegate for Gesture and other details find here but isn't work too !!





class PDFViewGestureRecognizer: UIGestureRecognizer {

var isTracking = false



override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {

isTracking = true

print ("but not iOS 13.2.3")

}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {

isTracking = false

}



override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent) {

isTracking = false

}

}



here is second part





let pdfSubVws = pdfView.subviews

print("subVws ",pdfSubVws)

for subVws in pdfSubVws

{

if (String(describing: subVws).range(of:"UIPageViewControllerContentView") != nil)

{

let pageVc = subVws.subviews

for subVws in pageVc

{

if (String(describing: subVws).range(of:"UIQueuingScrollView") != nil)

{

let QueueVc = subVws.subviews

// print("QueueVcQueueVc ", QueueVc)

for subVws in QueueVc

{

if (String(describing: subVws).range(of:"UIView") != nil)

{

let viewVc = subVws.subviews

// print("\n\nviewVcVcQueueVc ", viewVc)

for subVws in viewVc

{

if (String(describing: subVws).range(of:"UIView") != nil)

{

let SubviewVc = subVws.subviews

// print("\n\nSubviewVcSubviewVc ", SubviewVc)

for subVws in SubviewVc

{

if (String(describing: subVws).range(of:"UIScrollView") != nil)

{

let finalVw = subVws.subviews

// print("\n\nfinalVw ", finalVw)

//

for subVws in finalVw

{

if (String(describing: subVws).range(of:"UIView") != nil) //here is ok iOS 12 It's ok but not iOS 13.2.3

{

Replies

Here is my Code it work perfectly in iOS 12 but for iOS 13 code can't give exactly values


What do you get ?

What did you expect ?

Which line (below) do you expect those values being displayed ? Is it line 36 that you get nil instead of what ?


Note: you should format the source code with the source formatter tool of this forum (<>)


     let pdfViewGestureRecognizer = PDFViewGestureRecognizer()
            pdfView.autoScales = true
            pdfView.displayMode = .singlePage
            pdfView.displayDirection = .horizontal
            pdfView.usePageViewController(true, withViewOptions: [UIPageViewControllerOptionInterPageSpacingKey: 20])
          
            pdfView.addGestureRecognizer(pdfViewGestureRecognizer)
          
            pdfView.document = pdfDocument



here is first problem is not go here I adding great delegate for Gesture and other details find here but isn't work too !!

What is great delegate ?


class PDFViewGestureRecognizer: UIGestureRecognizer {
    var isTracking = false

    override func touchesBegan(_ touches: Set, with event: UIEvent) {
        isTracking = true
        print ("but not iOS 13.2.3")
     }

    override func touchesEnded(_ touches: Set, with event: UIEvent) {
        isTracking = false
    }

    override func touchesCancelled(_ touches: Set, with event: UIEvent) {
        isTracking = false
    }
}


here is second part

In which class is this ? Is it part of PDFViewGestureRecognizer ?


            let pdfSubVws = pdfView.subviews
            print("subVws  ",pdfSubVws)
        
            for subVws in pdfSubVws
            {
                if (String(describing: subVws).range(of:"UIPageViewControllerContentView") != nil)
                {
                    let pageVc = subVws.subviews
                
                    for subVws in pageVc
                    {
                        if (String(describing: subVws).range(of:"UIQueuingScrollView") != nil)
                        {
                            let QueueVc = subVws.subviews
                             //                        print("QueueVcQueueVc  ", QueueVc)             
                            for subVws in QueueVc
                            {
                                if (String(describing: subVws).range(of:"UIView") != nil)
                                {
                                    let viewVc = subVws.subviews
                                       //                                print("\n\nviewVcVcQueueVc  ", viewVc)
                                    for subVws in viewVc
                                    {
                                        if (String(describing: subVws).range(of:"UIView") != nil)
                                        {
                                            let SubviewVc = subVws.subviews
                                            //                                        print("\n\nSubviewVcSubviewVc  ", SubviewVc)
                                            for subVws in SubviewVc
                                            {
                                                if (String(describing: subVws).range(of:"UIScrollView") != nil)
                                                {
                                                    let finalVw = subVws.subviews
                                                    //                                                print("\n\nfinalVw  ", finalVw)
                                                    for subVws in finalVw
                                                    {
                                                        if (String(describing: subVws).range(of:"UIView") != nil)   / /. here is  ok iOS 12 It's ok  but not iOS 13.2.3
                                                        {

If you need to explain why nil line 37,

if (String(describing: subVws).range(of:"UIView") != nil)   //. here is  ok iOS 12 It's ok  but not iOS 13.2.3


Is it for all subVws in finalVw or for a specific one ?

it is because "UIView" is not found in the string.

With the limited info you provide it is just impossible to say why, except that subVws does not contain UIView in its description !!!


Note: please, read your post again. How can you hope with such lack of context information for anyone else than you to guess the root cause of the issue ?

Hi Claude
i add one text box and user can change place the text box with finger in one pdf file its correct my code in ios 12 but user can't change move textbox in ios 13 :
if you need i can send you a sample project

//
//  BookViewController.swift
//  BookReader


import UIKit
import PDFKit
import MessageUI
import UIKit.UIGestureRecognizerSubclass
import Social
import MobileCoreServices

class BookViewController: UIViewController, UIPopoverPresentationControllerDelegate, PDFViewDelegate, ActionMenuViewControllerDelegate, SearchViewControllerDelegate, ThumbnailGridViewControllerDelegate, OutlineViewControllerDelegate, BookmarkViewControllerDelegate, UITextViewDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UIDocumentPickerDelegate, choosedColorProtocol {
    var pdfDocument: PDFDocument?
    
    var pdfNewDocument: PDFDocument?

    var docController: UIDocumentInteractionController?
    
    
    
    @IBOutlet weak var pdfView: PDFView!
    @IBOutlet weak var pdfThumbnailViewContainer: UIView!
    @IBOutlet weak var pdfThumbnailView: PDFThumbnailView!
    @IBOutlet private weak var pdfThumbnailViewHeightConstraint: NSLayoutConstraint!

    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var titleLabelContainer: UIView!
    @IBOutlet weak var pageNumberLabel: UILabel!
    @IBOutlet weak var pageNumberLabelContainer: UIView!

    let tableOfContentsToggleSegmentedControl = UISegmentedControl(items: [ imageLiteral(resourceName: "Grid"),  imageLiteral(resourceName: "List"),  imageLiteral(resourceName: "Bookmark-N")])
    @IBOutlet weak var thumbnailGridViewConainer: UIView!
    @IBOutlet weak var outlineViewConainer: UIView!
    @IBOutlet weak var bookmarkViewConainer: UIView!

    var lastPoint = CGPoint()
    var lastLocationPoint = CGPoint()
    var currentPointSelec = CGPoint()
    var BezierPath = UIBezierPath()
    var pdfBezierPath = UIBezierPath()
    
    var pdfClickedRow : Int = 77
    
    var touchCount : Int = 0
    var previousTouchCount : Int = 0
    var isTouchMoved : Bool = false
    var layerPathArr = [Int : [CGPath]]()
    var toDeleteLayerName = String()
    
    var inkAnnotationArr = [PDFAnnotation]()
    
    var bookmarkButton: UIBarButtonItem!

    var searchNavigationController: UINavigationController?

    let barHideOnTapGestureRecognizer = UITapGestureRecognizer()
    let pdfViewGestureRecognizer = PDFViewGestureRecognizer()
    
    var whichTask = String()
    var spacingNumber : CGFloat = 10.0
    var colorForeground = UIColor()
    var AddTextCount : Int = 0
    var drawNumCount = Int()
    
    var heightYOrgin  = CGFloat()
    
    var getHighlightColor = UIColor()
    
    var lastTextAnnoPoint = CGPoint()
    
    @IBOutlet weak var blackSaveButVw: UIView!
    // FOR COLOR CHANGE
    
    @IBOutlet weak var bottomColorView: UIView!
    
    @IBOutlet weak var redClrVw: UIView!
    @IBOutlet weak var brownClrVw: UIView!
    @IBOutlet weak var yelloClrVw: UIView!
    @IBOutlet weak var magentaClrVw: UIView!
    @IBOutlet weak var darkGrayClrVw: UIView!
    @IBOutlet weak var blueClrVw: UIView!
    @IBOutlet weak var greenClrVw: UIView!
    @IBOutlet weak var blackClrVw: UIView!
    
    
    @IBOutlet weak var actionsButStckVw: UIStackView!
    //TO DRAW
    @IBOutlet weak var editActionButStckVw: UIStackView!
    
    @IBOutlet weak var drawView: UIView!
    
    // FOR TEXT
    var isDoneButtonPressed = false
    @IBOutlet weak var sideWidthHeightVw: UIView!
    
    @IBOutlet weak var spacingLbl: UILabel!
    
    @IBOutlet weak var widthDiffImgVw: UIImageView!
    
    @IBOutlet weak var heightDifImgVw: UIImageView!
    
    @IBOutlet weak var topMoveImgVw: UIImageView!
    
    
    @IBOutlet weak var bottomMoveImgVw: UIImageView!
    
    @IBOutlet weak var leftMoveImgVw: UIImageView!
    
    @IBOutlet weak var rightMoveImgVw: UIImageView!
    
    var gettinfFileURL : URL?
    var pdfPagesImgArr = [UIImage]()
    
    var signingPath = UIBezierPath()
    var annotationAdded = false
    var currentAnnotation : PDFAnnotation?
    
    var addTextViewArr = [UITextView]()
    
    var addTxtCount : String = ""
    
    var pdfLandingView = UIView()
    var fontChangePickerView = UIPickerView()
    var currentTypeTxtVw = UITextView()
    
    var textAnnoStoredDict = [String : [String:Any]]()  //TEXT STORED USER DEFAULT
    var totalBezierPathDict = [String : [[String:Any]]]() //BEZIERPATH STORED USER DEFAULT
    var BezierPathAddArr = [[String:Any]]()
    var currentDrawAddArr = [[String:Any]]()
    var PreviousBezierPathAddArr = [[String:Any]]()
    
    @IBOutlet weak var FontToolBarVw: UIView!
    @IBOutlet weak var setBtn: UIButton!
    @IBOutlet weak var fontNameLbl: UILabel!
    @IBOutlet weak var fontClrVw: UIView!
    var fontNam : String = "Helvetica Neue" // ARIAL // Verdana // Times New Roman // Georgia // Courier New
    
    var fontFamilyName = [Int : String]()
    
    var highLightText = String()
    
    var isMenuColorClicked : Bool = true
    
    var fontSizeList : [Int : CGFloat] = [
        0 : 12,
        1 : 14,
        2 : 16,
        3 : 18,
        4 : 20,
        5 : 22,
        6 : 24,
        7 : 26,
        8 : 28,
        9 : 30,
        10 : 32,
        11 : 34
    ]
    
    var bgOpacityList : [Int : CGFloat] = [
        0 : 0.0,
        1 : 0.1,
        2 : 0.2,
        3 : 0.3,
        4 : 0.4,
        5 : 0.5,
        6 : 0.6,
        7 : 0.7,
        8 : 0.8,
        9 : 0.9,
        10 : 1.0
    ]
    
    var fontColorList = [
        0 : UIColor.black,
        1 : UIColor.blue,
        2 : UIColor.brown,
        3 : UIColor.cyan,
        4 : UIColor.darkGray,
        5 : UIColor.green,
        6 : UIColor.lightGray,
        7 : UIColor.magenta,
        8 : UIColor.orange,
        9 : UIColor.red,
        10 : UIColor.white,
        11 : UIColor.yellow
    ]
    
    var bgChangecolor = UIColor()
    
    var usingFontName = "Helvetica Neue"
    var usingFontColor = UIColor.black
    var usingFontSize = 12
    
    var usingWidthText = CGFloat()
    var usingHeightText = CGFloat()
    
    var usingBGFontColor = UIColor.black
    var usingBGFontAlpha : CGFloat = 0.2
    
    var usingTextVwNumber : Int = 0
    
    var selectedBGRowColor = 0
    var selectedBGAlpha : Int = 5
    
    var selectedRowFont = Int()
    var selectedRowColor = 0
    var selectedRowSize = 0
    var linkAnn = PDFAnnotation()
    
    var PdfImagesArr = [UIImage]()
    
    var addWindow = UIApplication.shared.keyWindow
    var newVw = UIView()
    
    var textVwMovedX = CGFloat()
    var textVwMovedY = CGFloat()
    
    let needFont = ["Helvetica Neue", "Arial", "Verdana", "Times New Roman", "Georgia", "Courier New"]
    var fontList = [Int : [[String : Any]]]()
    
    var hasKeyboardChanged : Bool = false
    var whichPickerView = String()
    
    var pdfChoosedRowNumber = String()
    
    var ColorMenu = UIMenuController.shared
    
    let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom
    
    var isTypeTextVwChanged : Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        definesPresentationContext = true
        
        var forCount : Int = 0
        
        print("clikdRow     ", pdfClickedRow)
        
        pdfChoosedRowNumber = "pdfChoosedRowNumber" + String(pdfClickedRow)
        
        highLightText = "highLightText"
        
        for familyName:String in UIFont.familyNames {
//            print("\n\nFamily Name: \(familyName)")
            
            let contains = needFont.contains(where: { $0 == familyName })
            if contains == true
            {
                if familyName == "Helvetica Neue"
                {
                    selectedRowFont = forCount
                }
                
                fontFamilyName[forCount] = familyName
                forCount = forCount + 1
            }
            
            
//            for fontName:String in UIFont.fontNames(forFamilyName: familyName) {
//                print("--Font Name: \(fontName)")
//            }
        }
        
//        let newwindow = UIWindow(frame: UIScreen.main.bounds)
//        newwindow.backgroundColor = UIColor.brown
//        newwindow.isHidden = false
//        newwindow.windowLevel = UIWindowLevelAlert
//        newwindow.makeKeyAndVisible()
        
        
//        window.addSubview(someView)
        
        
        fontClrVw.layer.cornerRadius = 7.5
        print("fontFamilyNamefontFamilyName   ", fontFamilyName)
        
        fontNameLbl.font = UIFont(name: usingFontName, size: 14)
        fontNameLbl.text = " - " + String(usingFontSize) + " - " + usingFontName
        fontNameLbl.textColor = usingFontColor
        fontClrVw.backgroundColor = usingFontColor
        
        bottomColorView.isHidden = true
        actionsButStckVw.isHidden = true
        sideWidthHeightVw.isHidden = true
        colorForeground = UIColor.black
        editActionButStckVw.isHidden = true
        whichTask = "goingToEdit"
        drawView.isHidden = true
        
        currentTypeTxtVw.delegate = self
        
        
        fontChangePickerView.delegate = self
        fontChangePickerView.dataSource = self
        
        NotificationCenter.default.addObserver(self, selector: #selector(pdfViewPageChanged(_:)), name: .PDFViewPageChanged, object: nil)

        barHideOnTapGestureRecognizer.addTarget(self, action: #selector(gestureRecognizedToggleVisibility(_:)))
        view.addGestureRecognizer(barHideOnTapGestureRecognizer)

        tableOfContentsToggleSegmentedControl.selectedSegmentIndex = 0
        tableOfContentsToggleSegmentedControl.addTarget(self, action: #selector(toggleTableOfContentsView(_:)), for: .valueChanged)

        pdfView.autoScales = true
        pdfView.displayMode = .singlePage
        pdfView.displayDirection = .horizontal
        pdfView.usePageViewController(true, withViewOptions: [UIPageViewControllerOptionInterPageSpacingKey: 20])

        pdfView.addGestureRecognizer(pdfViewGestureRecognizer)

//        drawPDFfromURL(url: pdfNewDocument?.documentURL as! NSURL)
//        ConvertImagesToPages()
        
        pdfView.document = pdfDocument

        pdfThumbnailView.layoutMode = .horizontal
        pdfThumbnailView.pdfView = pdfView

        titleLabel.text = pdfDocument?.documentAttributes?["Title"] as? String
        titleLabelContainer.layer.cornerRadius = 4
        pageNumberLabelContainer.layer.cornerRadius = 4
        
        let menuItem3 = UIMenuItem(title: "Draw", action: #selector(drawingOnPDF))
        let menuItem4 = UIMenuItem(title: "Text", action: #selector(TextOnPDF))
        
        let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightTextColor))
        UIMenuController.shared.menuItems = [menuItem1] //, menuItem4]
        

        resume()
        
        ColorBorderCustomisation()
        
        
        getHighlightColor = UIColor.orange
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow),
                                               name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide),
                                               name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
    
        NotificationCenter.default.addObserver(self, selector: #selector(menuWillHide),
                                               name: NSNotification.Name.UIMenuControllerWillHideMenu, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(menuWillShow),
                                               name: NSNotification.Name.UIMenuControllerWillShowMenu, object: nil)
    }
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        adjustThumbnailViewHeight()
    }
    
    @objc func highlightTextColor()
    {
        whichTask = "highLightText"
        ActionHighLight()
        ColorListHighlight()
        
        isMenuColorClicked = false
    }
    
    @objc func menuWillShow(notif: NSNotification)
    {
        
        
        
        
        print("Meu_Shwing")
        
//        removeHighlightAnno()
    }
    @objc func menuWillHide(notif: NSNotification)
    {
//        if whichTask == "colorPickAppeared"
//        {
//            print("foundBadSce")
//            whichTask = "goingToEdit"
//            let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightTextColor))
//            UIMenuController.shared.menuItems = [menuItem1]
//        }
        
//        becomeFirstResponder()
//        whichTask = "goingToEdit"
//        UIMenuController.shared.isMenuVisible = true
        
        if isMenuColorClicked == false{
            
            whichTask = "goingToEdit"
            
            print("dfgdfsgdf", ColorMenu.isMenuVisible)
            
            ColorMenu.menuItems = []
            
            let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightTextColor))
            UIMenuController.shared.menuItems = [menuItem1]
        }
        
        print("Meu_Hding")
    }
    
    
    
    func ActionHighLight()
    {
        removeHighlightAnno()
    }
    func addColorHighLights()
    {
        let selections = pdfView.currentSelection?.selectionsByLine()
        // Simple scenario, assuming your pdf is single-page.
        guard let page = selections?.first?.pages.first else { return }
        
        selections?.forEach({ selection in
            
//            pdfView.currentPage.se
            
            let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
            highlight.endLineStyle = .square
            
            
            highlight.color = getHighlightColor
            
            whichTask = "goingToEdit"
            let menuItem1 = UIMenuItem(title: "Highlight", action: #selector(highlightTextColor))
            UIMenuController.shared.menuItems = [menuItem1]
            
            page.addAnnotation(highlight)
        })
    }
    
    func removeHighlightAnno()
    {
        var recHL = CGRect()
        let selections = pdfView.currentSelection?.selectionsByLine()
        // Simple scenario, assuming your pdf is single-page.
        guard let page = selections?.first?.pages.first else { return }
        
        selections?.forEach({ selection in
            
            recHL = selection.bounds(for: page)
            
            print("recHLrecHL   ", recHL)
            
            let anno = pdfView.currentPage?.annotation(at: CGPoint(x: recHL.origin.x, y: recHL.origin.y))
            
            print("asdasdasd     ", anno?.type)
            
            print("->>Tot_ann    ", pdfView.currentPage?.annotations)
            
            if anno?.type == "Highlight"
            {
                pdfView.currentPage?.removeAnnotation(anno!)
            }
            
            if anno?.type == nil
            {
                for allInn in (pdfView.currentPage?.annotations)!
                {
                    if allInn.type == "Highlight"
                    {
                        if Int(allInn.bounds.origin.x) == Int(recHL.origin.x)
                        {
                            if Int(allInn.bounds.origin.y) == Int(recHL.origin.y)
                            {
                                print("ano_rem")
                                pdfView.currentPage?.removeAnnotation(allInn)
//                                break
                            }
                        }
                    }
                }
            }
        })
        
        
         print("fdsdsfsf")
        
    }
    
    //MARK:- SPACING MENU
    func ColorListHighlight() {
//        becomeFirstResponder()

        let red : UIMenuItem = UIMenuItem(title: "Red", action: #selector(spacingRed))
        
        let blue = UIMenuItem(title: "Blue", action: #selector(spacingCyan))
        let yellow = UIMenuItem(title: "Yellow", action: #selector(spacingYellow))
        let orange = UIMenuItem(title: "Orange", action: #selector(spacingOrange))
        let purple = UIMenuItem(title: "Purple", action: #selector(spacingPurple))
        ColorMenu.menuItems = [red, blue, yellow, orange, purple]

        
        ColorMenu.setMenuVisible(true, animated: true)
//        whichTask = "colorPickAppeared"
    }
    
    @objc func spacingRed()
    {
        getHighlightColor = UIColor.red
        addColorHighLights()
        isMenuColorClicked = true
    }
    @objc func spacingCyan()
    {
        getHighlightColor = UIColor.cyan
        addColorHighLights()
        isMenuColorClicked = true
    }
    @objc func spacingYellow()
    {
        getHighlightColor = UIColor.yellow
        addColorHighLights()
        isMenuColorClicked = true
    }
    @objc func spacingOrange()
    {
        getHighlightColor = UIColor.orange
        addColorHighLights()
        isMenuColorClicked = true
    }
    @objc func spacingPurple()
    {
        getHighlightColor = UIColor.purple
        addColorHighLights()
        isMenuColorClicked = true
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        if let getValuesData = UserDefaults.standard.value(forKey: "TextStorage") as? NSData {
            textAnnoStoredDict = NSKeyedUnarchiver.unarchiveObject(with: getValuesData as Data) as! [String : [String:Any]]
            print("getValuestexttoredDict      ", textAnnoStoredDict)
        }
        else
        {
            print("Nthn In UserDef")
        }
        
        if let getPathsData = UserDefaults.standard.value(forKey: "BezierPathStorage") as? NSData {
            totalBezierPathDict = NSKeyedUnarchiver.unarchiveObject(with: getPathsData as Data) as! [String : [[String:Any]]]
            
            print("totalBezierPathDicttotalBezierPathDict   ", totalBezierPathDict)
            
            print("0th PAge")
            
            let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
            
            previousDrawAddedInPage()
            
            getPreviousDrawOnCurrentPage(currPageNum: getPagenumber)
            
        }
        else
        {
            print("Nthn Datas In UserDef")
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        
        
    }
    
    func getPDFLocation()
    {
        let url = Bundle.main.url(forResource: "Sample", withExtension: "pdf")!
        
        let pdfData = NSData(contentsOf: url)
        
        // get the documents directory url
        let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // choose a name for your image
        let fileName = "new.pdf"
        // create the destination file url to save your image
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        
        
        gettinfFileURL = fileURL
        // get your UIImage jpeg data representation and check if the destination file url already exists
        if let data = pdfData,
            !FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                // writes the image data to disk
                try data.write(to: fileURL)
                print("file saved    ", fileURL)
            } catch {
                print("error saving file:   ", error)
            }
        }
    }
    
    func ColorBorderCustomisation()
    {
        redClrVw.backgroundColor = UIColor.red
        brownClrVw.backgroundColor = UIColor.brown
        yelloClrVw.backgroundColor = UIColor.yellow
        magentaClrVw.backgroundColor = UIColor.magenta
        darkGrayClrVw.backgroundColor = UIColor.orange
        blueClrVw.backgroundColor = UIColor.blue
        greenClrVw.backgroundColor = UIColor.green
        blackClrVw.backgroundColor = UIColor.black
        
        redClrVw.layer.cornerRadius = 10
        brownClrVw.layer.cornerRadius = 10
        yelloClrVw.layer.cornerRadius = 10
        magentaClrVw.layer.cornerRadius = 10
        darkGrayClrVw.layer.cornerRadius = 10
        blueClrVw.layer.cornerRadius = 10
        greenClrVw.layer.cornerRadius = 10
        blackClrVw.layer.cornerRadius = 10
        
        widthDiffImgVw.image = widthDiffImgVw.image!.withRenderingMode(.alwaysTemplate)
        widthDiffImgVw.tintColor = UIColor.orange
        
        heightDifImgVw.image = heightDifImgVw.image!.withRenderingMode(.alwaysTemplate)
        heightDifImgVw.tintColor = UIColor.orange
        
        topMoveImgVw.image = topMoveImgVw.image!.withRenderingMode(.alwaysTemplate)
        topMoveImgVw.tintColor = UIColor.orange
        
        bottomMoveImgVw.image = bottomMoveImgVw.image!.withRenderingMode(.alwaysTemplate)
        bottomMoveImgVw.tintColor = UIColor.orange
        
        leftMoveImgVw.image = leftMoveImgVw.image!.withRenderingMode(.alwaysTemplate)
        leftMoveImgVw.tintColor = UIColor.orange
        
        rightMoveImgVw.image = rightMoveImgVw.image!.withRenderingMode(.alwaysTemplate)
        rightMoveImgVw.tintColor = UIColor.orange
    
    }

    
    
    
    override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
        coordinator.animate(alongsideTransition: { (context) in
            self.adjustThumbnailViewHeight()
        }, completion: nil)
    }

    private func adjustThumbnailViewHeight() {
        self.pdfThumbnailViewHeightConstraint.constant = 44 + self.view.safeAreaInsets.bottom
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let viewController = segue.destination as? ThumbnailGridViewController {
            viewController.pdfDocument = pdfDocument
            viewController.delegate = self
        } else if let viewController = segue.destination as? OutlineViewController {
            viewController.pdfDocument = pdfDocument
            viewController.delegate = self
        } else if let viewController = segue.destination as? BookmarkViewController {
            viewController.pdfDocument = pdfDocument
            viewController.delegate = self
        }
        
    }

    override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
        
        print("Dismiss123123123: \(self.presentedViewController)")
        super.dismiss(animated: flag, completion: completion)
    }
    
    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }

    func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
        
        return false
    }
    
    
    
    func actionMenuViewControllerShareDocument(_ actionMenuViewController: ActionMenuViewController) {
        
        self.dismiss(animated: true, completion: nil)
        let url = Bundle.main.url(forResource: "Sample", withExtension: "pdf")!
        docController = UIDocumentInteractionController(url: url)
        docController?.delegate = self
        docController?.presentOptionsMenu(from: self.view.frame, in:self.view, animated:true)
    }

    func share(url: URL) {
        docController?.url = url
        docController?.uti = url.typeIdentifier ?? "public.data, public.content"
        docController?.name = url.localizedName ?? url.lastPathComponent
        docController?.presentOptionsMenu(from: view.frame, in: view, animated: true)
    }
    
    func actionMenuViewControllerPrintDocument(_ actionMenuViewController: ActionMenuViewController) {
        let printInteractionController = UIPrintInteractionController.shared
        printInteractionController.printingItem = pdfDocument?.dataRepresentation()
        printInteractionController.present(animated: true, completionHandler: nil)
    }

    func searchViewController(_ searchViewController: SearchViewController, didSelectSearchResult selection: PDFSelection) {
        selection.color = .yellow
        pdfView.currentSelection = selection
        pdfView.go(to: selection)
        showBars()
    }

    func thumbnailGridViewController(_ thumbnailGridViewController: ThumbnailGridViewController, didSelectPage page: PDFPage) {
        resume()
        pdfView.go(to: page)
    }

    func outlineViewController(_ outlineViewController: OutlineViewController, didSelectOutlineAt destination: PDFDestination) {
        resume()
        pdfView.go(to: destination)
    }

    func bookmarkViewController(_ bookmarkViewController: BookmarkViewController, didSelectPage page: PDFPage) {
        resume()
        pdfView.go(to: page)
    }

    private func resume() {
        let backButton = UIBarButtonItem(image:  imageLiteral(resourceName: "Chevron"), style: .plain, target: self, action: #selector(back(_:)))
        let tableOfContentsButton = UIBarButtonItem(image:  imageLiteral(resourceName: "List"), style: .plain, target: self, action: #selector(showTableOfContents(_:)))
        let actionButton = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(showActionMenu(_:)))
        navigationItem.leftBarButtonItems = [backButton, tableOfContentsButton, actionButton]
       
        let brightnessButton = UIBarButtonItem(image:  imageLiteral(resourceName: "Brightness"), style: .plain, target: self, action: #selector(showAppearanceMenu(_:)))
        let searchButton = UIBarButtonItem(image:  imageLiteral(resourceName: "Search"), style: .plain, target: self, action: #selector(showSearchView(_:)))
        bookmarkButton = UIBarButtonItem(image:  imageLiteral(resourceName: "Bookmark-N"), style: .plain, target: self, action: #selector(addOrRemoveBookmark(_:)))
        let composeButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.compose, target: self, action: #selector(toEditPDFPage(_:)))
        
        navigationItem.rightBarButtonItems = [composeButton,bookmarkButton, searchButton, brightnessButton]

        pdfThumbnailViewContainer.alpha = 1
        pdfView.isHidden = false
        titleLabelContainer.alpha = 1
        pageNumberLabelContainer.alpha = 1
        thumbnailGridViewConainer.isHidden = true
        outlineViewConainer.isHidden = true

        barHideOnTapGestureRecognizer.isEnabled = true

        updateBookmarkStatus()
        updatePageNumberLabel()
    }

    private func showTableOfContents() {
        view.exchangeSubview(at: 0, withSubviewAt: 1)
        view.exchangeSubview(at: 0, withSubviewAt: 2)

        let backButton = UIBarButtonItem(image:  imageLiteral(resourceName: "Chevron"), style: .plain, target: self, action: #selector(back(_:)))
        let tableOfContentsToggleBarButton = UIBarButtonItem(customView: tableOfContentsToggleSegmentedControl)
        let resumeBarButton = UIBarButtonItem(title: NSLocalizedString("Resume", comment: ""), style: .plain, target: self, action: #selector(resume(_:)))
        navigationItem.leftBarButtonItems = [backButton, tableOfContentsToggleBarButton]
        navigationItem.rightBarButtonItems = [resumeBarButton]

        pdfThumbnailViewContainer.alpha = 0

        toggleTableOfContentsView(tableOfContentsToggleSegmentedControl)

        barHideOnTapGestureRecognizer.isEnabled = false
    }

    @objc func resume(_ sender: UIBarButtonItem) {
        resume()
    }

    @objc func back(_ sender: UIBarButtonItem) {
        navigationController?.popViewController(animated: true)
    }

    @objc func showTableOfContents(_ sender: UIBarButtonItem) {
        showTableOfContents()
    }

    
    
    @objc func showActionMenu(_ sender: UIBarButtonItem) {
        if let viewController = storyboard?.instantiateViewController(withIdentifier: String(describing: ActionMenuViewController.self)) as? ActionMenuViewController {
            viewController.modalPresentationStyle = .popover
            viewController.preferredContentSize = CGSize(width: 300, height: 88)
            viewController.popoverPresentationController?.barButtonItem = sender
            viewController.popoverPresentationController?.permittedArrowDirections = .up
            viewController.popoverPresentationController?.delegate = self
            viewController.delegate = self
            present(viewController, animated: true, completion: nil)
        }
    }

    @objc func showAppearanceMenu(_ sender: UIBarButtonItem) {
        if let viewController = storyboard?.instantiateViewController(withIdentifier: String(describing: AppearanceViewController.self)) as? AppearanceViewController {
            viewController.modalPresentationStyle = .popover
            viewController.preferredContentSize = CGSize(width: 300, height: 44)
            viewController.popoverPresentationController?.barButtonItem = sender
            viewController.popoverPresentationController?.permittedArrowDirections = .up
            viewController.popoverPresentationController?.delegate = self
            present(viewController, animated: true, completion: nil)
        }
    }

    @objc func showSearchView(_ sender: UIBarButtonItem) {
        if let searchNavigationController = self.searchNavigationController {
            present(searchNavigationController, animated: true, completion: nil)
        } else if let navigationController = storyboard?.instantiateViewController(withIdentifier: String(describing: SearchViewController.self)) as? UINavigationController,
            let searchViewController = navigationController.topViewController as? SearchViewController {
            searchViewController.pdfDocument = pdfDocument
            searchViewController.delegate = self
            present(navigationController, animated: true, completion: nil)

            searchNavigationController = navigationController
        }
    }

    @objc func addOrRemoveBookmark(_ sender: UIBarButtonItem) {
        
        if let documentURL = pdfDocument?.documentURL?.absoluteString {
            var bookmarks = UserDefaults.standard.array(forKey: documentURL) as? [Int] ?? [Int]()
            if let currentPage = pdfView.currentPage,
                let pageIndex = pdfDocument?.index(for: currentPage) {
                if let index = bookmarks.index(of: pageIndex) {
                    bookmarks.remove(at: index)
                    UserDefaults.standard.set(bookmarks, forKey: documentURL)
                    bookmarkButton.image =  imageLiteral(resourceName: "Bookmark-N")
                } else {
                    UserDefaults.standard.set((bookmarks + [pageIndex]).sorted(), forKey: documentURL)
                    bookmarkButton.image =  imageLiteral(resourceName: "Bookmark-P")
                }
            }
        }
    }

    @objc func toEditPDFPage(_ sender: UIBarButtonItem)
    {
        editActionButStckVw.isHidden = false
        barHideOnTapGestureRecognizer.isEnabled = false
        hideBars()
        whichTask = "text"
        
//        deleteInKAnno()
        
        
        
        
//        showPickerPop()
    }
    
    @objc func toggleTableOfContentsView(_ sender: UISegmentedControl) {
        pdfView.isHidden = true
        titleLabelContainer.alpha = 0
        pageNumberLabelContainer.alpha = 0

        if tableOfContentsToggleSegmentedControl.selectedSegmentIndex == 0 {
            thumbnailGridViewConainer.isHidden = false
            outlineViewConainer.isHidden = true
            bookmarkViewConainer.isHidden = true
        } else if tableOfContentsToggleSegmentedControl.selectedSegmentIndex == 1 {
            thumbnailGridViewConainer.isHidden = true
            outlineViewConainer.isHidden = false
            bookmarkViewConainer.isHidden = true
        } else {
            thumbnailGridViewConainer.isHidden = true
            outlineViewConainer.isHidden = true
            bookmarkViewConainer.isHidden = false
        }
    }

    @objc func pdfViewPageChanged(_ notification: Notification) {
        
        BezierPathAddArr.removeAll()
        inkAnnotationArr.removeAll()
        
        if pdfViewGestureRecognizer.isTracking {
            hideBars()
            
            let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
            getPreviousDrawOnCurrentPage(currPageNum: getPagenumber)
//            print("getVBezierPathAddArr      ", BezierPathAddArr)
        }
        else
        {
            
        }
        updateBookmarkStatus()
        updatePageNumberLabel()
        
        
        
        drawNumCount = BezierPathAddArr.count
        
    }

    @objc func gestureRecognizedToggleVisibility(_ gestureRecognizer: UITapGestureRecognizer) {
        if let navigationController = navigationController {
            if navigationController.navigationBar.alpha > 0 {
                hideBars()
            } else {
                showBars()
            }
        }
    }

    private func updateBookmarkStatus() {
        
        if let documentURL = pdfDocument?.documentURL?.absoluteString,
            let bookmarks = UserDefaults.standard.array(forKey: documentURL) as? [Int],
            let currentPage = pdfView.currentPage,
            let index = pdfDocument?.index(for: currentPage) {
            bookmarkButton.image = bookmarks.contains(index) ?  imageLiteral(resourceName: "Bookmark-P") :  imageLiteral(resourceName: "Bookmark-N")
        }
    }

    private func updatePageNumberLabel() {
        if let currentPage = pdfView.currentPage, let index = pdfDocument?.index(for: currentPage), let pageCount = pdfDocument?.pageCount {
            pageNumberLabel.text = String(format: "%d/%d", index + 1, pageCount)
        } else {
            pageNumberLabel.text = nil
        }
    }

    private func showBars() {
        if let navigationController = navigationController {
            UIView.animate(withDuration: CATransaction.animationDuration()) {
                navigationController.navigationBar.alpha = 1
                self.pdfThumbnailViewContainer.alpha = 1
                self.titleLabelContainer.alpha = 1
                self.pageNumberLabelContainer.alpha = 1
                
                navigationController.navigationBar.isHidden = false
                self.pdfThumbnailViewContainer.isHidden = false
                self.titleLabelContainer.isHidden = false
                self.pageNumberLabelContainer.isHidden = false
            }
        }
    }

    private func hideBars() {
        if let navigationController = navigationController {
            UIView.animate(withDuration: CATransaction.animationDuration()) {
                navigationController.navigationBar.alpha = 0
                self.pdfThumbnailViewContainer.alpha = 0
                self.titleLabelContainer.alpha = 0
                self.pageNumberLabelContainer.alpha = 0
                
                navigationController.navigationBar.isHidden = true
                self.pdfThumbnailViewContainer.isHidden = true
                self.titleLabelContainer.isHidden = true
                self.pageNumberLabelContainer.isHidden = true
            }
        }
    }
    
    
    
    override func touchesBegan(_ touches: Set, with event: UIEvent?) {
        
        pdfBezierPath.removeAllPoints()
        if let touch = touches.first
        {
            isTouchMoved = false
            
            if touch.view == drawView
            {
                let position = touch.location(in: drawView)
                print("\n\npositionBefo   ",position)
                guard let page = pdfView.page(for: position, nearest: true) else {
                    return
                }
                
                let locationOnPage = pdfView.convert(position, to: page)
                lastLocationPoint = locationOnPage
                lastPoint = position
                pdfBezierPath.move(to: locationOnPage)
            }
            
        }
    }
    
    override func touchesMoved(_ touches: Set, with event: UIEvent?) {
        
        if let touch = touches.first
        {
            if touch.view == drawView
            {
                isTouchMoved = true
                
                let position = touch.location(in: drawView)
                
                guard let page = pdfView.page(for: position, nearest: true) else {
                    return
                }
                let locationOnPage = pdfView.convert(position, to: page)
                
                currentPointSelec = position
                BezierPath.move(to: lastPoint)
                BezierPath.addLine(to: currentPointSelec)
                pdfBezierPath.move(to: lastLocationPoint)
                pdfBezierPath.addLine(to: locationOnPage)
                let shapeLayer = CAShapeLayer()
                shapeLayer.name = String(touchCount)
                shapeLayer.path = BezierPath.cgPath
                shapeLayer.strokeColor = colorForeground.cgColor
                shapeLayer.fillColor = UIColor.clear.cgColor
                shapeLayer.lineWidth = 5.0
                
                
                drawView.layer.addSublayer(shapeLayer)
                
                lastPoint = currentPointSelec
                lastLocationPoint = locationOnPage
            }
            
        }
    }
    
    override func touchesEnded(_ touches: Set, with event: UIEvent?) {
        
        if let touch = touches.first
        {
            if touch.view == drawView
            {
                let position = touch.location(in: drawView)
                guard let page = pdfView.page(for: position, nearest: true) else {
                    return
                }
                
                let pageBounds = pdfView.currentPage?.bounds(for: .mediaBox)
                
                let b = PDFBorder()
                b.lineWidth = 10.0
                let inkAnnotation = PDFAnnotation(bounds: pageBounds!, forType: PDFAnnotationSubtype.ink, withProperties: nil)
                
                inkAnnotation.add(pdfBezierPath)
                
//                inkAnnotation.backgroundColor = UIColor.yellow
                inkAnnotation.border = b
                inkAnnotation.color = colorForeground.withAlphaComponent(0.0)
                
                inkAnnotationArr.append(inkAnnotation)
                
                print("pdfBezierPathpdfBezierPathpdfBezierPath    ", pdfBezierPath)
                print("BezierPathAddArrBezierPathAddArr    ", pdfBezierPath.cgPath.getPathElementsPoints())
//                BezierPathAddArr.append()
                let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
                drawNumCount = drawNumCount + 1
                
                var createdDict = [String : Any]()
                
                createdDict["BezierPathPoints"] = pdfBezierPath.cgPath.getPathElementsPoints()
                createdDict["BezierPathColor"] = colorForeground
                
                currentDrawAddArr.append(createdDict)
//                BezierPathAddArr.append(createdDict)
//
//                totalBezierPathDict["fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)"] = BezierPathAddArr
//                UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: self.totalBezierPathDict), forKey: "BezierPathStorage")
                
//                let index = pdfDocument?.index(for: pdfView.currentPage!)
                
                
//                pdfView.document?.page(at: index!)?.addAnnotation(inkAnnotation)
                
                pdfView.currentPage?.addAnnotation(inkAnnotation)
                
                BezierPath.close()
                pdfBezierPath.close()
                
                BezierPath.removeAllPoints()
                
                if isTouchMoved == false
                {

                }
                else
                {
                    previousTouchCount = previousTouchCount + 1
                    touchCount = previousTouchCount
                }
            }
        }
    }
    
    func getPreviousDrawOnCurrentPage(currPageNum: Int)
    {
        print("HowCurrPageNum      ", currPageNum)
        if totalBezierPathDict.count > 0
        {
            for (key, value) in totalBezierPathDict
            {
                let charset = CharacterSet(charactersIn: "fileNumber\(pdfClickedRow)")
                
                if key.rangeOfCharacter(from: charset) != nil
                {
                    let gettPageNum = Int(key.components(separatedBy: "PageNumber")[1])
                    
                    if gettPageNum == currPageNum
                    {
                        for path in value
                        {
                            print("Pathqwe1234234234")
                            BezierPathAddArr.append(path)
                        }
                        break
                    }
                    else
                    {
                        continue
                    }
                }
            }
        }
        
        print("HowManyPrevVlaues      ", BezierPathAddArr.count)
    }
    
    //MARK: - DRAW ON PDF
    @objc func drawingOnPDF()
    {
        whichTask = "draw"
        drawView.isHidden = false
        drawView.backgroundColor = UIColor.clear
        //        drawView.alpha = 0.1
        
        actionsButStckVw.isHidden = false
        bottomColorView.isHidden = false
        sideWidthHeightVw.isHidden = true
        
        barHideOnTapGestureRecognizer.isEnabled = false
        hideBars()
    }
    
    @objc func TextOnPDF()
    {
        drawView.isHidden = true
        drawView.backgroundColor = UIColor.clear
        
        actionsButStckVw.isHidden = false
        
        whichTask = "text"
        
        let linkAnn = PDFAnnotation.init(bounds: CGRect(x: 150, y: 450, width: 150, height: 100), forType: PDFAnnotationSubtype.widget, withProperties: nil)
        linkAnn.widgetFieldType = .text
        linkAnn.isMultiline = true
        linkAnn.widgetStringValue = "\(AddTextCount + 1). "
        linkAnn.font = .systemFont(ofSize: 20)
        linkAnn.fontColor = UIColor.darkGray
        linkAnn.backgroundColor = UIColor.orange.withAlphaComponent(0.2)
        linkAnn.setValue("addtext\(AddTextCount)", forAnnotationKey: PDFAnnotationKey.name)
        pdfView.currentPage?.addAnnotation(linkAnn)
        bottomColorView.isHidden = true
        bottomColorView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
        sideWidthHeightVw.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
        sideWidthHeightVw.isHidden = true
        barHideOnTapGestureRecognizer.isEnabled = false
        hideBars()
    }
    
    //MARK: - ANNOTATION EDIT TAP ACN
    
    @IBAction func saveTapAcn(_ sender: UITapGestureRecognizer) {
        
        drawView.isHidden = true
        drawView.layer.sublayers = nil
        
        if whichTask == "draw"
        {
            print("inkAnnotationArrinkAnnotationArr   ", inkAnnotationArr)
            let index : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
            
            for anno in inkAnnotationArr
            {
                anno.color = colorForeground
                
                pdfView.document?.page(at: index)?.addAnnotation(anno)
            }
            
            for i in currentDrawAddArr
            {
                var dict = i
                dict["BezierPathColor"] = colorForeground
                BezierPathAddArr.append(dict)
            }
            
//            BezierPathAddArr.append(currentDrawAddArr)
            
            totalBezierPathDict["fileNumber\(pdfClickedRow)PageNumber\(index)"] = BezierPathAddArr
            UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: self.totalBezierPathDict), forKey: "BezierPathStorage")
            
        }
        else if whichTask == "text"
        {
//            AddTextCount = AddTextCount + 1
//            UserDefaults.standard.set(AddTextCount, forKey: "addTextCount")
        }
        actionsButStckVw.isHidden = true
        sideWidthHeightVw.isHidden = true
        bottomColorView.isHidden = true
        
        whichTask = "goingToEdit"
        let menuItem3 = UIMenuItem(title: "Draw", action: #selector(drawingOnPDF))
        let menuItem4 = UIMenuItem(title: "Text", action: #selector(TextOnPDF))
        UIMenuController.shared.menuItems = [menuItem3, menuItem4]
        editActionButStckVw.isUserInteractionEnabled = true
        editActionButStckVw.alpha = 1.0
        currentDrawAddArr.removeAll()
        
        inkAnnotationArr.removeAll()
    }
    
    @IBAction func deleteTapAcn(_ sender: UITapGestureRecognizer) {
        
        
        
    }
    
    func distance(from lhs: CGPoint, to rhs: CGPoint) -> CGFloat {
        return hypot(lhs.x.distance(to: rhs.x), lhs.y.distance(to: rhs.y))
    }
    
    @IBAction func cancelTapAcn(_ sender: UITapGestureRecognizer) {
        
        print("cancel_Tap")
        drawView.isHidden = true
        drawView.layer.sublayers = nil
        
        sideWidthHeightVw.isHidden = true
        bottomColorView.isHidden = true
        actionsButStckVw.isHidden = true
        
        if whichTask == "draw"
        {
            inkAnnotationArr.removeAll()
            currentDrawAddArr.removeAll()
        }
        if whichTask == "text"
        {
            let getAllAnnotations = pdfView.currentPage?.annotations
            
            for ann in getAllAnnotations!
            {
                let getBounds = ann.bounds
                if Int(getBounds.origin.x) == Int(lastTextAnnoPoint.x)
                {
                    if Int(getBounds.origin.y) == Int(lastTextAnnoPoint.y)
                    {
                        pdfView.currentPage?.removeAnnotation(ann)
                        
                        getPDFFrame(todo: "deleteTextVw")
                        
//                        print("-->>annDEnyStyr    ", ann.contents)
                        break
                    }
                }
                else
                {
                    
                }
            }
//            MovingTextViewAnnotation(forWhich: "cancel")
        }
        
        
        whichTask = "goingToEdit"
//        let menuItem3 = UIMenuItem(title: "Draw", action: #selector(drawingOnPDF))
//        let menuItem4 = UIMenuItem(title: "Text", action: #selector(TextOnPDF))
//        UIMenuController.shared.menuItems = [menuItem3, menuItem4]
        
        editActionButStckVw.isUserInteractionEnabled = true
        editActionButStckVw.alpha = 1.0
    }
    
    @IBAction func longPressTapAcn(_ sender: UILongPressGestureRecognizer) {
        
        let touchPoint = sender.location(in: self.drawView)
//        guard let page = pdfView.page(for: touchPoint, nearest: true) else {
//            return
//        }
        
        print("touchPoint   ", touchPoint)
        
        print("drawView.layer.sublayersdrawView.layer.sublayers  ", drawView.layer.sublayers)
        
        for laySub in drawView.layer.sublayers!
        {
            if laySub.isKind(of: CAShapeLayer.self)
            {
                if laySub.name == "gk"
                {
                    print("layPoslayPos   ", laySub)
                }
            }
        }
        
//        let locationOnPage = pdfView.convert(touchPoint, to: page)
//        page.annotation(at: locationOnPage)
        
    }
    
    //MARK:- SPACING MENU
    func SpacingMenuAction() {
        becomeFirstResponder()
        let menu = UIMenuController.shared
        let One = UIMenuItem(title: "1", action: #selector(spacingOne))
        let Two = UIMenuItem(title: "2", action: #selector(spacingTwo))
        let Five = UIMenuItem(title: "5", action: #selector(spacingFive))
        let Eleven = UIMenuItem(title: "11", action: #selector(spacingEleven))
        let Seventeen = UIMenuItem(title: "17", action: #selector(spacingSeventeen))
        menu.menuItems = [One, Two, Five, Eleven, Seventeen]
        menu.setTargetRect(CGRect(x:sideWidthHeightVw.frame.origin.x, y:sideWidthHeightVw.frame.origin.y, width: 150, height:50), in: self.drawView)
        menu.setMenuVisible(true, animated: true)
    }
    
    @objc func spacingOne()
    {
        spacingNumber = 1.0
        spacingLbl.text = String(Int(spacingNumber))
    }
    @objc func spacingTwo()
    {
        spacingNumber = 2.0
        spacingLbl.text = String(Int(spacingNumber))
    }
    @objc func spacingFive()
    {
        spacingNumber = 5.0
        spacingLbl.text = String(Int(spacingNumber))
    }
    @objc func spacingEleven()
    {
        spacingNumber = 11.0
        spacingLbl.text = String(Int(spacingNumber))
    }
    @objc func spacingSeventeen()
    {
        spacingNumber = 17.0
        spacingLbl.text = String(Int(spacingNumber))
    }
    
    func drawAnnotationColorAction()
    {
        print("\n\ntoucnt    ",touchCount)
        for i in 0..<touchcount
        {
            if drawView.layer.sublayers != nil
            {
                for laySub in drawView.layer.sublayers!
                {
                    if laySub.isKind(of: CAShapeLayer.self)
                    {
                        let caLaye : CAShapeLayer = laySub as! CAShapeLayer
                        caLaye.strokeColor = colorForeground.cgColor
                    }
                    
                }
            }
            
        }
        
    }
    
    @IBAction func redColorTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.red
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    @IBAction func brownColorTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.brown
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    @IBAction func yellowColorTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.yellow
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    
    @IBAction func magentaColorTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.magenta
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    
    @IBAction func OrangeTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.orange
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    @IBAction func blueTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.blue
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    @IBAction func greenTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.green
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    @IBAction func blackTapAcn(_ sender: UITapGestureRecognizer) {
        
        colorForeground = UIColor.black
        if whichTask == "text"
        {
            MovingTextViewAnnotation(forWhich: "color")
        }
        else if whichTask == "draw"
        {
            drawAnnotationColorAction()
        }
    }
    
    
    @IBAction func spacingTapAcn(_ sender: UITapGestureRecognizer) {
        SpacingMenuAction()
    }
    
    @IBAction func widthTapAcn(_ sender: UITapGestureRecognizer) {
        
        MovingTextViewAnnotation(forWhich: "width")
    }
    
    @IBAction func heightTapAcn(_ sender: UITapGestureRecognizer) {
        MovingTextViewAnnotation(forWhich: "height")
    }
    
    @IBAction func topMoveTapAcn(_ sender: UITapGestureRecognizer) {
        
        MovingTextViewAnnotation(forWhich: "bottom")
        
    }
    
    @IBAction func bottomMoveTapAcn(_ sender: UITapGestureRecognizer) {
        
        MovingTextViewAnnotation(forWhich: "top")
        
    }
    
    @IBAction func leftMoveTapAcn(_ sender: UITapGestureRecognizer) {
        
        MovingTextViewAnnotation(forWhich: "left")
    }
    
    @IBAction func rightMoveTapAcn(_ sender: UITapGestureRecognizer) {
        
        MovingTextViewAnnotation(forWhich: "right")
    }
    
    //MARK:- KEYBOARD
    @objc func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
            
            isDoneButtonPressed = false
            
            print("\n\nKBShowingg       ------>>>     ")
            
            //            if whichTask == "text"
            //            {
            if hasKeyboardChanged == false
            {
                getPDFFrame(todo: "firstResponder")
                //                    whichTask = "firstTry"
                getPDFFrame(todo: "default")
            }
            
        }
    }
    
    @objc func keyboardWillHide(notification: NSNotification) {
        
        hasKeyboardChanged = false
        
        if isDoneButtonPressed == false
        {
            getPDFFrame(todo: "removeArrowSuviews")
            
            switch (deviceIdiom) {
                
            case .pad:
                colorForeground = usingFontColor
                MovingTextViewAnnotation(forWhich: "color")
                MovingTextViewAnnotation(forWhich: "font")
                MovingTextViewAnnotation(forWhich: "BGColor")
                
            case .phone:
                print("iPhonekb and iPod touch style UI")
                
//                MovingTextViewAnnotation(forWhich: "height")
//                MovingTextViewAnnotation(forWhich: "width")
//                MovingTextViewAnnotation(forWhich: "fingerPan")
//
//                colorForeground = usingFontColor
//                MovingTextViewAnnotation(forWhich: "color")
//                MovingTextViewAnnotation(forWhich: "font")
//                MovingTextViewAnnotation(forWhich: "BGColor")
                
            default:
                print("Unspecified UI idiom")
            }
        }
        
        print("\n\nKBHidingingg       ------>>>     ")
    }
    
    func getAllAnnotationInThisPage()
    {
        var textAnnoNameArr = [String]()
        
        let getAllAnnotations = pdfView.currentPage?.annotations
        
        for ann in getAllAnnotations!
        {
            if let nameStr = ann.contents as? String
            {
                let charset = CharacterSet(charactersIn: "addtext")
                
                if nameStr.rangeOfCharacter(from: charset) != nil
                {
                    print("annannann   Bounds     ", ann.bounds)
                    textAnnoNameArr.append(nameStr)
                    print("yes")
                    
                }
            }
        }
        
        AddTextCount = textAnnoNameArr.count
        
        print("textAnnoNameArrtextAnnoNameArr   ", textAnnoNameArr.count)
        print("textAnnoNameArrtextAnnoNameArr   ", textAnnoNameArr)
    }
    
    func deleteInKAnno()
    {
        let getAllAnnotations = pdfView.currentPage?.annotations
        
        for ann in getAllAnnotations!
        {
            if ann.type == "Highlight"
            {
                print("ann.typeann.type     ", ann.type)
                pdfView.currentPage?.removeAnnotation(ann)
            }
        }
        
    }
    
    func findHavingTextAnnotation(annoPoint: CGPoint)
    {
        
        print("annoPointannoPoint      ", annoPoint)
        whichTask = "text"
        
        editActionButStckVw.isHidden = false
        editActionButStckVw.isUserInteractionEnabled = false
        editActionButStckVw.alpha = 0.3
        
//        getAllAnnotationInThisPage()
        
        let getAllAnnotations = pdfView.currentPage?.annotations
        
        for ann in getAllAnnotations!
        {
            let getBounds = ann.bounds
            print("getBounds     ", getBounds)
            print("getBoundsX     ", getBounds.origin.x)
            print("getBoundsY     ", getBounds.origin.y)
            print("getBoundsIntX     ", Int(getBounds.origin.x))
            print("getBoundsIntY     ", Int(getBounds.origin.y))
            if Int(getBounds.origin.x) == Int(annoPoint.x)
            {
                if Int(getBounds.origin.y) == Int(annoPoint.y)
                {
                    print("workingGud")
                    
                    let getContentStr : String = ann.contents!
                    
                    
                    let comp = getContentStr.components(separatedBy: "addtext")
                    
                    print("getContentStrgetContentStr   ",getContentStr)
                    
                    actionsButStckVw.isHidden = false
                    
                    addTxtCount = comp[1]
                    
                    usingFontColor = ann.fontColor!
                    usingFontName = (ann.font?.fontName)!
                    usingFontSize = Int((ann.font?.fontDescriptor.pointSize)!)
                    
                    let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
                    print("getPagenumbergetPagenumber  ",getPagenumber)
                    
                    print("-->>> fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(addTxtCount)")
                    
                    var createdColorDict = [String : Any]()
                    createdColorDict = textAnnoStoredDict["fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(addTxtCount)"]!
                    
                    usingBGFontColor = createdColorDict["BGColor"] as! UIColor
                    usingBGFontAlpha = createdColorDict["BGOpacity"] as! CGFloat
                    
                    print("\n\nusingFontColorusingFontColor ", usingFontColor)
                    print("\n\nusfusingsdfdAlpha ", usingBGFontAlpha)
                    
                    for (key, value) in fontColorList {
                        
                        if value == usingFontColor
                        {
                            selectedRowColor = key
                            break
                        }
                    }
                    for (key, value) in fontFamilyName {
                        
                        if value == usingFontName
                        {
                            selectedRowFont = key
                            break
                        }
                    }
                    for (key, value) in fontSizeList {
                        
                        if value == CGFloat(usingFontSize)
                        {
                            selectedRowSize = key
                            break
                        }
                    }
                    
                    for (key, value) in fontColorList {
                        
                        if value == usingBGFontColor
                        {
                            selectedBGRowColor = key
                            break
                        }
                    }
                    for (key, value) in bgOpacityList {
                        
                        if value == usingBGFontAlpha
                        {
                            selectedBGAlpha = key
                            break
                        }
                    }
                    
                    textVwMovedX = ann.bounds.origin.x
                    textVwMovedY = ann.bounds.origin.y + usingHeightText // SET DEFAULT HEIGHT
                    
                    print("\n\nXmovTxt    ", textVwMovedX)
                    print("YmovTxt    ", textVwMovedY)
                    print("\n")
                    
//                    print("selectselectedRowColorowColor    ", selectedRowColor)
//                    print("selectedBGRowColorselectedBGRowColor    ", selectedBGRowColor)
//                    print("selectedBGAlphaselectedBGAlpha    ", selectedBGAlpha)
                    
                    print("aaalllll   annnnn       ", ann)
                    
                    return
                }
            }
        }
        
//        pdfView.currentPage?.annotation(at: <#T##CGPoint#>)
        
        
//        let ann : PDFAnnotation = (pdfView.currentPage?.annotation(at: CGPoint(x: 35, y: 715)))!
        
        
//        print("ann    ",ann.type)
//        print("ann    ",ann.bounds)
//        print("ann    ",ann.backgroundColor)
//        print("ann    ",ann.widgetStringValue)
//        print("ann    ",ann.font)
//        print("ann    ",ann.font?.fontDescriptor.pointSize)
//        print("ann    ",ann.fontColor)
//        print("ann    ",ann.contents)
        
            
        
//        }
        
        
    }
//    func getStoredTextViewDetailsFromUserDefaults()
//    {
//        //1. TOEDITPDF
//
//    }
//    func toSaveTextViewDetailsToUserDefaults()
//    {
//        //1. BLACKTEXTTAPACN
//        //2. MOVINGTEXTVIEWANNOTATION
//    }
    
    func MovingTextViewAnnotation(forWhich: String)
    {
        
        if whichTask == "text"
        {
            let getAllAnnotations = pdfView.currentPage?.annotations
            for ann in getAllAnnotations!
            {
                if let nameStr = ann.contents as? String
                {
                    print("nameStrnameStr    ", nameStr)
                    let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
                    
                    print("addTxtCoaddTxtCount      ",addTxtCount)
                    
                    if nameStr == "fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(addTxtCount)"
                    {
                        print("B:   ", ann.bounds)
                        
                        if forWhich == "top"
                        {
                            ann.bounds.origin.y = ann.bounds.origin.y - spacingNumber
                        }
                        else if forWhich == "bottom"
                        {
                            ann.bounds.origin.y = ann.bounds.origin.y + spacingNumber
                        }
                        else if forWhich == "left"
                        {
                            ann.bounds.origin.x = ann.bounds.origin.x - spacingNumber
                        }
                        else if forWhich == "right"
                        {
                            ann.bounds.origin.x = ann.bounds.origin.x + spacingNumber
                        }
                        else if forWhich == "width"
                        {
//                            ann.bounds.size.width = ann.bounds.size.width + spacingNumber
//                            usingWidthText = ann.bounds.size.width
//                            getPDFFrame(todo: "widthChange")
                            
                            ann.bounds.size.width = usingWidthText
                        }
                        else if forWhich == "height"
                        {
//                            ann.bounds.size.height = ann.bounds.size.height + spacingNumber
//                            usingHeightText = ann.bounds.size.height
//                            getPDFFrame(todo: "heightChange")
                            
                            
                            ann.bounds.size.height = usingHeightText
                        }
                        else if forWhich == "color"
                        {
                            ann.fontColor = colorForeground
                        }
                        else if forWhich == "font"
                        {
                            print("CGFloat(usingFontSize)CGFloat(usingFontSize)  ", CGFloat(usingFontSize))
                            ann.font = UIFont(name: usingFontName, size: CGFloat(usingFontSize))
                            
                            let gettingSize = GettingTextViewSize(getStr: ann.widgetStringValue!, fontSize: CGFloat(usingFontSize), widthAnno: ann.bounds.size.width)
                            if usingHeightText < gettingSize.height
                            {
                                getPDFFrame(todo: "sizeChangeByFont")
                            }
                            
                            print("gettingSizegettingSize   ", gettingSize)
                        }
                        else if forWhich == "BGColor"
                        {
                            ann.backgroundColor = usingBGFontColor.withAlphaComponent(usingBGFontAlpha)
                            
                            let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
                            var createdColorDict = [String : Any]()
                            createdColorDict["BGColor"] = usingBGFontColor
                            createdColorDict["BGOpacity"] = usingBGFontAlpha
                            
                            textAnnoStoredDict["fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(addTxtCount)"] = createdColorDict
                            
                            print("OverridetextAnnoStoredDict   ", textAnnoStoredDict)
                        }
                        else if forWhich == "fingerPan"
                        {
                            print("\n\ntextMovX   ", textVwMovedX)
                            print("textMvY   ", textVwMovedY)
                            ann.bounds.origin.x = textVwMovedX
                            ann.bounds.origin.y = textVwMovedY - usingHeightText // TEXTVIEW HEIGHT [100]
                            
                            lastTextAnnoPoint = CGPoint(x: ann.bounds.origin.x, y: ann.bounds.origin.y)
                        }
                        else if forWhich == "cancel"
                        {
                            pdfView.currentPage?.removeAnnotation(ann)
                        }
                        
                        return
                    }
                    
                }
                
            }
        }
    }
    
    
    func GettingTextViewSize(getStr : String, fontSize: CGFloat, widthAnno : CGFloat) -> CGSize
    {
        var textSize = (getStr as! NSString).size(withAttributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: fontSize)])
        if textSize.width > widthAnno
        {
            // IF STRING WIDTH GREATER THAN TABLEVIEW WIDTH
            let multipleValue = textSize.width / widthAnno
            textSize.height = (textSize.height * (multipleValue + 1.0))
            textSize.width = widthAnno
            
            
        }
        else
        {
            textSize.height = textSize.height + 5 //ADDING EXTRA SPACE
            textSize.width = textSize.width + 5 //ADDING EXTRA SPACE
        }
        
        return textSize
    }
    
    @IBAction func blackDrawTapAcn(_ sender: UITapGestureRecognizer) {
        
        editActionButStckVw.isUserInteractionEnabled = false
        editActionButStckVw.alpha = 0.3
//
        whichTask = "draw"
        drawView.isHidden = false
        drawView.backgroundColor = UIColor.clear
//                drawView.alpha = 0.1
//
        actionsButStckVw.isHidden = false
        bottomColorView.isHidden = false
        sideWidthHeightVw.isHidden = true
        
        barHideOnTapGestureRecognizer.isEnabled = false
        hideBars()
        
    }
    
    @IBAction func blackTextTapAcn(_ sender: UITapGestureRecognizer) {
        
        getAllAnnotationInThisPage()
        
        print("afterGetAllAnno")
        
        let getPagenumber : Int = (pdfDocument?.index(for: pdfView.currentPage!))!
    
        editActionButStckVw.isUserInteractionEnabled = false
        editActionButStckVw.alpha = 0.3
        
        drawView.isHidden = true
        drawView.backgroundColor = UIColor.clear
        
        actionsButStckVw.isHidden = false
        
        whichTask = "text"
        
        usingWidthText = 150.0
        usingHeightText = 100.0
        
        textVwMovedX = 150
        
        AddTextCount = AddTextCount + 1
        
        print("adTxCou    ",AddTextCount)
        
        let linkAnn = PDFAnnotation.init(bounds: CGRect(x: 150, y: 450, width: 150, height: usingHeightText), forType: PDFAnnotationSubtype.widget, withProperties: nil)
         linkAnn.widgetFieldType = .text
         linkAnn.isMultiline = true
        linkAnn.contents = "fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(AddTextCount)"   //"\(AddTextCount)"
         linkAnn.widgetStringValue = "hi "

         linkAnn.font = UIFont(name: usingFontName, size: CGFloat(usingFontSize))
         linkAnn.fontColor = usingFontColor
         linkAnn.backgroundColor = usingBGFontColor.withAlphaComponent(usingBGFontAlpha)
         linkAnn.setValue("addtext\(AddTextCount)", forAnnotationKey: PDFAnnotationKey.name)
        
        print("linkAnn.cont   ",linkAnn.contents)


        
        let index = pdfDocument?.index(for: pdfView.currentPage!)
        pdfView.document?.page(at: index!)?.addAnnotation(linkAnn)
        
        var createdColorDict = [String : Any]()
        createdColorDict["BGColor"] = usingBGFontColor
        createdColorDict["BGOpacity"] = usingBGFontAlpha
        
        textAnnoStoredDict["fileNumber\(pdfClickedRow)PageNumber\(getPagenumber)addtext\(AddTextCount)"] = createdColorDict
        
        
//        pdfView.currentPage?.addAnnotation(linkAnn)
        bottomColorView.isHidden = false
        bottomColorView.backgroundColor = UIColor(red: 0/255, green: 0/255, blue: 0/255, alpha: 1.0)
        sideWidthHeightVw.backgroundColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1.0)
        sideWidthHeightVw.isHidden = true
        barHideOnTapGestureRecognizer.isEnabled = false
        hideBars()
        
//        getPDFFrame()
    }
    
    
    @IBAction func blackSaveTapAcn(_ sender: UITapGestureRecognizer) {
        
        //ACTION SHEET
        
        
        let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        
        // create an action
        let firstAction: UIAlertAction = UIAlertAction(title: "Replace", style: .default) { action -> Void in
            
            
            self.pdfDocument?.write(to: (self.pdfDocument?.documentURL)!)
            
            //BEZIERPATH NOT WORKIN
            print("\n\ntextAnnoStoredDicttextAnnoStoredDictv       ", self.textAnnoStoredDict)
//            UserDefaults.standard.set(self.textAnnoStoredDict, forKey: "TextStorage")
            UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: self.textAnnoStoredDict), forKey: "TextStorage")
            
            self.editActionButStckVw.isHidden = true
            self.barHideOnTapGestureRecognizer.isEnabled = true
            self.showBars()
            
            
            
            print("First Action pressed")
            
            
        }
        
        let secondAction: UIAlertAction = UIAlertAction(title: "Create New", style: .default) { action -> Void in
            
            if let path = self.pdfDocument?.documentURL?.absoluteString, let document = self.pdfView.document {

                print("\n\nPath   ", path)
                print("document   ", document)
                
//                self.pdfDocument?.write(to: (self.pdfDocument?.documentURL)!)
                self.convertPDFtoImageToShare()
                
                let fileManager = FileManager.default
                do {
                    let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
                    let fileURL : URL = documentDirectory.appendingPathComponent("newsample.pdf")
                    
                    print("\n\nfileURL   ", fileURL)
//                    print("document   ", document)
                    
                    
//                    for img in self.PdfImagesArr
//                    {
//                        try self.createPDF(image: img)?.write(to: fileURL)
//
//                        break
//
////                        self.createPDF(image: img)?.write(to: fileURL, atomically: true)
//
//
//
//                    }
                    
                    var pdfDoc = PDFDocument() // = PDFDocument(url: fileURL)!
                    var pgCoun : Int = 0
                    
                    for img in 0..<self.pdfimagesarr.count
                    {
                        
                        let c_img = self.PdfImagesArr[img].cgImage
                        
                        let newImg = UIImage(cgImage: c_img!, scale: self.PdfImagesArr[img].scale, orientation: UIImageOrientation.downMirrored)
                        
                        let pfPage : PDFPage = PDFPage(image: newImg)!
                        
                        pdfDoc.insert(pfPage, at: pgCoun)
                        
                        pgCoun = pgCoun + 1
                    }
                    
                    pdfDoc.write(to: fileURL)
                    

                } catch {
                    print(error)
                }

                
            }
            
            print("Second Action pressed")
        }
        
        let thirdAction: UIAlertAction = UIAlertAction(title: "Remove All", style: .default) { action -> Void in
            
            self.editActionButStckVw.isHidden = true
            self.barHideOnTapGestureRecognizer.isEnabled = true
            self.showBars()
            
            print("remove Action pressed")
        }
        
        let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in }
        
        // add actions
        actionSheetController.addAction(firstAction)
        actionSheetController.addAction(secondAction)
        actionSheetController.addAction(thirdAction)
        actionSheetController.addAction(cancelAction)
        
        
        switch (deviceIdiom) {
        case .pad:
            
           actionSheetController.preferredContentSize = CGSize(width:100,height:250)
          
           actionSheetController.popoverPresentationController?.sourceView = blackSaveButVw
           
           actionSheetController.popoverPresentationController?.sourceRect = CGRect(x:20,y:40,width:0,height:0)
//           actionSheetController.popoverPresentationController?.barButtonItem = self.navigationItem.rightBarButtonItem
            present(actionSheetController, animated: true, completion: nil)
            
        case .phone:
            
            present(actionSheetController, animated: true, completion: nil)
            
        default:
            print("Unspecified UI idiom")
        }
        
    }
    
    
    @IBAction func blackiCloudTapAcn(_ sender: UITapGestureRecognizer) {
        
        let docPickCont = UIDocumentPickerViewController(documentTypes: [String(kUTTypePDF)], in: .import)
        docPickCont.delegate = self
        present(docPickCont, animated: true, completion: nil)
    }
    
    func convertPDFtoImageToShare()
    {
        
        let pageCount : Int = (pdfDocument?.pageCount)!
        
        for i in 0..<pagecount
        {
            let page = pdfDocument?.page(at: i)!
            let rect = page?.bounds(for: PDFDisplayBox.mediaBox)
            let renderer = UIGraphicsImageRenderer(size: (rect?.size)!)
            
            let image = renderer.image(actions: { context in
                
                let cgContext = context.cgContext
                
                cgContext.setFillColor(gray: 1, alpha: 1)
                cgContext.fill(CGRect(x: 0, y: 0, width: (rect?.size.width)!, height: (rect?.size.height)!))
                
                cgContext.translateBy(x: 0, y: (rect?.size.height)!)
                cgContext.scaleBy(x: 1, y: -1)
                
                page?.draw(with: PDFDisplayBox.mediaBox, to: cgContext)
                
                
                print("GoingTofinished")
                
            })
            
            
            PdfImagesArr.append(image)
            
            UIGraphicsEndImageContext()
        }
        
        
        
        print("finished    ", PdfImagesArr.count)
        let imgVw = UIImageView(frame: self.drawView.frame)
            imgVw.backgroundColor = UIColor.red
            imgVw.image = PdfImagesArr[1]
        
            self.view.addSubview(imgVw)
        
    }
    
    func createPDF(image: UIImage) -> NSData? {
        
        let pdfData = NSMutableData()
        let pdfConsumer = CGDataConsumer(data: pdfData as CFMutableData)!
        
        var mediaBox = CGRect.init(x: 0, y: 0, width: image.size.width, height: image.size.height)
        
        let pdfContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
        
        pdfContext.beginPage(mediaBox: &mediaBox)
        pdfContext.draw(image.cgImage!, in: mediaBox)
        pdfContext.endPage()
        
        return pdfData
    }
    
    func getPDFFrame(todo: String)
    {
        let pdfSubVws = pdfView.subviews
        print("subVws  ",pdfSubVws)
        
        for subVws in pdfSubVws
        {
            if (String(describing: subVws).range(of:"UIPageViewControllerContentView") != nil)
            {
                let pageVc = subVws.subviews
                
                for subVws in pageVc
                {
                    if (String(describing: subVws).range(of:"UIQueuingScrollView") != nil)
                    {
                        let QueueVc = subVws.subviews
//                        print("QueueVcQueueVc  ", QueueVc)
                        for subVws in QueueVc
                        {
                            if (String(describing: subVws).range(of:"UIView") != nil)
                            {
                                let viewVc = subVws.subviews
//                                print("\n\nviewVcVcQueueVc  ", viewVc)
                                
                                for subVws in viewVc
                                {
                                    if (String(describing: subVws).range(of:"UIView") != nil)
                                    {
                                        
                                        let SubviewVc = subVws.subviews
//                                        print("\n\nSubviewVcSubviewVc  ", SubviewVc)
                                        
                                        for subVws in SubviewVc
                                        {
                                            if (String(describing: subVws).range(of:"UIScrollView") != nil)
                                            {
                                                let finalVw = subVws.subviews
//                                                print("\n\nfinalVw  ", finalVw)
//
                                                for subVws in finalVw
                                                {
                                                    if (String(describing: subVws).range(of:"UIView") != nil)
                                                    {
//                                                        print("subVwssubVws  ", subVws)
                                                        
                                                        let pagView = subVws.subviews
//                                                        pdfLandingView =
                                                        for subVws in pagView
                                                        {
//                                                            print("\n\n EndVwssubVws  ", subVws)
                                                            
                                                            if (String(describing: subVws).range(of:"PDFPageView") != nil)
                                                            {
                                                                let pageLandVw = subVws.subviews
                                                               
                                                                print("\n\n WasVwssubVws  ", pageLandVw)
                                                                
                                                                for subVws in pageLandVw
                                                                {
                                                                    if (String(describing: subVws).range(of:"UITextView") != nil)
                                                                    {
                                                                        print("dddddddd")
                                                                        
                                                                        let txtVw = subVws as! UITextView
                                                                        
                                                                        if todo == "firstResponder"
                                                                        {
                                                                            let rect = pdfView.currentPage?.bounds(for: .mediaBox)
                                                                            
                                                                             usingHeightText = txtVw.frame.size.height
                                                                             usingWidthText = txtVw.frame.size.width
                                                                            
                                                                            let xPoint = txtVw.frame.origin.x
                                                                            let yPoint = (rect?.height)! - (txtVw.frame.origin.y) - txtVw.frame.size.height
                                                                           
                                                                      
                                                                            lastTextAnnoPoint = CGPoint(x: xPoint, y: yPoint)
                                                                            
                                                                            findHavingTextAnnotation(annoPoint: CGPoint(x: xPoint, y: yPoint))
                                                                            
//                                                                            txtVw.contentInset = UIEdgeInsetsMake(0, 10, 0, 0)
                                                                            
                                                                            print("C_Sz      ", txtVw.contentSize)
                                                                            print("C_Off      ", txtVw.contentOffset)
                                                                            
                                                                            let widthMoveView = UIView(frame: CGRect(x: txtVw.frame.size.width - 20, y: 0, width: 20, height: txtVw.frame.size.height))
                                                                            widthMoveView.backgroundColor = UIColor.brown.withAlphaComponent(0.0)
                                                                            widthMoveView.tag = 333
                                                                            
                                                                            
                                                                            let wdImgVw = UIImageView()
                                                                            wdImgVw.frame.origin.x = 0
                                                                            wdImgVw.frame.origin.y = 8
                                                                            wdImgVw.frame.size.width = 20 // widthMoveView.frame.width
                                                                            wdImgVw.frame.size.height = 20 // widthMoveView.frame.height
                                                                            wdImgVw.contentMode = .scaleAspectFit
                                                                            wdImgVw.image = UIImage(named: "widthLeftRight")
                                                                            
                                                                            wdImgVw.layer.cornerRadius = 10
//                                                                            wdImgVw.backgroundColor = UIColor.orange
                                                                            
                                                                            widthMoveView.addSubview(wdImgVw)
                                                                            
                                                                            txtVw.addSubview(widthMoveView)
//
                                                                            
                                                                            let tapVw = UIPanGestureRecognizer(target: self, action: #selector(self.handleWidthTapVw(_:)))
                                                                            widthMoveView.addGestureRecognizer(tapVw)
                                                                            
                                                                            
                                                                        }
                                                                        else
                                                                        {
                                                                            //                                                                        txtVw.tag = AddTextCount
                                                                            txtVw.textColor = usingFontColor
                                                                            txtVw.font = UIFont(name: usingFontName, size: CGFloat(usingFontSize))
                                                                            txtVw.backgroundColor = nil
                                                                            txtVw.backgroundColor = usingBGFontColor.withAlphaComponent(usingBGFontAlpha)
                                                                            txtVw.delegate = self
                                                                            txtVw.autocorrectionType = .no
                                                                            
                                                                            let iPadShortcut = txtVw.inputAssistantItem
                                                                            
                                                                            iPadShortcut.leadingBarButtonGroups = []
                                                                            iPadShortcut.trailingBarButtonGroups = []
                                                                            
                                                                            print("\n\nTAG_TXTVW-->>>       ",txtVw.tag)
                                                                            
                                                                            let panGest = UIPanGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
                                                                            txtVw.addGestureRecognizer(panGest)
                                                                            if todo == "default"
                                                                            {
                                                                                print("\n\n defasdasfs")
                                                                                txtVw.inputView = nil
                                                                                setDoneOnKeyboard(myTextView: txtVw, showButImg: UIImage(named: "editing")!, bgImg: UIImage(named: "textbgcolor")!, kboardIcon: UIImage(named: "keyboard")!, logic: "first")
                                                                                hasKeyboardChanged = true
                                                                                txtVw.reloadInputViews()
                                                                            }
                                                                            if todo == "showPickerView"
                                                                            {
                                                                                print("\n\n showwewrewrasfs")
                                                                                txtVw.inputView = fontChangePickerView
                                                                                setDoneOnKeyboard(myTextView: txtVw, showButImg: UIImage(named: "editing")!, bgImg: UIImage(named: "textbgcolor")!, kboardIcon: UIImage(named: "keyboard")!, logic: "textchange")
                                                                                txtVw.reloadInputViews()
                                                                            }
                                                                            else if todo == "hidePickerView"
                                                                            {
                                                                                print("\n\n hideewrewrasfs")
                                                                                txtVw.inputView = nil
                                                                                setDoneOnKeyboard(myTextView: txtVw, showButImg: UIImage(named: "editing")!, bgImg: UIImage(named: "textbgcolor")!, kboardIcon: UIImage(named: "keyboard")!, logic: "first")
                                                                                txtVw.reloadInputViews()
                                                                            }
                                                                            else if todo == "widthChange"
                                                                            {
                                                                                txtVw.tag = 118
                                                                                txtVw.frame.size.width = usingWidthText
                                                                            }
                                                                            else if todo == "heightChange"
                                                                            {
                                                                                txtVw.frame.size.height = usingHeightText
                                                                                let rect = pdfView.currentPage?.bounds(for: .mediaBox)
                                                                                textVwMovedY = (rect?.height)! - (txtVw.frame.origin.y)
                                                                                MovingTextViewAnnotation(forWhich: "fingerPan")
                                                                            }
                                                                            else if todo == "sizeChangeByFont"
                                                                            {
                                                                                txtVw.frame.size.height = txtVw.contentSize.height
                                                                                usingHeightText = txtVw.frame.size.height
                                                                                
                                                                                MovingTextViewAnnotation(forWhich: "height")
                                                                                MovingTextViewAnnotation(forWhich: "fingerPan")
                                                                                
                                                                            }
                                                                            else if todo == "removeArrowSuviews"
                                                                            {
                                                                                for subVws in txtVw.subviews
                                                                                {
                                                                                    if subVws.tag == 333
                                                                                    {
                                                                                        subVws.removeFromSuperview()
                                                                                    }
                                                                                }
                                                                                
                                                                            }
                                                                            else if todo == "deleteTextVw"
                                                                            {
                                                                                txtVw.removeFromSuperview()
                                                                            }
                                                                            print("\n\ntxtVwFrame     ", txtVw.frame)
                                                                        }
                                                                        
                                                                        return
//                                                                        txtVw.inputView = fontChangePickerView
//
//                                                                        setDoneOnKeyboard(myTextView: txtVw)
//                                                                        print("\n\n TxtVwsubVws  ", subVws)
                                                                    }
                                                                
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                                
                                            }
                                        }
                                        
                                    }
                                }
                                
                                //                                break
                            }
                        }
                    }
                }
                
                // UIQueuingScrollView
            }
        }
        
        
    }
    
    //MARK: - TEXTVIEW DYNAMIC WIDTH CHANGE
    @objc func handleWidthTapVw(_ gestureRecognizer: UIPanGestureRecognizer)
    {
        let getSuperViewWidth : CGFloat = (gestureRecognizer.view?.superview?.frame.width)!
        print("brownTAp     ", getSuperViewWidth)
        if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
            
            let velo = gestureRecognizer.velocity(in: gestureRecognizer.view)
            
            if getSuperViewWidth > 80
            {
                if velo.x > 0
                {
                    print("Moving_rigtht")
                    gestureRecognizer.view?.superview?.frame.size.width = (gestureRecognizer.view?.superview?.frame.size.width)! + 2
                    gestureRecognizer.view?.frame.origin.x = (gestureRecognizer.view?.superview?.frame.size.width)! - 20
                }
                else
                {
                    print("Moving_left")
                    gestureRecognizer.view?.superview?.frame.size.width = (gestureRecognizer.view?.superview?.frame.size.width)! - 2
                    gestureRecognizer.view?.frame.origin.x = (gestureRecognizer.view?.superview?.frame.size.width)! - 20
                }
                
                if (gestureRecognizer.view?.superview as! UITextView).contentSize.height > 80
                {
                    gestureRecognizer.view?.superview?.frame.size.height = (gestureRecognizer.view?.superview as! UITextView).contentSize.height
                }
                else
                {
                    gestureRecognizer.view?.superview?.frame.size.height = 82
                }
            }
            else
            {
                gestureRecognizer.view?.superview?.frame.size.width = 82
            }
        }
        else if gestureRecognizer.state == .ended
        {
            print("\n\nHello World      ", gestureRecognizer.view)
            
            usingWidthText = (gestureRecognizer.view?.superview?.frame.size.width)!
            usingHeightText = (gestureRecognizer.view?.superview?.frame.size.height)!
            
            print("usingWidthTxt ", usingWidthText)
            
//            MovingTextViewAnnotation(forWhich: "height")
//            MovingTextViewAnnotation(forWhich: "width")
        }
        
    }
    
    
    //MARK:- PREVIOUS DRAW FORM USERDEF
    func previousDrawAddedInPage()
    {
        if totalBezierPathDict.count > 0
        {
            for (key, value) in totalBezierPathDict
            {
                let charset = CharacterSet(charactersIn: "fileNumber\(pdfClickedRow)")
                
                if key.rangeOfCharacter(from: charset) != nil
                {
                    let gettPageNum = Int(key.components(separatedBy: "PageNumber")[1])
                    
                    for path in value
                    {
                        print("Pathqwe1234234234")
                        BezierPathAddArr.append(path)
                    }
                    
                    print("keykey   ", key)
                    print("Qwerqeqeqewqqweqe   ", BezierPathAddArr)
                    
                    if BezierPathAddArr.count > 0
                    {
                        for i in BezierPathAddArr
                        {
                            var createdDict = [String : Any]()
                            createdDict = i
                            
                            let pointsArr : [CGPoint] = createdDict["BezierPathPoints"] as! [CGPoint]
                            let pathColr : UIColor = createdDict["BezierPathColor"] as! UIColor
                            
                            print("qwe1234234234")
                            let pageBounds = pdfView.currentPage?.bounds(for: .mediaBox)
                            
                            let b = PDFBorder()
                            b.lineWidth = 10.0
                            let inkAnnotation = PDFAnnotation(bounds: pageBounds!, forType: PDFAnnotationSubtype.ink, withProperties: nil)
                            
                            var retrivePdfBezierPath = UIBezierPath()
                            
                            for points in 0..<pointsarr.count
                            {
                                if (points % 2) != 0
                                {
                                    retrivePdfBezierPath.addLine(to: pointsArr[points] )
                                }
                                else
                                {
                                    retrivePdfBezierPath.move(to: pointsArr[points])
                                }
                            }
                            
                            print("added1234234234    ", retrivePdfBezierPath)
                            inkAnnotation.add(retrivePdfBezierPath)
                            
                            inkAnnotation.border = b
                            inkAnnotation.color = pathColr //colorForeground.withAlphaComponent(0.0)
                            
                            
                            pdfView.document?.page(at: gettPageNum!)?.addAnnotation(inkAnnotation)
                            
                            print("1234234234")
                        }
                        
                        BezierPathAddArr.removeAll()
                    }
                }
                
            }
        }
        
    }
    
    //MARK:- TXTVW PAN GESTURE
    @objc func handleTap(_ gestureRecognizer: UIPanGestureRecognizer) {
        
        if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {
            
            let translation = gestureRecognizer.translation(in: gestureRecognizer.view)
            
            gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
            gestureRecognizer.setTranslation(CGPoint.zero, in: gestureRecognizer.view)
        }
        else
        {
            print("\n\nHello World      ", gestureRecognizer.view)
            
            let position = CGPoint(x: (gestureRecognizer.view?.frame.origin.x)!, y: (gestureRecognizer.view?.frame.origin.y)!)
            guard let page = pdfView.page(for: position, nearest: true) else {
                return
            }
            
            let rect = pdfView.currentPage?.bounds(for: .mediaBox)
            
            let locationOnPage = pdfView.convert(position, to: page)
            
            textVwMovedX = (gestureRecognizer.view?.frame.origin.x)!
            textVwMovedY = (rect?.height)! - (gestureRecognizer.view?.frame.origin.y)!//   locationOnPage.y
            
            MovingTextViewAnnotation(forWhich: "fingerPan")
            
            print("locationOnPage World      ", locationOnPage)
        }
        
    }
    
    //MARK:- TOOL BAR
    func setDoneOnKeyboard(myTextView: UITextView, showButImg: UIImage, bgImg: UIImage, kboardIcon: UIImage, logic: String) {
        
        let keyboardToolbar = UIToolbar()
        keyboardToolbar.sizeToFit()
        let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        
        
        //textbgcolor
        let show = UIBarButtonItem(image: showButImg, style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissKeyboard))
        let background = UIBarButtonItem(image: bgImg, style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissKeyboard))
        let kboard = UIBarButtonItem(image: kboardIcon, style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissKeyboard))
        
//        let show = UIBarButtonItem(title: showButTitle, style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissKeyboard))
        
//        keyboardToolbar.backgroundColor = UIColor.red
        
        let doneBarButton = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(dismissKeyboard))
        
        if logic == "first"
        {
            keyboardToolbar.items = [show,background,flexBarButton,doneBarButton]
        }
        if logic == "textchange" || logic == "bgchange"
        {
            keyboardToolbar.items = [show,background,flexBarButton,kboard]
        }
        
        myTextView.inputAccessoryView = keyboardToolbar
    }
    
    @objc func dismissKeyboard(sender: UIBarButtonItem) {
        
        if sender.image == UIImage(named: "editing")
        {
//            print("new_button_add")
//            sender.title = "hide"
            hasKeyboardChanged = true
            whichPickerView = "fontchange"
            
            fontChangePickerView.reloadAllComponents()
            fontChangePickerView.selectRow(selectedRowFont, inComponent: 0, animated: true)
            fontChangePickerView.selectRow(selectedRowSize, inComponent: 1, animated: true)
            fontChangePickerView.selectRow(selectedRowColor, inComponent: 2, animated: true)
            
            
            switch (deviceIdiom) {
                
            case .pad:
                print("iPad style UI")
                showPickerPop(sender: sender)
            case .phone:
                print("iPhone and iPod touch style UI")
                getPDFFrame(todo: "showPickerView")
            
            default:
                print("Unspecified UI idiom")
            }
        }
        else if sender.image == UIImage(named: "textbgcolor")
        {
            whichPickerView = "bgchange"
            hasKeyboardChanged = true
            fontChangePickerView.reloadAllComponents()
            fontChangePickerView.selectRow(selectedBGRowColor, inComponent: 0, animated: true)
            fontChangePickerView.selectRow(selectedBGAlpha, inComponent: 1, animated: true)
            
            switch (deviceIdiom) {
                
            case .pad:
                print("iPad style UI")
                showPickerPop(sender: sender)
            case .phone:
                print("iPhone and iPod touch style UI")
                getPDFFrame(todo: "showPickerView")
                
            default:
                print("Unspecified UI idiom")
            }
        }
        else if sender.image == UIImage(named: "keyboard")
        {
//            print("hidePressed_button_add")
//            sender.title = "show"
            hasKeyboardChanged = true
            getPDFFrame(todo: "hidePickerView")
            
            
            
            colorForeground = usingFontColor
            MovingTextViewAnnotation(forWhich: "color")
            MovingTextViewAnnotation(forWhich: "font")
            MovingTextViewAnnotation(forWhich: "BGColor")
        }
        else
        {
            print("selPer     ", self.presentingViewController?.popoverPresentationController)
            
            isDoneButtonPressed = true
            
            getPDFFrame(todo: "removeArrowSuviews")
            
            switch (deviceIdiom) {
                
            case .pad:
                
                colorForeground = usingFontColor
                MovingTextViewAnnotation(forWhich: "color")
                MovingTextViewAnnotation(forWhich: "font")
                MovingTextViewAnnotation(forWhich: "BGColor")
                
            case .phone:
                print("iPhonekb and iPod touch style UI")
                
                MovingTextViewAnnotation(forWhich: "height")
                MovingTextViewAnnotation(forWhich: "width")
                MovingTextViewAnnotation(forWhich: "fingerPan")
                
                colorForeground = usingFontColor
                MovingTextViewAnnotation(forWhich: "color")
                MovingTextViewAnnotation(forWhich: "font")
                MovingTextViewAnnotation(forWhich: "BGColor")
                
            default:
                print("Unspecified UI idiom")
            }
            
            hasKeyboardChanged = false
//            print("new_button_add")
            view.endEditing(true)
        }
        
    }
    
    func hidePopOver(sender: UIBarButtonItem)
    {
        let popoverContent = self.storyboard?.instantiateViewController(withIdentifier: "poppicker") as! PickerPopViewController
        
        popoverContent.modalPresentationStyle = .popover
        popoverContent.preferredContentSize = CGSize(width:300,height:200)
        popoverContent.popoverPresentationController!.delegate = self
        popoverContent.popoverPresentationController!.barButtonItem = sender
        
        popoverContent.dismiss(animated: false, completion: nil)
    }
    
    func showPickerPop(sender: UIBarButtonItem) {
        
        if let presented = self.popoverPresentationController {
            print("pres")
        }
        else{
            
            print("no_pres")
        }
        
        let popoverContent = self.storyboard?.instantiateViewController(withIdentifier: "poppicker") as! PickerPopViewController
        
        popoverContent.modalPresentationStyle = .popover
        popoverContent.preferredContentSize = CGSize(width:300,height:200)
        popoverContent.popoverPresentationController!.delegate = self
        popoverContent.popoverPresentationController!.barButtonItem = sender
        
        popoverContent.popoverPresentationController?.backgroundColor = UIColor.orange
        popoverContent.chooseColrDel = self
        
        popoverContent.selectedBGRowColor = selectedBGRowColor
        popoverContent.selectedBGAlpha = selectedBGAlpha
        popoverContent.usingBGFontColor = usingBGFontColor
        popoverContent.usingBGFontAlpha = usingBGFontAlpha
        
        popoverContent.usingFontName = usingFontName
        popoverContent.usingFontSize = usingFontSize
        popoverContent.usingFontColor = usingFontColor
        
        popoverContent.selectedRowFont = selectedRowFont
        popoverContent.selectedRowSize = selectedRowSize
        popoverContent.selectedRowColor = selectedRowColor
        
        popoverContent.whichPickerView = whichPickerView
        

        
        self.present(popoverContent, animated: true, completion: nil)

        
        
        print("shPiPop")
    }
    
    func chooseColor(f_name: String, f_size: Int, f_color: UIColor, bg_color: UIColor, bg_alpha: CGFloat, f_name_sel: Int, f_size_sel: Int, f_color_sel: Int, bg_color_sel: Int, bg_alpha_sel: Int) {
        
        usingFontName = f_name
        usingFontSize = f_size
        usingFontColor = f_color
        usingBGFontAlpha = bg_alpha
        usingBGFontColor = bg_color
        
        selectedRowColor = f_color_sel
        selectedRowSize = f_size_sel
        selectedRowFont = f_name_sel
        selectedBGAlpha = bg_alpha_sel
        selectedBGRowColor = bg_color_sel
        
        getPDFFrame(todo: "default")
    }
    
    //MARK:- TEXTVIEW DELEGATE
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        
        print("dsfdsf")
        

        
        return true
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        

    }
    
    func textViewDidChange(_ textView: UITextView) {
        
        print("changin     ")
        
        print("C_Sz_Del      ", textView.contentSize)
        print("C_Off_Del      ", textView.contentOffset)
        
        if textView.contentSize.height >= usingHeightText
        {
            isTypeTextVwChanged = false
            for subVws in textView.subviews
            {
                textView.frame.size.height = textView.contentSize.height
                
                if subVws.tag == 444
                {
                    subVws.frame.origin.y = textView.contentSize.height - 20
//                    heightYOrgin = subVws.frame.origin.y
                    
                }
                if subVws.tag == 333
                {
//                    subVws.frame.origin.y = textView.contentOffset.y //- 30
                }
            }
        }
        else
        {
            print("Logic_less_than_height         ", usingHeightText)
        }
        
    }
    
    //MARK:- PICKERVIEW DELEGATE
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        
        if whichPickerView == "fontchange"
        {
            return 3
        }
        else if whichPickerView == "bgchange"
        {
            return 2
        }
        else
        {
            return 0
        }
        
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        if whichPickerView == "fontchange"
        {
            if component == 0
            {
                return fontFamilyName.count
            }
            else if component == 1
            {
                return fontSizeList.count
            }
            else
            {
                return fontColorList.count
            }
        }
        else if whichPickerView == "bgchange"
        {
            if component == 0
            {
                return fontColorList.count
            }
            else
            {
                return bgOpacityList.count
            }
            
        }
        else
        {
            return 0
        }
        

    }
    

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        if whichPickerView == "fontchange"
        {
            if component == 0
            {
                selectedRowFont = row
                usingFontName = fontFamilyName[row]!
                fontNameLbl.text = " - " + String(usingFontSize) + " - " + usingFontName
            }
            if component == 1
            {
                selectedRowSize = row
                usingFontSize = Int(fontSizeList[row]!)
                fontNameLbl.text = " - " + String(usingFontSize) + " - " + usingFontName
            }
            if component == 2
            {
                selectedRowColor = row
                usingFontColor = fontColorList[row]!
                fontClrVw.backgroundColor = usingFontColor
            }
            
            fontNameLbl.font = UIFont(name: usingFontName, size: 14)
        }
        else if whichPickerView == "bgchange"
        {
            if component == 0
            {
                selectedBGRowColor = row
                usingBGFontColor = fontColorList[row]!
                fontChangePickerView.reloadComponent(1)
            }
            if component == 1
            {
                selectedBGAlpha = row
                usingBGFontAlpha = bgOpacityList[row]!
                print("two_options")
            }
        }
        else
        {
        }
        
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        
        fontChangePickerView.backgroundColor = UIColor(red: 40/255, green: 40/255, blue: 40/255, alpha: 1.0)
        
        if whichPickerView == "fontchange"
        {
            var label = UILabel()
            if let v = view {
                label = v as! UILabel
            }
            
            if component == 0
            {
                
                label.font = UIFont (name: fontFamilyName[row]!, size: 15)
                label.text = fontFamilyName[row]
                label.textAlignment = .center
                label.textColor = .white
                return label
            }
            else if component == 1
            {
                label.font = UIFont (name: "Helvetica Neue", size: 12)
                let fontSize : Int = Int(fontSizeList[row]!)
                label.text = String(fontSize)
                label.textAlignment = .right
                label.textColor = .white
                return label
            }
            else
            {
                var colorView = UIView()
                if let v = view
                {
                    colorView = v
                }
                
                print("colorViewcolorView    ", view)
                
                let colorSubView = UIView(frame: CGRect(x: 40, y: (colorView.frame.midY + 3), width: 20, height: 20))
                colorSubView.layer.cornerRadius = 10
                colorSubView.backgroundColor = fontColorList[row]
                colorSubView.layer.borderWidth = 1.0
                colorSubView.layer.borderColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 0.3).cgColor
                colorView.addSubview(colorSubView)
                return colorView
            }
        }
        else if whichPickerView == "bgchange"
        {
            var label = UILabel()
            if let v = view {
                label = v as! UILabel
            }
            
            var colorView = UIView()
            if let v = view
            {
                colorView = v
            }
            
            if component == 0
            {
                let colorSubView = UIView(frame: CGRect(x: (((self.view.frame.width) / 4) - 15), y: (colorView.frame.midY + 3), width: 30, height: 20))
                colorSubView.layer.cornerRadius = 5
                colorSubView.backgroundColor = fontColorList[row]
                colorSubView.layer.borderWidth = 1.0
                colorSubView.layer.borderColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 0.3).cgColor
                colorView.addSubview(colorSubView)
                return colorView
            }
            else
            {
                let colorSubView = UIView(frame: CGRect(x: (((self.view.frame.width) / 4) - 15), y: (colorView.frame.midY + 3), width: 30, height: 20))
                colorSubView.layer.cornerRadius = 5
                colorSubView.backgroundColor = usingBGFontColor.withAlphaComponent(bgOpacityList[row]!)
                colorSubView.layer.borderWidth = 1.0
                colorSubView.layer.borderColor = UIColor(red: 250/255, green: 250/255, blue: 250/255, alpha: 0.3).cgColor
                colorView.addSubview(colorSubView)
                return colorView
            
            }
        }
        else
        {
            let vw = UIView()
            return vw
        }
        
    }
    
    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        
        if whichPickerView == "fontchange"
        {
            let componentTwoWidth : CGFloat = 50.0 //self.view.frame.width
            let componentThreeWidth : CGFloat = componentTwoWidth + 50
            let componentOneWidth : CGFloat = self.view.frame.width - componentThreeWidth - componentTwoWidth
            
            if component == 0
            {
                return componentOneWidth
            }
            else if component == 1
            {
                return componentTwoWidth
            }
            else
            {
                return componentThreeWidth
            }
        }
        else if whichPickerView == "bgchange"
        {
            if component == 0
            {
                return (self.view.frame.width) / 2
            }
            else
            {
                return (self.view.frame.width) / 2
            }
            
        }
        else
        {
            return 0
        }
        
        
    }
    
    @IBAction func fontSetToolBarBtnAcn(_ sender: UIButton) {
        
        
        colorForeground = usingFontColor
        
//        getPDFFrame()
        MovingTextViewAnnotation(forWhich: "color")
        MovingTextViewAnnotation(forWhich: "font")
//        FontToolBarVw.isHidden = true
        
//        addWindow?.isHidden = true
        
//        addWindow.resignKey()
        
        
        for vw in (addWindow?.subviews)!
        {
            
            print("\n\nvwwww    ",vw)
            
            if vw.tag == 900
            {
                vw.backgroundColor = UIColor.yellow
                vw.alpha = 0.0

                
                vw.removeFromSuperview()
                
                
//                vw.alpha = 0.0
//                vw = UIView()
            }
            else
            {
//                addWindow?.insertSubview(vw, belowSubview: newVw)
            }
        }

    }
    
    
    
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        
        print("actionaction   ", action)
        
        print("whichTaskPerf    ", whichTask)
        
        if whichTask == "text"
        {
            
            if action == #selector(BookViewController.highlightTextColor) {
                return true
            }
            else
            {
                print("wrkin_cpy_not_come")
                return false
            }
        }
        else if whichTask == "goingToEdit"
        {
            
            if action == #selector(BookViewController.highlightTextColor) {
                return true
            }
            else
            {
                
                return false
            }
        }
        
        if whichTask == "highLightText"
        {
            
            if action == #selector(BookViewController.spacingRed) {
                return true
            }
            if action == #selector(BookViewController.spacingCyan) {
                return true
            }
            if action == #selector(BookViewController.spacingYellow) {
                return true
            }
            if action == #selector(BookViewController.spacingOrange) {
                return true
            }
            if action == #selector(BookViewController.spacingPurple) {
                return true
            }
            else
            {
                return false
            }
        }
        return false
    }
    
    //MARK:- CONVERT PDF TO IMAGE TO PAGE AND PDF
    func drawPDFfromURL(url: NSURL) {
        
        var pdfDoc: CGPDFDocument!
        pdfDoc = CGPDFDocument(url)
        let numberOfPages = pdfDoc.numberOfPages
        
        print("numberOfPagesnumberOfPages  ", numberOfPages)
        
        for ii in 1...numberOfPages
        {
            let document = CGPDFDocument(url)
            let page = document?.page(at: ii)
            
            let pageRect = page!.getBoxRect(CGPDFBox.mediaBox)
            
            UIGraphicsBeginImageContextWithOptions(pageRect.size, true, 0)
            let context = UIGraphicsGetCurrentContext()
            
            context!.setFillColor(UIColor.white.cgColor)
            context!.fill(pageRect)
            
            context!.translateBy(x: 0.0, y: pageRect.size.height)
            context!.scaleBy(x: 1.0, y: -1.0)
            context!.drawPDFPage(page!)
            
            let img = UIGraphicsGetImageFromCurrentImageContext()
            
            pdfPagesImgArr.append(img!)
            
            UIGraphicsEndImageContext()
        }
    }
    
    func ConvertImagesToPages()
    {
        var pageNum : Int = 0
        
        for img in pdfPagesImgArr
        {
            let currPage = PDFPage(image: img)
            
            pdfDocument?.insert(currPage!, at: pageNum)
            pageNum = pageNum + 1
        }
    }
    
}

extension CGPath {
    
    func forEach( body: @escaping @convention(block) (CGPathElement) -> Void) {
        typealias Body = @convention(block) (CGPathElement) -> Void
        let callback: @convention(c) (UnsafeMutableRawPointer, UnsafePointer) -> Void = { (info, element) in
            let body = unsafeBitCast(info, to: Body.self)
            body(element.pointee)
        }
        print(MemoryLayout.size(ofValue: body))
        let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self)
        self.apply(info: unsafeBody, function: unsafeBitCast(callback, to: CGPathApplierFunction.self))
    }
    func getPathElementsPoints() -> [CGPoint] {
        var arrayPoints : [CGPoint]! = [CGPoint]()
        self.forEach { element in
            switch (element.type) {
            case .moveToPoint:
                arrayPoints.append(element.points[0])
            case .addLineToPoint:
                arrayPoints.append(element.points[0])
            default: break
            }
        }
        return arrayPoints
    }
    func getPathElementsPointsAndTypes() -> ([CGPoint],[CGPathElementType]) {
        var arrayPoints : [CGPoint]! = [CGPoint]()
        var arrayTypes : [CGPathElementType]! = [CGPathElementType]()
        self.forEach { element in
            switch (element.type) {
            case .addLineToPoint:
                arrayPoints.append(element.points[0])
                arrayTypes.append(element.type)
            default: break
            }
        }
        return (arrayPoints,arrayTypes)
    }
}

class PDFViewGestureRecognizer: UIGestureRecognizer {
    var isTracking = false

    override func touchesBegan(_ touches: Set, with event: UIEvent) {
        isTracking = true
        
        
    }
    override func touchesEnded(_ touches: Set, with event: UIEvent) {
        isTracking = false
        
        
    }

    override func touchesCancelled(_ touches: Set, with event: UIEvent) {
        isTracking = false
    }
}

extension URL {
    var typeIdentifier: String? {
        return (try? resourceValues(forKeys: [.typeIdentifierKey]))?.typeIdentifier
    }
    var localizedName: String? {
        return (try? resourceValues(forKeys: [.localizedNameKey]))?.localizedName
    }
}

extension UIColor {
    var name: String? {
        switch self {
        case UIColor.black: return "black"
        case UIColor.darkGray: return "darkGray"
        case UIColor.lightGray: return "lightGray"
        case UIColor.white: return "white"
        case UIColor.gray: return "gray"
        case UIColor.red: return "red"
        case UIColor.green: return "green"
        case UIColor.blue: return "blue"
        case UIColor.cyan: return "cyan"
        case UIColor.yellow: return "yellow"
        case UIColor.magenta: return "magenta"
        case UIColor.orange: return "orange"
        case UIColor.purple: return "purple"
        case UIColor.brown: return "brown"
        default: return nil
        }
    }
}

extension BookViewController: UIDocumentInteractionControllerDelegate {
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    func documentInteractionController(_ controller: UIDocumentInteractionController, willBeginSendingToApplication application: String?) {
        print("will begin")
    }
    
    func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
        print("did end")
    }
}