您可以在一个层上调用renderInContext。对UIPrintPageRenderer来说有这样的东西吗?我基本上想要从PDF文档的第一页中创建一个UIImage。除了上下文部分的实际呈现之外,我还有其余的代码。
编辑:我是不是误解了一些基本的基本概念?如果是的话,请随时给我上一课。
发布于 2015-09-21 21:50:56
从这个职位中的Vel Genov获取我的大部分信息,下面是您应该做的事情:
下面的示例代码向UIPrintPageRenderer添加了一个类别,以创建实际的PDF数据。
@interface UIPrintPageRenderer (PDF)
- (NSData*) createPDF;
@end
@implementation UIPrintPageRenderer (PDF)
- (NSData*) createPDF
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData( pdfData, self.paperRect, nil );
[self prepareForDrawingPages: NSMakeRange(0, self.numberOfPages)];
CGRect bounds = UIGraphicsGetPDFContextBounds();
for ( int i = 0 ; i < self.numberOfPages ; i++ )
{
UIGraphicsBeginPDFPage();
[self drawPageAtIndex: i inRect: bounds];
}
UIGraphicsEndPDFContext();
return pdfData;
}
@end然后,这就进入了webViewDidFinishLoad()
- (void)webViewDidFinishLoad:(UIWebView *)webViewIn {
NSLog(@"web view did finish loading");
// webViewDidFinishLoad() could get called multiple times before
// the page is 100% loaded. That's why we check if the page is still loading
if (webViewIn.isLoading)
return;
UIPrintPageRenderer *render = [[UIPrintPageRenderer alloc] init];
[render addPrintFormatter:webViewIn.viewPrintFormatter startingAtPageAtIndex:0];
// Padding is desirable, but optional
float padding = 10.0f;
// Define the printableRect and paperRect
// If the printableRect defines the printable area of the page
CGRect paperRect = CGRectMake(0, 0, PDFSize.width, PDFSize.height);
CGRect printableRect = CGRectMake(padding, padding, PDFSize.width-(padding * 2), PDFSize.height-(padding * 2));
[render setValue:[NSValue valueWithCGRect:paperRect] forKey:@"paperRect"];
[render setValue:[NSValue valueWithCGRect:printableRect] forKey:@"printableRect"];
// Call the printToPDF helper method that will do the actual PDF creation using values set above
NSData *pdfData = [render createPDF];
// Save the PDF to a file, if creating one is successful
if (pdfData) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *pdfPath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"Purchase Order.pdf"]];
[pdfData writeToFile:pdfPath atomically:YES];
}
else
{
NSLog(@"error creating PDF");
}
}PDFSize被定义为常量,设置为标准的A4页面大小。它可以编辑,以满足您的需要。
#define PDFSize CGSizeMake(595.2,841.8)下面是Val对代码的看法:
当调用webViewDidFinishLoad()时,视图可能不会100%加载。检查是必要的,以查看视图是否仍在加载。这一点很重要,因为它可能是问题的根源。如果不是,那我们就可以走了。这里有一个非常重要的注意事项。一些网页是动态加载的(在页面本身中定义)。以youtube.com为例。页面几乎立即显示,带有“加载”屏幕。这将欺骗我们的web视图,它的"isLoading“属性将被设置为"false",而网页仍在动态加载内容。这是一个非常罕见的情况,在一般情况下,这个解决方案将很好地工作。如果需要从这样的动态加载网页生成PDF文件,则可能需要将实际生成的文件移到不同的位置。即使是动态加载网页,您也会得到一个显示加载屏幕的PDF,而不是一个空PDF文件。 另一个关键方面是设置printableRect和pageRect。请注意,它们是单独设置的。如果printableRect小于paperRect,那么最终会在内容周围填充一些内容--例如,参见代码。这里有一个链接到苹果的API文档,并对两者做了一些简短的描述。
https://stackoverflow.com/questions/32642580
复制相似问题