0

I have a View with some subviews on it like Labels and ImageViews. The subviews can have any transformation. I have to convert the View into PDF using CGContext. The PDF is created but there is issue in label positions in final PDF file when I rotate them in View. I don't know where I am doing wrong. I am using a Category to Draw hierarchy.

Below is my code and Source view and final PDF. Original View PDF File created

UIGraphicsBeginPDFContextToFile(myPathDocs, CGRectMake(0, 0, 612, 792), nil);
// Mark the beginning of a new page.
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(),bgColor.CGColor);
CGContextFillRect(UIGraphicsGetCurrentContext(),CGRectMake(0, 0, 612, 792));
    [_pdfView drawHierarchy];
UIGraphicsEndPDFContext();


// Category
#import "UIView+HierarchicalDrawing.h"


@implementation UIView (HierarchicalDrawing)

- (void)drawHierarchy {

    [self layoutSubviews];

    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextSaveGState(c);

    CGContextTranslateCTM(c, self.frame.origin.x, self.frame.origin.y);

    if (self.backgroundColor != nil) {
        CGContextSetFillColorWithColor(c, [self.backgroundColor CGColor]);
        CGContextFillRect(c, self.bounds);
    }
    if ([self isKindOfClass:[UIImageView class]]) {
        if(self.layer.shadowColor) {
            CGContextSetShadowWithColor(c, self.layer.shadowOffset, 0.0, self.layer.shadowColor);
        }
    }

    if ([self isKindOfClass:[UILabel class]]) {

        CGPoint centrePoint = self.center;
        CGFloat angle = atan2f(self.transform.b, self.transform.a);

        CGContextRotateCTM(c, angle); 

    }

    [self drawRect:self.bounds];

    if(self.clipsToBounds) CGContextClipToRect(c, self.bounds);

    for(UIView *v in self.subviews) {
        if(v.hidden) continue;
        [v drawHierarchy];
    }
    //    NSLog(@"counter is %d",counter);
    CGContextRestoreGState(c);
}
@end
Mudassir
  • 71
  • 11
  • The first image is the screenshot of my final pdf file. The first second one is the source view that I have to convert. – Mudassir Jan 29 '19 at 05:50
  • If you want to make any Edit please do it in correct way so that it should be readable. – TheTiger Jan 29 '19 at 05:50
  • First try capturing the screenshot of main view and save that image into desktop or directory, Open it and check if it is correct, then make PDF of it. – TheTiger Jan 29 '19 at 05:52
  • I have checked there is a slight difference but not as in pdf. Also, in pdf file the text should be copied, that is why i'm using CGContext. – Mudassir Jan 29 '19 at 06:04
  • Can anyone suggest any solution? – Mudassir Feb 07 '19 at 10:01

0 Answers0