如何从UIView创建PDF格式的转换图像?

时间:2018-04-24 09:51:52

标签: ios pdf uiview uiimageview cgpdfcontext

我正在使用以下代码从已有子视图的PDF创建UIView。我正在获取所有子视图并在pdf上下文中重绘。但我无法改变UIImageView。以下是我的代码

NSMutableData *pdfData = [NSMutableData data];
CGRect pageFrame = CGRectMake(0, 0, aView.frame.size.width, aView.frame.size.height);
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);
if([view isKindOfClass:[UIImageView class]]) {
    UIImageView *imgv = (UIImageView *)view;
    [imgv.image  drawInRect:CGRectMake(view.frame.origin.x + imgv.frame.origin.x, view.frame.origin.y + imgv.frame.origin.y, imgv.frame.size.width, imgv.frame.size.height)];
}
UIGraphicsEndPDFContext();

即使图像在UIView中旋转,但pdf显示没有旋转。如何在pdf上下文中将其转换为90度?

2 个答案:

答案 0 :(得分:0)

请注意,以下方法仅创建视图的位图;它不会创建实际的排版。

-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    // Creates a mutable data object for updating with binary data, like a byte array
    NSMutableData *pdfData = [NSMutableData data];

    // Points the pdf converter to the mutable data object and to the UIView to be converted
    UIGraphicsBeginPDFContextToData(pdfData, aView.bounds, nil);
    UIGraphicsBeginPDFPage();
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    // draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData

    [aView.layer renderInContext:pdfContext];

    // remove PDF rendering context
    UIGraphicsEndPDFContext();

    // Retrieves the document directories from the iOS device
    NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

    NSString* documentDirectory = [documentDirectories objectAtIndex:0];
    NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

    // instructs the mutable data object to write its context to a file on disk
    [pdfData writeToFile:documentDirectoryFilename atomically:YES];
    NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

还要确保导入:QuartzCore / QuartzCore。

答案 1 :(得分:0)

如果您只需要使用旋转绘制一些元素,请尝试将矩阵变换函数用于当前上下文(它将是PDF上下文)。

CGContextRotateCTM(currentContext, M_PI / 2);