• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 在 Web View 中生成 PDF 时,如何首先将 PDF 数据写入文件

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:49:27 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我的应用在生成 PDF 时不断收到内存警告和随后的崩溃。有人建议我先将我的 PDF 写入文件,但没有提供扩展。

这是我第一次使用 iOS 生成 PDF,尽管查看了 Apple 文档 http://developer.apple.com/library/ios/#documentation/2ddrawing/conceptual/drawingprintingios/GeneratingPDF/GeneratingPDF.html并搜索 SO、Google 并使用 UIGraphicsBeginPDFContextToFile 我只是不断收到警告/没有生成 PDF 或抛出异常,因为我只是在猜测。这个概念我还真没搞懂。

有人可以提供一些关于如何首先将我的 PDF 写入文件的建议

- (void)viewWillAppearBOOL)animated
 {
 LogCmd();

[super viewWillAppear:animated];
 if (self.pdfData != nil && self.viewHasUnloaded == YES) {
self.viewHasUnloaded = NO;
[self.webView loadData:self.pdfData MIMEType"application/pdf" textEncodingName"utf-8"   baseURL:nil];
 }
}



- (void)viewDidAppearBOOL)animated
 {

  LogCmd();
 [super viewDidAppear:animated];
 if (self.pdfData == nil) {



// Generate PDF
 [ICUtils showProgressViewWithTitle"Generating PDF. This may take a minute..."];
 [self performSelectorInBackgroundselector(generatePdf) withObject:nil];
  }
 }

 - (void)generatePdf
  {
  NSMutableArray *pagesArray = [NSMutableArray array];

 if ([self.certificate.certificateType.title isEqualToString"EICR"]) {
[pagesArray addObject:[[ICPDFEICRPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPage2 alloc] initWithCertificate:self.certificate]];
[self addObservationsToPagesArray:pagesArray];
[self addDistributionBoardsToPagesArray:pagesArray];
[pagesArray addObject:[[ICPDFEICRInspection alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage1 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage2 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRInspectionPage3 alloc] initWithCertificate:self.certificate]];
[pagesArray addObject:[[ICPDFEICRPageFinal alloc] initWithCertificate:self.certificate]];
    }

    // Set page count on all pages
     int pageNumber = 0;
     for (ICCertificateComponent *page in pagesArray) {
     page.pageNumber.text = [NSString stringWithFormat"%d", ++pageNumber];
     page.pageCount.text = [NSString stringWithFormat"%d", pagesArray.count];
   }

   NSData *pdfData = [self createPdfWithPages:pagesArray];
   [self performSelectorOnMainThreadselector(pdfDone withObject:pdfData waitUntilDone:YES];

  }
 }
 - (void)pdfDoneNSData *)data
 {
self.pdfData = data;
[self.webView loadData:self.pdfData MIMEType"application/pdf" textEncodingName"utf-8"   baseURL:nil];
[ICUtils removeProgressView];
      }


- (NSData *)createPdfWithPagesNSArray *)pages

     {
    // Creates a mutable data object for updating with binary data, like a byte array

 NSMutableData *pdfData = [NSMutableData data];

 ICCertificateComponent *firstPage = [pages objectAtIndex:0];

 UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

 for (int i = 0; i < pages.count; i++) {
   ICCertificateComponent *thisPage = [pages objectAtIndex:i];
UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[thisPage.contentView.layer renderInContext:pdfContext];
   }

 UIGraphicsEndPDFContext();

 return pdfData;

 }

我的尝试

 -(void)createPDFfromUIViewUIView*)aView saveToDocumentsWithFileNameNSString*)aFilename
 {

 NSArray *pages;
// Creates a mutable data object for updating with binary data, like a byte array
        NSMutableData *pdfData = [NSMutableData data];

    ICCertificateComponent *firstPage = [pages objectAtIndex:0];

    UIGraphicsBeginPDFContextToData(pdfData, firstPage.contentView.bounds, nil);

    for (int i = 0; i < pages.count; i++) {
        ICCertificateComponent *thisPage = [pages objectAtIndex:i];
        UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

        CGContextRef pdfContext = UIGraphicsGetCurrentContext();
        [thisPage.contentView.layer renderInContext:pdfContext];
      }

    UIGraphicsBeginPDFPage();
   CGContextRef currentContext = UIGraphicsGetCurrentContext();
 animated:NO];
 [_webView.layer renderInContext:currentContext];



  UIGraphicsEndPDFContext();

   NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);

   NSString* documentDirectory = [documentDirectories objectAtIndex:0];
   NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:aFilename];

  //return pdfData;
  [pdfData writeToFile:documentDirectoryFilename atomically:YES];
}

错误:抛出异常 'NSInvalidArgumentException',原因:'-[ICPDFPreviewController createPdfWithPages:]: unrecognized selector sent to instance 其中我确定

也试过了:

 - (NSString *)createPdfWithPagesNSArray *)pages
 {

    @autoreleasepool {



    ICCertificateComponent *firstPage = [pages objectAtIndex:0];

    NSString *docDirectory =
    [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *pdfPath = [docDirectory stringByAppendingPathComponent:@"pdfFile.pdf"];

    UIGraphicsBeginPDFContextToFile(pdfPath, firstPage.contentView.bounds, nil);

    for (int i = 0; i < pages.count; i++) {
        ICCertificateComponent *thisPage = [pages objectAtIndex:i];
        UIGraphicsBeginPDFPageWithInfo(thisPage.contentView.bounds, nil);

        CGContextRef pdfContext = UIGraphicsGetCurrentContext();
        [thisPage.contentView.layer renderInContext:pdfContext];
               }

    UIGraphicsEndPDFContext();

    return pdfPath;

}

错误:NSInvalidArgumentException',原因:'-[NSPathStore2 bytes]: unrecognized selector sent to instance 0x24aa4580'



Best Answer-推荐答案


你试试下面的代码。

+(void)drawLineFromPointCGPoint)from toPointCGPoint)to
{

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetLineWidth(context, 2.0);

    CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();

    CGFloat components[] = {0.2, 0.2, 0.2, 0.3};

    CGColorRef color = CGColorCreate(colorspace, components);

    CGContextSetStrokeColorWithColor(context, color);

    CGContextMoveToPoint(context, from.x, from.y);
    CGContextAddLineToPoint(context, to.x, to.y);

    CGContextStrokePath(context);
    CGColorSpaceRelease(colorspace);
    CGColorRelease(color);

}

+(void)drawText
{

    NSString* textToDraw = @"Hello World";
    CFStringRef stringRef = (__bridge CFStringRef)textToDraw;
    // Prepare the text using a Core Text Framesetter
    CFAttributedStringRef currentText = CFAttributedStringCreate(NULL, stringRef, NULL);
    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(currentText);

    CGRect frameRect = CGRectMake(0, 0, 300, 50);
    CGMutablePathRef framePath = CGPathCreateMutable();
    CGPathAddRect(framePath, NULL, frameRect);

    // Get the frame that will do the rendering.
    CFRange currentRange = CFRangeMake(0, 0);
    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, currentRange, framePath, NULL);
    CGPathRelease(framePath);

    // Get the graphics context.
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    // Put the text matrix into a known state. This ensures
    // that no old scaling factors are left in place.
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity);

    // Core Text draws from the bottom-left corner up, so flip
    // the current transform prior to drawing.
    CGContextTranslateCTM(currentContext, 0, 100);
    CGContextScaleCTM(currentContext, 1.0, -1.0);

    // Draw the frame.
    CTFrameDraw(frameRef, currentContext);

    CFRelease(frameRef);
    CFRelease(stringRef);
    CFRelease(framesetter);
}

+(void)drawPDFNSString*)fileName
{

    // Create the PDF context using the default page size of 612 x 792.
    UIGraphicsBeginPDFContextToFile(fileName, CGRectZero, nil);
    // Mark the beginning of a new page.
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);

    CGPoint from = CGPointMake(0, 0);
    CGPoint to = CGPointMake(200, 300);
    [PDFRenderer drawLineFromPoint:from toPoint:to];

    [self drawText];

    // Close the PDF context and write the contents out.
    UIGraphicsEndPDFContext();
}

关于ios - 在 Web View 中生成 PDF 时,如何首先将 PDF 数据写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16416206/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap