How to present a single page pdf document in PDFView so that the document is centred and fully presented?

2.2k Views Asked by At

I have an application that takes a photo of a document and then presented as a pdf in PDFView in a new UIViewController. The problem that I am having is that when the pdf document is presented, it is some what zoomed in and the PDFView does not show the full outline of the document by default. How do I accomplish this?

class ShowPDFViewController: UIViewController{

@IBOutlet weak var pdfPreview: PDFView!
var pdfDocument: PDFDocument!


    override func viewDidLoad() {
        super.viewDidLoad()

        // PRESENT PDF DOCUMENT JUST CREATED
        pdfPreview.document = pdfDocument
        pdfPreview.autoScales = true

    }
}

This is how the pdf document is currently presented default - often zoomed:

enter image description here

This is how I would like the document presented by default - full outline of document see:

enter image description here

3

There are 3 best solutions below

1
On BEST ANSWER

I create the view from code the following way and it works (left and right side are aligned to superview left and right and height is scaled to fit)

var pdfView = PDFView(frame: view.frame)
pdfView.document = PDFDocument(url: Bundle.main.url(forResource: "doc"
    , withExtension: "pdf")!)

pdfView.displayMode = .singlePage
pdfView.autoScales = true

view.addSubview(pdfView)
0
On

I have a idea. you can create a ScrollView , add PDFView to it. put them to Controller. you can change ScrollView.contentOffset for your need

0
On

Fix for pdfView.displayMode = .singlePageContinuous

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        DispatchQueue.main.async {
            self.pdfView.subviews.forEach {
                guard let scrollView = ($0 as? UIScrollView) else { return }
                scrollView.setContentOffset(.zero, animated: false)
            }
        }

    }