Xcode save a PDF as Image?

后端 未结 4 398
不思量自难忘°
不思量自难忘° 2020-12-21 05:36

I have a question, is it possible to save a PDF to Camera Roll? I mean, I know how to save a Picture, but can you save a PDF as well?

相关标签:
4条回答
  • 2020-12-21 06:35

    You could convert the PDF into a set of images, and import those into the roll. You cannot add the actual PDF to the roll.

    0 讨论(0)
  • 2020-12-21 06:36

    As @jshin47 - the following fragment will get you going:

    This converts a pdf called test.pdf sitting in the local documents directory to a png called test.png. I've used A4 dimensions for the PDF, but if you're not in UK / Europe you might need to US letter sizes.

    NSString* localDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString* pdfPath = [localDocuments stringByAppendingPathComponent:@"test.pdf"];
    
    // create a sample PDF (just for illustration)
    UIGraphicsBeginPDFContextToFile(pdfPath, CGRectZero, nil);
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil);
    [@"Test string" drawInRect:CGRectMake(50, 50, 300, 200) withFont: [UIFont systemFontOfSize: 48.0]];
    UIGraphicsEndPDFContext();
    
    NSURL* url = [NSURL fileURLWithPath: pdfPath];
    
    CGPDFDocumentRef document = CGPDFDocumentCreateWithURL ((CFURLRef) url);
    
    UIGraphicsBeginImageContext(CGSizeMake(596,842));
    CGContextRef currentContext = UIGraphicsGetCurrentContext();
    
    CGContextTranslateCTM(currentContext, 0, 842);
    CGContextScaleCTM(currentContext, 1.0, -1.0); // make sure the page is the right way up
    
    CGPDFPageRef page = CGPDFDocumentGetPage (document, 1); // first page of PDF is page 1 (not zero)
    CGContextDrawPDFPage (currentContext, page);  // draws the page in the graphics context
    
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSString* imagePath = [localDocuments stringByAppendingPathComponent: @"test.png"];
    [UIImagePNGRepresentation(image) writeToFile: imagePath atomically:YES];
    
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); // do error checking in production code
    
    0 讨论(0)
  • 2020-12-21 06:39

    No, that is not possible. Apple only allows Photos and Videos to be stored in the Photo Library. PDF formatted files can be stored in iBooks, or other programs that can handle PDF's but the Photo Library cannot accept PDF's

    0 讨论(0)
  • 2020-12-21 06:41

    If you try to do it indirectly, and some one has tried it, you can't view it. https://discussions.apple.com/thread/2479252

    Camera Roll is for Photos. iBooks is for PDFs.

    0 讨论(0)
提交回复
热议问题