Paste hyperlink to PDF using Core Graphics on iOS

I'm trying to do a fairly simple thing: write the URL inside the PDF file, which can actually be clicked by the user.

I know for sure that with libharu this can be done. What I'm looking for is to do the same using Core Graphics, since all the code that I already have in my application already uses these methods.

== edit ==

I think I found something: UIGraphicsSetPDFContextURLForRect , but I can't get it to work.

I am using something like:

 NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; UIGraphicsSetPDFContextURLForRect( url, CGRectMake(0, 0, 100, 100)); 

Not directly clickable.

+4
source share
1 answer

Well, I managed to find out why it does not work.

The context of the main graphic is β€œreversed” in the sense of the presence in the lower left corner of the page, and UIKit has the origin in the upper left corner.

This is the method I came up with:

 - (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect { CGContextRef context = UIGraphicsGetCurrentContext(); CGAffineTransform ctm = CGContextGetCTM(context); // Translate the origin to the bottom left. // Notice that 842 is the size of the PDF page. CGAffineTransformTranslate(ctm, 0.0, 842); // Flip the handedness of the coordinate system back to right handed. CGAffineTransformScale(ctm, 1.0, -1.0); // Convert the update rectangle to the new coordiante system. CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm); NSURL *url = [NSURL URLWithString:text]; UIGraphicsSetPDFContextURLForRect( url, xformRect ); CGContextSaveGState(context); NSDictionary *attributesDict; NSMutableAttributedString *attString; NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle]; attributesDict = @{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]}; attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict]; [attString drawInRect:frameRect]; CGContextRestoreGState(context); } 

What this method does:

  • to get the current context and apply the transformation to the provided rectangle, to get the rectangle that will work when marking the window when UIGraphicsSetPDFContextURLForRect it as clickable
  • to mark the new rectangle ( xformRect ) as clickable using the above method
  • to preserve the current context so that everything that was done later (color, size, attributes, etc.) does not remain constant in the current context.
  • to draw text in the provided rectangle (now using the UIKit coordinate system)
  • to restore the GState context
+12
source

All Articles