Ios pdf zooming at specific coordinate - ios

i created a Ios app for reading pdf documents following Apple pdf zooming
https://developer.apple.com/library/ios/samplecode/zoomingpdfviewer/Introduction/Intro.html
but , i don't know how to zoom pdf pages at specific coordinate automatically ,
i mean when my did load method the pdf page zoomed at specific coordinate(x, y) such as : (10, 20)
some body help me ? please !
thank !

From Apple's Sample Code of Zooming PDF Viewer
UIScrollView has the API to do that
[yourScrollView zoomToRect:CGRectMake(X, Y, Width, Height) animated:YES];
Basically if you want to see the animation on your changes then you can put your code in View did Appear method.
#import "ZoomingPDFViewerViewController.h"
#import "PDFScrollView.h"
#import <QuartzCore/QuartzCore.h>
#implementation ZoomingPDFViewerViewController
- (void)viewDidLoad
{
[super viewDidLoad];
/*
Open the PDF document, extract the first page, and pass the page to the PDF scroll view.
*/
NSURL *pdfURL = [[NSBundle mainBundle] URLForResource:#"TestPage" withExtension:#"pdf"];
CGPDFDocumentRef PDFDocument = CGPDFDocumentCreateWithURL((__bridge CFURLRef)pdfURL);
CGPDFPageRef PDFPage = CGPDFDocumentGetPage(PDFDocument, 1);
[(PDFScrollView *)self.view setPDFPage:PDFPage];
CGPDFDocumentRelease(PDFDocument);
}
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
// 1. Get the Scroll View
UIScrollView *scrollView = (UIScrollView*)self.view;
// 2. Zoom to specified rect
[scrollView zoomToRect:CGRectMake(X, Y, Width, Height) animated:YES];
}

Related

display specific pdf page in the UIWebview ios

I am currently working on a project and I have ios need to display a pdf file.
However i want choose the page to display.
For example see page 10 of 37 in a UIWebView.
I have not found a way to cleanly separate the pages of a pfd.
thank you for your help.
Use UIWebView's delegate method to do this:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//Check if file still loading
if(!webView.isLoading)
{
//now traverse to specific page
[self performSelector:#selector(traverseInWebViewWithPage) withObject:nil afterDelay:0.1];
}
}
Now add below method to traverse to your page. Note need valid PDF file path and provide your valid specific page no you want traverse in PDF file.
-(void)traverseInWebViewWithPage
{
//Get total pages in PDF File ----------- PDF File name here ---------------
NSString *strPDFFilePath = [[NSBundle mainBundle] pathForResource:#"yourPDFFileNameHere" ofType:#"pdf"];
NSInteger totalPDFPages = [self getTotalPDFPages:strPDFFilePath];
//Get total PDF pages height in webView
CGFloat totalPDFHeight = yourWebViewPDF.scrollView.contentSize.height;
NSLog ( #"total pdf height: %f", totalPDFHeight);
//Calculate page height of single PDF page in webView
NSInteger horizontalPaddingBetweenPages = 10*(totalPDFPages+1);
CGFloat pageHeight = (totalPDFHeight-horizontalPaddingBetweenPages)/(CGFloat)totalPDFPages;
NSLog ( #"pdf page height: %f", pageHeight);
//scroll to specific page --------------- here your page number -----------
NSInteger specificPageNo = 2;
if(specificPageNo <= totalPDFPages)
{
//calculate offset point in webView
CGPoint offsetPoint = CGPointMake(0, (10*(specificPageNo-1))+(pageHeight*(specificPageNo-1)));
//set offset in webView
[yourWebViewPDF.scrollView setContentOffset:offsetPoint];
}
}
For calculation of total PDF pages
-(NSInteger)getTotalPDFPages:(NSString *)strPDFFilePath
{
NSURL *pdfUrl = [NSURL fileURLWithPath:strPDFFilePath];
CGPDFDocumentRef document = CGPDFDocumentCreateWithURL((CFURLRef)pdfUrl);
size_t pageCount = CGPDFDocumentGetNumberOfPages(document);
return pageCount;
}
Enjoy coding .....
You can use setContentOffset property of webview to show that page,
[[webView scrollView] setContentOffset:CGPointMake(0,10*pageheight) animated:YES];
where pageheight=your page height, 10 is your page no,

UIWebview full screen size

I am trying to display a pdf in a UIWebview using the entire screen of the device, except the status bar and top bar. So far, I created IBOutlet UIWebview *webview; in my .h file. I connected the webview in my storyboard and wrote the following code in my .m file:
- (void)viewDidLoad
{
[super viewDidLoad];
webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
webview.scalesPageToFit = YES;
webview.autoresizesSubviews = YES;
webview.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
[webview setBackgroundColor:[UIColor clearColor]];
NSString *path = [[NSBundle mainBundle] pathForResource:#"Chart" ofType:#"pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webview loadRequest:request];
[self.view addSubview:webview];
}
The pdf displays correctly in my 3.5 inch, but in my 4 inch display, the bottom is cut off. This is even more noticeable when I rotate to landscape view. About 33% of the screen is not used at all. How can I fix this? I know it must have something to do with the UIWebview dimensions in my code above (webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];), but is there a better way to simply display the webview on the entire screen, without specifying a specific screen height and width?
One cheap thing to do would be to set the frame of the webview in overriding - (void)viewDidLayoutSubviews
- (void)viewDidLayoutSubviews {
webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
}
the advantage of doing it here, is that the size and orientation of the view has already been determined here, and you can get an accurate measurement.
Using Auto Layout
Be sure the "Constrain to margins" option is not checked, all constrain values are 0:
And your webview is a first child of your main view:
Without Auto Layout
Change webview autosizing connections:
After a lot of headache dealing with compatibility of iOS6, 7 and different screen sizes, I use this one:
- (void)viewDidLoad {
[super viewDidLoad];
self.webview = [[UIWebView alloc] init];
// More setting your webview here
// Set webview to full screen
self.view = self.webview;
[self.webview loadRequest:aRequest];
}
I was able to get this working correctly for me by selecting the Reset to Suggested Constraints under the Resolve Auto Layout Issues menu.

How to size UIWebView in a UIModalPresentationFormSheet?

I tried every permutation known to mankind and I cannot get a UIWebView to size properly in a modal form view for the iPad. The web page still displays the full iPad portrait width of 768 points.
Where and how do I tell UIWebView to display width 540 points?
I thought 'scalesPageToFit' is supposed to do this but it does not work.
I tried setting the web view to the size of form view which is 540 x 576 with navigation and status bar. Height is irrelevant though.
I tried adding a UIWebView to a UIView in a storyboard with all resizing set. I then removed the UIWebView and added it programmatically.
- (void)viewDidLoad
{
[super viewDidLoad];
CGRect aFrame = self.view.frame;
if (IS_IPAD)
{
aFrame = CGRectMake(0, 0, FORM_VIEW_WIDTH, FORM_VIEW_HEIGHT);
}
_webView = [[UIWebView alloc] initWithFrame:aFrame];
[_webView setOpaque:NO];
[_webView setDelegate:self];
[_webView setScalesPageToFit:YES];
self.view = _webView;
...
}
I also tried loading in viewDidAppear (in addition to viewDidLoad, viewWillAppear, etc.)
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[self webView] setFrame:CGRectMake(0, 0, FORM_VIEW_WIDTH, FORM_VIEW_HEIGHT)];
[[self webView] setScalesPageToFit:YES];
NSURL *webURL = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0f];
[[self webView] loadRequest:request];
}
Any recommendations appreciated.
This keeps happening to me. I post a lengthy question, then two seconds later I find the answer.
Anyway, someone posted a solution to this problem here:
UIWebView -- load external website, programmatically set initial zoom scale, and allow user to zoom afterwards
However, I altered the script to set the width to the iPad width:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString* js =
#"var meta = document.createElement('meta'); "
#"meta.setAttribute( 'name', 'viewport' ); "
#"meta.setAttribute( 'content', 'width = 540px, initial-scale = 1.0, user-scalable = yes' ); "
#"document.getElementsByTagName('head')[0].appendChild(meta)";
[[self webView] stringByEvaluatingJavaScriptFromString: js];
}
Note the portion 'width = 540px, initial-scale = 1.0, user-scalable = yes'
I changed the width to the form width and scale to 1.0.
I also need to handle iPhone, and so I will make adjustments for that next. I think this fix may only be needed for the iPad form view.
UPDATE: Answer is short-lived. If I load any other page the sizing is thrown off again. Back to square one.
SOLUTION: This view will only need to access a few web pages that I developed. Therefore, I updated the few web pages that I need to access by adding the meta tag to each of them. I only need to access these pages and so this is the solution I plan to go with. This means I need to set the viewport width to 540px only for iPad somehow. I will figure that out next.
<meta name="viewport" content="width:540, initial-scale=1, maximum-scale=1">

How can I generate a PDF with "real" text content on iOS?

I want to generate a good-looking PDF in my iOS 6 app.
I've tried:
UIView render in context
Using CoreText
Using NSString drawInRect
Using UILabel drawRect
Here is a code example:
-(CGContextRef) createPDFContext:(CGRect)inMediaBox path:(NSString *) path
{
CGContextRef myOutContext = NULL;
NSURL * url;
url = [NSURL fileURLWithPath:path];
if (url != NULL) {
myOutContext = CGPDFContextCreateWithURL ((__bridge CFURLRef) url,
&inMediaBox,
NULL);
}
return myOutContext;
}
-(void)savePdf:(NSString *)outputPath
{
if (!pageViews.count)
return;
UIView * first = [pageViews objectAtIndex:0];
CGContextRef pdfContext = [self createPDFContext:CGRectMake(0, 0, first.frame.size.width, first.frame.size.height) path:outputPath];
for(UIView * v in pageViews)
{
CGContextBeginPage (pdfContext,nil);
CGAffineTransform transform = CGAffineTransformIdentity;
transform = CGAffineTransformMakeTranslation(0, (int)(v.frame.size.height));
transform = CGAffineTransformScale(transform, 1, -1);
CGContextConcatCTM(pdfContext, transform);
CGContextSetFillColorWithColor(pdfContext, [UIColor whiteColor].CGColor);
CGContextFillRect(pdfContext, v.frame);
[v.layer renderInContext:pdfContext];
CGContextEndPage (pdfContext);
}
CGContextRelease (pdfContext);
}
The UIViews that are rendered only contain a UIImageView + a bunch of UILabels (some with and some without borders).
I also tried a suggestion found on stackoverflow: subclassing UILabel and doing this:
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx {
BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds());
if (!layer.shouldRasterize && isPDF)
[self drawRect:self.bounds]; // draw unrasterized
else
[super drawLayer:layer inContext:ctx];
}
But that didn't change anything either.
No matter what I do, when opening the PDF in Preview the text parts are selectable as a block, but not character per character, and zooming the pdf shows it is actually a bitmap image.
Any suggestions?
This Tutorial From Raywenderlich Saved my Day.Hope it will work for you too.
http://www.raywenderlich.com/6818/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-2
My experience when I did this last year was that Apple didn't provide any library to do it. I ended up importing an open source C library (libHaru). Then I added a function for outputting to it in each class in my view hierarchy. Any view with subviews would call render on its subviews. My UILabels, UITextFields, UIImageViews, UISwitches etc would output their content either as text or graphics accordingly I also rendered background colors for some views.
It wasn't very daunting, but libHaru gave me some problems with fonts so iirc I ended up just using the default font and font size.
It works good with UILabels except that you have to work around a bug:
Rendering a UIView into a PDF as vectors on an iPad - Sometimes renders as bitmap, sometimes as vectors

ipad orientation problem with webview

I'm creating ipad application. It has just 2 views.
One view has few buttons. On click of a button it will open another view. This view has a webview which shows PDF file. I'm using the following code to show the PDF
- (void)viewDidLoad {
[super viewDidLoad];
NSString* path = [[NSBundle mainBundle] pathForResource:#"mypdf" ofType:#"pdf"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];
}
Now the problem is that, when I change the orientation, whole view is rotating, but the pdf is being disturbed and not rendering properly. how can I avoid this?
As the PDF is having 250 pages, reloading the whole PDF on willRotateToInterfaceOrientation and didRotateFromInterfaceOrientation will delay the display.
How to avoid this situation.
There has to be a way a better to avoid/fix this, for now i just read the y scroll position with:
int scrollPosition = [[webView stringByEvaluatingJavaScriptFromString:#"window.pageYOffset"] intValue];
Then reloaded the document in:
(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
and then set the scroll position again with:
[webView stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:#"scrollTo(0,%d)",scrollPosition];

Resources