How to get actual pdf page size in iPad?

前端 未结 5 2023
时光取名叫无心
时光取名叫无心 2020-12-10 08:16

How can I get PDF page width and height in iPad? Any document or suggestions on how I can find this information?

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 08:59

    Swift 3.x (based on answer provided by Ege Akpinar)

    let pageRect = pdfPage.getBoxRect(CGPDFBox.mediaBox) // where pdfPage is a CGPDFPage
    let pageSize = pageRect.size
    

    A more full example showing how to extract the dimensions of page in a PDF file:

    /**
     Returns the dimensions of a PDF page.
     - Parameter pdfURL: The URL of the PDF file.
     - Parameter pageNumber: The number of the page to obtain dimensions (Note: page numbers start from `1`, not `0`)
     */
    func pageDimension(pdfURL: URL, pageNumber: Int) -> CGSize? {
    
        // convert URL to NSURL which is toll-free-briged with CFURL
        let url = pdfURL as NSURL
        guard let pdf = CGPDFDocument(url) else { return nil }
        guard let pdfPage = pdf.page(at: pageNumber) else { return nil }
    
        let pageRect = pdfPage.getBoxRect(CGPDFBox.mediaBox)
        let pageSize = pageRect.size
    
        return pageSize
    }
    
    let url = Bundle.main.url(forResource: "file", withExtension: "pdf")!
    let dimensions = pageDimension(pdfURL: url, pageNumber: 1)
    print(dimensions ?? "Cannot get dimensions")
    

提交回复
热议问题