Answers for "pdf to image in ios swift"

0

pdf to image in ios swift

// Create a URL for the PDF file.
guard let path = Bundle.main.path(forResource: "filename", ofType: "pdf") else { return }
let url = URL(fileURLWithPath: path)

// Instantiate a `CGPDFDocument` from the PDF file's URL.
guard let document = PDFDocument(url: url) else { return }

// Get the first page of the PDF document.
guard let page = document.page(at: 0) else { return }

// Fetch the page rect for the page we want to render.
let pageRect = page.bounds(for: .mediaBox)

let renderer = UIGraphicsImageRenderer(size: pageRect.size)
let img = renderer.image { ctx in
    // Set and fill the background color.
    UIColor.white.set()
    ctx.fill(CGRect(x: 0, y: 0, width: pageRect.width, height: pageRect.height))

    // Translate the context so that we only draw the `cropRect`.
    ctx.cgContext.translateBy(x: -pageRect.origin.x, y: pageRect.size.height - pageRect.origin.y)

    // Flip the context vertically because the Core Graphics coordinate system starts from the bottom.
    ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

    // Draw the PDF page.
    page.draw(with: .mediaBox, to: ctx.cgContext)
}
Posted by: Guest on September-17-2021
0

pdf to image in ios swift

func drawPDFfromURL(url: URL) -> UIImage? {
    guard let document = CGPDFDocument(url as CFURL) else { return nil }
    guard let page = document.page(at: 1) else { return nil }

    let pageRect = page.getBoxRect(.mediaBox)
    let renderer = UIGraphicsImageRenderer(size: pageRect.size)
    let img = renderer.image { ctx in
        UIColor.white.set()
        ctx.fill(pageRect)

        ctx.cgContext.translateBy(x: 0.0, y: pageRect.size.height)
        ctx.cgContext.scaleBy(x: 1.0, y: -1.0)

        ctx.cgContext.drawPDFPage(page)
    }

    return img
}
Posted by: Guest on September-17-2021

Code answers related to "pdf to image in ios swift"

Code answers related to "Swift"

Browse Popular Code Answers by Language