Creating PDF file from UIWebView

后端 未结 6 1934
天命终不由人
天命终不由人 2020-11-29 19:10
 -(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
    // Creates a mutable data object for updating with binary data, lik         


        
6条回答
  •  醉梦人生
    2020-11-29 19:50

    Thank you for your answers Firemarble, it helped me a lot. I managed to get a somewhat good looking results with this method :

    -(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
    {
        // Creates a mutable data object for updating with binary data, like a byte array
      UIWebView *webView = (UIWebView*)aView;
        NSString *heightStr = [webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
    
        int height = [heightStr intValue];
    //  CGRect screenRect = [[UIScreen mainScreen] bounds];
    //  CGFloat screenHeight = (self.contentWebView.hidden)?screenRect.size.width:screenRect.size.height;
      CGFloat screenHeight = webView.bounds.size.height;
        int pages = ceil(height / screenHeight);
    
      NSMutableData *pdfData = [NSMutableData data];
      UIGraphicsBeginPDFContextToData(pdfData, webView.bounds, nil);
     CGRect frame = [webView frame];
        for (int i = 0; i < pages; i++) {
          // Check to screenHeight if page draws more than the height of the UIWebView
            if ((i+1) * screenHeight  > height) {
                CGRect f = [webView frame];
                f.size.height -= (((i+1) * screenHeight) - height);
                [webView setFrame: f];
            }
    
            UIGraphicsBeginPDFPage();
            CGContextRef currentContext = UIGraphicsGetCurrentContext();
    //      CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
    
            [[[webView subviews] lastObject] setContentOffset:CGPointMake(0, screenHeight * i) animated:NO];
            [webView.layer renderInContext:currentContext];
        }
    
        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];
      [webView setFrame:frame];
    }
    

提交回复
热议问题