Erstellen von PDF-Dateien aus UIWebView

 -(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];

    //Get the number of pages needed to print. 9 * 72 = 648
    int pages = ceil(height / 648.0);

    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
  CGRect frame = [webView frame];
    for (int i = 0; i < pages; i++) {
      //Check to see if page draws more than the height of the UIWebView
        if ((i+1) * 648 > height) {
            CGRect f = [webView frame];
            f.size.height -= (((i+1) * 648.0) - height);
            [webView setFrame: f];
        }

        UIGraphicsBeginPDFPage();
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
        CGContextTranslateCTM(currentContext, 72, 72); //Translate for 1" margins

        [[[webView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * 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];
  NSLog(@"documentDirectoryFileName: %@",documentDirectoryFilename);
}

Bin ich mit dem code oben, erzeugt eine pdf-Datei aus einer webview. Es funktioniert, allerdings wird der Inhalt nicht abgeschnitten wird richtig : die Inhalte auf der Unterseite die Seiten Durcheinander kommen.
Ich denke, ich könnte etwas tun, verwenden Sie besser Core Graphics-Methoden, aber ich kann nicht herausfinden, wie das zu tun. Irgendwelche Ideen ?

InformationsquelleAutor der Frage AnderCover | 2013-04-04

Schreibe einen Kommentar