将PDF转换为UIImage [英] Convert PDF to UIImage
本文介绍了将PDF转换为UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
func drawOnPDF(path: String)
{
// Get existing Pdf reference
let pdf = CGPDFDocumentCreateWithURL(NSURL(fileURLWithPath: path))
// Get page count of pdf, so we can loop through pages and draw them accordingly
let pageCount = CGPDFDocumentGetNumberOfPages(pdf);
// Write to file
UIGraphicsBeginPDFContextToFile(path, CGRectZero, nil)
// Write to data
// var data = NSMutableData()
// UIGraphicsBeginPDFContextToData(data, CGRectZero, nil)
for index in 1...pageCount {
let page = CGPDFDocumentGetPage(pdf, index)
let pageFrame = CGPDFPageGetBoxRect(page, kCGPDFMediaBox)
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil)
var ctx = UIGraphicsGetCurrentContext()
// Draw existing page
CGContextSaveGState(ctx);
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
CGContextDrawPDFPage(ctx, page);
CGContextRestoreGState(ctx);
// Draw image on top of page
var image = UIImage(named: "signature3")
image?.drawInRect(CGRectMake(100, 100, 100, 100))
// Draw red box on top of page
//UIColor.redColor().set()
//UIRectFill(CGRectMake(20, 20, 100, 100));
}
UIGraphicsEndPDFContext()
}
我的问题是PDF转换为图像,但如何在View中打开图像然后向左,向右,向上和向下滑动如何可能
My problem is PDF convert to image but how to open image in View then swipe left,right,up and down how to possible
推荐答案
Swift 3:
func convertPDFPageToImage(page:Int) {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let filePath = documentsURL.appendingPathComponent("pathLocation").path
do {
let pdfdata = try NSData(contentsOfFile: filePath, options: NSData.ReadingOptions.init(rawValue: 0))
let pdfData = pdfdata as CFData
let provider:CGDataProvider = CGDataProvider(data: pdfData)!
let pdfDoc:CGPDFDocument = CGPDFDocument(provider)!
pageCount = pdfDoc.numberOfPages;
let pdfPage:CGPDFPage = pdfDoc.page(at: page)!
var pageRect:CGRect = pdfPage.getBoxRect(.mediaBox)
pageRect.size = CGSize(width:pageRect.size.width, height:pageRect.size.height)
print("\(pageRect.width) by \(pageRect.height)")
UIGraphicsBeginImageContext(pageRect.size)
let context:CGContext = UIGraphicsGetCurrentContext()!
context.saveGState()
context.translateBy(x: 0.0, y: pageRect.size.height)
context.scaleBy(x: 1.0, y: -1.0)
context.concatenate(pdfPage.getDrawingTransform(.mediaBox, rect: pageRect, rotate: 0, preserveAspectRatio: true))
context.drawPDFPage(pdfPage)
context.restoreGState()
let pdfImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.imageView.image = pdfImage
}
catch {
}
}
这篇关于将PDF转换为UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文