开发者

Load PDF into UIImage or UIImageView?

开发者 https://www.devze.com 2022-12-21 19:45 出处:网络
I\'m trying 开发者_运维百科to load a PDF file stored in Resources into a UIImage/UIImageView object in the iPhone SDK. Is this at all possible without converting the PDF to an image? If not, what are

I'm trying 开发者_运维百科to load a PDF file stored in Resources into a UIImage/UIImageView object in the iPhone SDK. Is this at all possible without converting the PDF to an image? If not, what are the member functions for converting a PDF into a PNG? I would really prefer to preserve the PDF if at all pssoible.


Now it is possible, I am using iOS 8+. If you put a pdf in your assets catalog, and then load the pdf in a UIImage using [UIImage imageNamed:] it renders the first page of the pdf into the UIImage.


PDFs can be loaded by UIWebView. If you need more control you can use Quartz 2D to render PDFs: Quartz2D


You may want to check out this UIImage-PDF category over on GitHub: https://github.com/mindbrix/UIImage-PDF


a solution based on 'https://www.hackingwithswift.com/example-code/core-graphics/how-to-render-a-pdf-to-an-image'

//MARK: - für Bild vom PDF erstellen
extension SettingsQuellen{
func drawIMGfromPDF(thisPDF: String) -> UIImage? {

    ///holt das PDF aus einem Verzeichnis im Programm
    ///nicht aus der 'Assets.xcassets'

    let path = Bundle.main.path(
        forResource: thisPDF,  //"fsm75-3 (Startstrecke)"
        ofType     : "pdf")  /////path to local file

    let url = URL(fileURLWithPath: path!)

    //following based on: https://www.hackingwithswift.com/example-code/core-graphics/how-to-render-a-pdf-to-an-image

    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
}//end func drawIMGfromPDF
}//end extension SettingsQuellen - für Bild vom PDF erstellen

Usage:

let img = drawIMGfromPDF(thisPDF: "fsm75-3 (Startstrecke)") //Bild vom PDF erstellen
cell.outletImageView.image = img


for Swift,

just Import or Add your PDF to Assets and use it like below.

your_image_view.image = UIImage(named:"name_of_your_file")

that is it and this should work charmly


for Swift, just Import or Add your PDF to Assets and use it like below.

your_image_view.image = UIImage(named:"name_of_your_file")
0

精彩评论

暂无评论...
验证码 换一张
取 消