|
8 | 8 | #import "SDImagePDFCoder.h" |
9 | 9 | #import "SDWebImagePDFCoderDefine.h" |
10 | 10 | #import "objc/runtime.h" |
| 11 | +#import <PDFKit/PDFKit.h> |
11 | 12 |
|
12 | 13 | #define SD_FOUR_CC(c1,c2,c3,c4) ((uint32_t)(((c4) << 24) | ((c3) << 16) | ((c2) << 8) | (c1))) |
13 | 14 |
|
@@ -151,25 +152,48 @@ - (UIImage *)createVectorPDFWithData:(nonnull NSData *)data pageNumber:(NSUInteg |
151 | 152 | image = [[NSImage alloc] initWithSize:imageRep.size]; |
152 | 153 | [image addRepresentation:imageRep]; |
153 | 154 | #else |
154 | | - CGDataProviderRef provider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); |
155 | | - if (!provider) { |
| 155 | + |
| 156 | + PDFDocument *document = [[PDFDocument alloc]initWithData:data]; |
| 157 | + if (!document) { |
156 | 158 | return nil; |
157 | 159 | } |
158 | | - CGPDFDocumentRef document = CGPDFDocumentCreateWithProvider(provider); |
159 | | - CGDataProviderRelease(provider); |
160 | | - if (!document) { |
| 160 | + if (pageNumber >= document.pageCount) { |
161 | 161 | return nil; |
162 | 162 | } |
163 | | - |
164 | | - // `CGPDFDocumentGetPage` page number is 1-indexed. |
165 | | - CGPDFPageRef page = CGPDFDocumentGetPage(document, pageNumber + 1); |
| 163 | + PDFPage *page = [document pageAtIndex:pageNumber]; |
166 | 164 | if (!page) { |
167 | | - CGPDFDocumentRelease(document); |
168 | 165 | return nil; |
169 | 166 | } |
170 | 167 |
|
171 | | - image = ((UIImage *(*)(id,SEL,CGPDFPageRef))[UIImage.class methodForSelector:SDImageWithCGPDFPageSEL])(UIImage.class, SDImageWithCGPDFPageSEL, page); |
172 | | - CGPDFDocumentRelease(document); |
| 168 | + CGPDFDocumentRef documentRef = document.documentRef; |
| 169 | + if (!documentRef) { |
| 170 | + return nil; |
| 171 | + } |
| 172 | + |
| 173 | + CGPDFPageRef pageRef = page.pageRef; |
| 174 | + if (!pageRef) { |
| 175 | + return nil; |
| 176 | + } |
| 177 | + |
| 178 | + CGPDFBox box = kCGPDFMediaBox; |
| 179 | + CGRect rect = CGPDFPageGetBoxRect(pageRef, box); |
| 180 | + CGAffineTransform transform = CGPDFPageGetDrawingTransform(pageRef, box, rect, 0, YES); |
| 181 | + |
| 182 | + SDGraphicsBeginImageContextWithOptions(targetRect.size, NO, 0); |
| 183 | + CGContextRef context = SDGraphicsGetCurrentContext(); |
| 184 | + |
| 185 | +#if SD_UIKIT || SD_WATCH |
| 186 | + // Core Graphics coordinate system use the bottom-left, UIKit use the flipped one |
| 187 | + CGContextTranslateCTM(context, 0, rect.size.height); |
| 188 | + CGContextScaleCTM(context, 1, -1); |
| 189 | +#endif |
| 190 | + |
| 191 | + CGContextConcatCTM(context, transform); |
| 192 | + [page drawWithBox:kPDFDisplayBoxMediaBox toContext:context]; |
| 193 | + |
| 194 | + image = SDGraphicsGetImageFromCurrentImageContext(); |
| 195 | + SDGraphicsEndImageContext(); |
| 196 | + |
173 | 197 | #endif |
174 | 198 |
|
175 | 199 | return image; |
|
0 commit comments