How to use pdfkit ios 11 to open pdf file?

2020-07-13 03:15发布

问题:

I am trying to open PDF file using new iOS 11 framework pdfkit.

But I am unable to do that.

So help me in opening the file using pdfkit framework.

Thank you in Advance.

回答1:

For new PDFKit,

you need to import PDFKit

Then create a view of PDFView and give a PDFDocument to view's document. Check the below code for reference.

let pdfView = PDFView(frame: self.view.bounds)
let url = Bundle.main.url(forResource: "pdfFile", withExtension: "pdf")
pdfView.document = PDFDocument(url: url!)
self.view.addSubview(pdfView)


回答2:

Here is Objective-C based example

  1. Ensure PDFKit framework is added to the project

  2. Import the framework header #import <PDFKit/PDFKit.h>

  3. Create PDFDocument instance. In my case, it was using NSURL

    // fileURL is NSURL file path instance created using base64 pdf content PDFDocument *pdfDocument = [[PDFDocument alloc] initWithURL:fileURL];

  4. Create PDFView instance and assign the pdfDocument document to it

    PDFView *pdfView = [[PDFView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)]; pdfView.document = pdfDocument; pdfView.displayMode = kPDFDisplaySinglePageContinuous; pdfView.autoScales = true; pdfView.layer.borderWidth = 2; pdfView.layer.borderColor = [UIColor blueColor].CGColor;

As done by many others, we were using webview for showing and interacting with PDF content. Reading through the framework and trying some samples, PDFKit comes out as a thoughtful design where multitude of features are available out of the box and eases development.

For example, we had AirPrint functionality in the application which had this check for determining printability

if ([UIPrintInteractionController canPrintData: fileData]) {

After replacing webview implementation with PDFKit, I just had to use dataRepresentation method to get fileData and the rest just worked as is

NSData *fileData = [pdfDocument dataRepresentation];

Please check this WWDC page for additional details



回答3:

Here is Objective-C based example

#import <PDFKit/PDFKit.h>



PDFView *View = [[PDFView alloc] initWithFrame: self.view.bounds];
View.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;
View.autoScales = NO ;
View.displayDirection = kPDFDisplayDirectionHorizontal;
View.displayMode = kPDFDisplaySinglePageContinuous;
View.displaysRTL = YES ;
[View setDisplaysPageBreaks:YES];
[View setDisplayBox:kPDFDisplayBoxTrimBox];
[View zoomIn:self];
[self.view addSubview:View];

NSURL * URL = [[NSBundle mainBundle] URLForResource: @"test" withExtension: @ "pdf" ];
PDFDocument * document = [[PDFDocument alloc] initWithURL: URL];
View.document = document;