在 objective c 中从 uiwebview 生成 PDF 的问题

Issues in generating PDF from uiwebview in objective c

我已在 uiwebview 中打开 pdf 文件,在 uiwebview 中添加图像和文本 subview.Then 我尝试创建 pdf 文件。下面的示例我已经用来生成 pdf 文件。单页写多页。我如何写样品质量和确切尺寸。 请查看屏幕截图和下方来源

UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );

for (int i = 0; i < 10; i++) {

    CGRect f = [pdfView frame];
    [pdfView setFrame: f];

    UIGraphicsBeginPDFPage();
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(currentContext, 72, 72); // Translate for 1" margins
    [[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
    [pdfView.layer renderInContext:currentContext];
}

UIGraphicsEndPDFContext();

而且我在 link 之后也试过这个,但我无法添加 uiwebview 子视图来编写 pdf。 http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/

你可以试试 this.It 对我有用:)

https://github.com/iclems/iOS-htmltopdf/blob/master/NDHTMLtoPDF.h

NSString *html = [webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];

 self.PDFCreator = [NDHTMLtoPDF createPDFWithHTML:html
                                          pathForPDF:[path  stringByExpandingTildeInPath]
                                            delegate:self
                                            pageSize:CGSizeMake(595,847)
                                             margins:UIEdgeInsetsMake(105, 0, 0, 0)];

像这样传递webView

您可以在 UIView 上使用以下类别来创建 PDF 文件:

#import <QuartzCore/QuartzCore.h>

@implementation UIView(PDFWritingAdditions)

- (void)renderInPDFFile:(NSString*)path
{
    CGRect mediaBox = self.bounds;
    CGContextRef ctx = CGPDFContextCreateWithURL((CFURLRef)[NSURL fileURLWithPath:path], &mediaBox, NULL);

    CGPDFContextBeginPage(ctx, NULL);
    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -mediaBox.size.height);
    [self.layer renderInContext:ctx];
    CGPDFContextEndPage(ctx);
    CFRelease(ctx);
}

@end

坏消息:UIWebView 不会在 PDF 中创建漂亮的形状和文本,而是将其自身呈现为 PDF 中的图像。

How to Convert UIView to PDF within iOS?

Creating PDF file from UIWebView

这可能对你有帮助:)

我也用过,效果不错 希望对你有帮助。

创建区块:-
typedef void (^PdfCompletion)(BOOL status,NSString *filePath,NSArray *fbArr);

-(void)addData
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSMutableDictionary *contactDict = [[NSMutableDictionary alloc] init];
    [contactDict setObject:contactTextField.text forKey:@"phonenumber"];
    [contactDict setObject:emailTextField.text forKey:@"emailid"];
    [contactDict setObject:userNameLabel.text forKey:@"displayname"];
    [self drawPdf:contactDict completion:^(BOOL status,NSString *filePath,NSArray *fbArr)
     {
         if (status)
         {
             NSMutableArray *arr;
             arr = [[NSMutableArray alloc] init];
             NSData *filedata;
             filedata = [NSData dataWithContentsOfFile:filePath];
             double locaTotalFileSize = filedata.length +498;
             totalFileSize += locaTotalFileSize;
             NSMutableDictionary *fileDict = [[NSMutableDictionary alloc] init];
             [fileDict setObject:userPicImageView.image forKey:@"image"];
             [fileDict setObject:filePath forKey:@"filePath"];
             [fileDict setObject:@"txt" forKey:@"fileType"];
             [fileDict setObject:[NSString stringWithFormat:@"%@_%@_%@",@"contact",[self getFbID],[self CurrentSystemTime]] forKey:@"fileName"];
             [fileDict setObject:@"1" forKey:@"uploadStatus"];
             [fileDict setObject:@"0 KB/0 KB" forKey:@"fileSizeStatus"];
             [fileDict setObject:@"0 KB/0 KB" forKey:@"ContentSize"];
             [arr addObject:fileDict];
             [self switchToReviewFiles:arr];
             //////NSLog(@"pdf convrt successfull");
         }
         else
         {
             //////NSLog(@"Error to convert into pdf");
         }
     }];
}


 // Then Call The DrawPDF Method::--

 -(void)drawPdf:(NSMutableDictionary *)drawText completion:(PdfCompletion)callback
{
    NSString* fileName = @"contact_card.txt";

    NSArray *arrayPaths =
    NSSearchPathForDirectoriesInDomains(
                                        NSDocumentDirectory,
                                        NSUserDomainMask,
                                        YES);
    NSString *path = [arrayPaths objectAtIndex:0];
    NSString* txtFileName = [path stringByAppendingPathComponent:fileName];

    NSData *data = [NSJSONSerialization dataWithJSONObject:drawText options:NSJSONWritingPrettyPrinted error:nil];
    [data writeToFile:txtFileName atomically:YES];
     callback(YES,txtFileName,nil);

}

你实际上已经非常接近你的代码了。我感觉你最大的问题是每次循环迭代都获取一个新的 CGContextRef ..

UIGraphicsBeginPDFContextToData( pdfData, CGRectZero, nil );
CGContextRef currentContext = UIGraphicsGetCurrentContext();//movedByJef

  //  default pdf..
  // 8.5 X 11 inch
  // 612 x 792


for (int i = 0; i < 10; i++) {

    CGContextSaveGstate( currentContext ); //addedByJef

    CGRect f = [pdfView frame];
    [pdfView setFrame: f]; // hmm what does this even do??

    UIGraphicsBeginPDFPage();
    CGContextTranslateCTM(currentContext, -72, -72); // Translate for 1" margins ///editedByJef, you had it backwards..

//assuming you want a 72pt margin on right and bottom as well..
//we want to reduce our size (612 x 792) by 72pts on all four sides..

CGSize printPageSize = CGSizeMake( (612.0 - (72.0 * 2.0)), (792.0 -(72.0*2.0)) );
CGSize layrSize = self.layer.bounds.size;

//so we translate the context so our view fills it nicely..
CGFloat xScaler = layrSize.width / printPageSize.width;
CGFloat yScaler = layrSize.height / printPageSize.height;

CGContextConcatCTM(currentContext, CGAffineTransformMakeScale(xScaler, yScaler) );


    [[[pdfView subviews] lastObject] setContentOffset:CGPointMake(0, 648 * i) animated:NO];
    [pdfView.layer renderInContext:currentContext];

CGContextRestoreGstate(currentContext);//added by jef
}

UIGraphicsEndPDFContext();

让我知道你是怎么处理的,毫无疑问,转换的顺序会有一些混乱,也许缩放的任何一侧都需要转换,但这应该让你非常接近..

在我看来,您只是想向现有 PDF 添加内容,对吗?

- (void) drawCustomPDFContent
{
    //  Put your drawing calls here
    //  Draw a red box
    [[UIColor redColor] set];
    UIRectFill(CGRectMake(20, 20, 100, 100));

    //  Example of drawing your view into PDF, note that this will be a rasterized bitmap, including the text.
    //  To get smoother text you'll need to use the NSString draw methods
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:ctx];
}

- (void) createCustomPDF
{
    NSURL* pdfURL = ... /* URL to pdf file */;
    CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);

    const size_t numberOfPages = CGPDFDocumentGetNumberOfPages(pdf);

    NSMutableData* data = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(data, CGRectZero, nil);

    for(size_t page = 1; page <= numberOfPages; page++)
    {
        //  Get the current page and page frame
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(pdf, page);
        const CGRect pageFrame = CGPDFPageGetBoxRect(pdfPage, kCGPDFMediaBox);

        UIGraphicsBeginPDFPageWithInfo(pageFrame, nil);

        //  Draw the page (flipped)
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGContextSaveGState(ctx);
        CGContextScaleCTM(ctx, 1, -1);
        CGContextTranslateCTM(ctx, 0, -pageFrame.size.height);
        CGContextDrawPDFPage(ctx, pdfPage);
        CGContextRestoreGState(ctx);

        if(page == 1)
        {
            [self drawCustomPDFContent];
        }
    }

    UIGraphicsEndPDFContext();

    CGPDFDocumentRelease(pdf);
    pdf = nil;

    //  Do something with data here
    [data writeToFile:... atomically:YES];
}

部分引用自:

http://b2cloud.com.au/tutorial/drawing-over-a-pdf-in-ios-pdf-template/