Created
April 25, 2015 09:24
-
-
Save tempire/0bd8cb78290aa9bc6adf to your computer and use it in GitHub Desktop.
swift draw image on pdf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
This works only on first page of the pdf file. Using this code actually removes the actual content on pdf and replaces it with the new image if there more than one pages in the pdf.
thank you, it work to me .
What is the path?
@MerrickWang1, path is location to pdf file stored on local
Thanks :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you very much, you are a lifesaver!
I did convert it correctly to Swift 4.2