How to search and extract text across a whole PDF document on iOS

Searching text across all pages of a PDF on iOS

This guide shows how to search text in PDF on iOS across every page of a document with RadaeePDF, and how to reuse the same text objects to extract page text and highlight matches.

Applies to: RadaeePDF Classic and Master SDK for iOS. All snippets use selectors declared in PDFViewer/PDFLib/PDFObjc.h, which are the same in both editions.

Short answer: For each page, get an RDPDFPage with [doc page:i] and load its text with [page objsStart:false]. Then call [page find:key :matchCase :wholeWord]. The returned RDPDFFinder gives you the match count (count) and the first character index of each match (objsIndex:). Run the loop on a background queue, the way the demo’s RDExtendedSearch class does. The same character indexes work with objsString:: to extract text and with objsCharRect:: to get rectangles for highlighting.

How the text API is organized

Text search and text extraction in RadaeePDF both work on a page’s text objects. You call objsStart: once per page. After that, every character on the page has a 0-based index from 0 to objsCount - 1, and the other calls use those indexes:

  • -(void)objsStart:(bool)rtol loads the page’s text objects. Pass true only for right-to-left text. The demo passes GLOBAL.g_sel_rtol. The header notes that this needs a standard license.
  • -(int)objsCount returns the number of characters on the page.
  • -(NSString *)objsString:(int)from :(int)to returns the text for a range of character indexes.
  • -(void)objsCharRect:(int)index :(PDF_RECT *)rect returns a character’s box in PDF page coordinates.
  • -(RDPDFFinder *)find:(NSString *)key :(bool)match_case :(bool)whole_word starts a find session on the page. It returns nil when there are no matches.
  • -(RDPDFFinder *)find2:(NSString *)key :(bool)match_case :(bool)whole_word :(bool)skip_blanks does the same but treats line breaks as blanks. Use it when a phrase can wrap across lines.

RDPDFFinder has three methods: count, objsIndex: (the first character of match n) and objsEnd: (the end character of match n).

The KB sample Search in whole pdf file (iOS) uses the older names PDFDoc, PDFPage, PDFFinder and an argument-less objsStart. In the current Classic and Master repositories, these classes are RDPDFDoc, RDPDFPage and RDPDFFinder, and objsStart: takes a bool.

Search text in PDF on iOS on a background queue

On a long document, searching every page can take noticeable time, so keep it off the main thread. This is how the demo’s RDExtendedSearch works: it loops over the pages inside dispatch_async(dispatch_get_global_queue(...)) and checks a stop flag on every page so the search can be cancelled. The class below does the same thing in a self-contained way.

Objective-C (Classic and Master)

#import "PDFObjc.h"

@interface DocSearcher : NSObject
@property (atomic) BOOL cancelled;
- (void)search:(RDPDFDoc *)doc
           key:(NSString *)key
     matchCase:(bool)matchCase
     wholeWord:(bool)wholeWord
    completion:(void (^)(NSArray<NSDictionary *> *hits))completion;
@end

@implementation DocSearcher

- (void)search:(RDPDFDoc *)doc
           key:(NSString *)key
     matchCase:(bool)matchCase
     wholeWord:(bool)wholeWord
    completion:(void (^)(NSArray<NSDictionary *> *hits))completion
{
    self.cancelled = NO;
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        NSMutableArray<NSDictionary *> *hits = [NSMutableArray array];
        int pageCount = [doc pageCount];
        for (int pageno = 0; pageno < pageCount && !self.cancelled; pageno++) {
            RDPDFPage *page = [doc page:pageno];
            if (!page) break;
            [page objsStart:false];
            RDPDFFinder *finder = [page find:key :matchCase :wholeWord];
            int count = [finder count];          // 0 when finder is nil
            int chars = [page objsCount];
            for (int i = 0; i < count; i++) {
                int first = [finder objsIndex:i];
                // Context snippet around the hit, like RDExtendedSearch builds it
                int from = MAX(first - 25, 0);
                int to = MIN(first + (int)key.length + 25, chars - 1);
                from = [page objsAlignWord:from :-1];
                to = [page objsAlignWord:to :1] + 1;
                NSString *context = [page objsString:from :to];
                [hits addObject:@{ @"page": @(pageno),
                                   @"char": @(first),
                                   @"context": context ?: @"" }];
            }
            page = nil;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(hits);
        });
    });
}

@end

Set cancelled = YES when the user changes the query or closes the document, and keep the RDPDFDoc open until the completion block has run.

Reusing the demo’s RDExtendedSearch

If you embed the demo’s PDFReader sources, you can call the singleton directly. It reads the case, whole-word and right-to-left options from GLOBAL.g_case_sensitive, GLOBAL.g_match_whole_word and GLOBAL.g_sel_rtol. Each result is an RDSearchResult with stringResult and a 1-based page. Both blocks are called on the background queue, which is why SearchResultViewController hops to the main queue:

#import "RDExtendedSearch.h"

[[RDExtendedSearch sharedInstance] searchText:@"invoice" inDoc:doc progress:^(NSMutableArray *occurrences, NSMutableArray *total) {
    dispatch_async(dispatch_get_main_queue(), ^{
        for (RDSearchResult *r in occurrences) {
            NSLog(@"page %d: %@", r.page, r.stringResult);
        }
    });
} finish:^{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"search finished");
    });
}];

// To stop a running search:
[[RDExtendedSearch sharedInstance] clearSearch];

Extract the full text of a page

To get a page’s full text, call objsStart: and then read the range from 0 to objsCount. This is what the Cordova plugin’s extractTextFromPage: does on iOS. To extract a whole document, run the same calls in a loop on a background queue:

- (NSString *)textOfDocument:(RDPDFDoc *)doc
{
    NSMutableString *all = [NSMutableString string];
    int pageCount = [doc pageCount];
    for (int pageno = 0; pageno < pageCount; pageno++) {
        RDPDFPage *page = [doc page:pageno];
        [page objsStart:false];
        int count = [page objsCount];
        if (count > 0) {
            NSString *text = [page objsString:0 :count];
            if (text) [all appendFormat:@"%@\n", text];
        }
        page = nil;
    }
    return all;
}

Get match rectangles for highlighting

A match can span several characters and even wrap onto a second line. The viewer’s RDVFinder gets the box of each character with objsCharRect:: and merges characters that share a line into a single rectangle. You can do the same to draw your own overlays:

// One rectangle per line covered by the match, in PDF page coordinates.
static NSArray<NSValue *> *MatchRects(RDPDFPage *page, int first, int length)
{
    NSMutableArray<NSValue *> *rects = [NSMutableArray array];
    PDF_RECT word, r;
    [page objsCharRect:first :&word];
    for (int i = first + 1; i < first + length; i++) {
        [page objsCharRect:i :&r];
        float gap = (r.bottom - r.top) / 2;
        if (word.top == r.top && word.bottom == r.bottom &&
            word.right + gap > r.left && word.left - gap < r.right) {
            if (word.left > r.left) word.left = r.left;
            if (word.right < r.right) word.right = r.right;
        } else {
            [rects addObject:[NSValue valueWithBytes:&word objCType:@encode(PDF_RECT)]];
            word = r;
        }
    }
    [rects addObject:[NSValue valueWithBytes:&word objCType:@encode(PDF_RECT)]];
    return rects;
}

Call this right after find: while the page’s text objects are still loaded, with first = [finder objsIndex:i] and length = key.length. That is the same end the viewer uses. PDF coordinates have the y axis pointing up, so the viewer maps a rectangle’s bottom to the top of the on-screen box. If you place overlays yourself at a zoom factor scale, use x = rect.left * scale and y = ([doc pageHeight:pageno] - rect.bottom) * scale.

To make the highlight a permanent annotation in the file instead of a temporary overlay, call [page addAnnotMarkup:first :first + length - 1 :0 :0xFFFFFF00] after objsStart:. Type 0 is Highlight, and the color is the ARGB value the demo uses by default for highlights. Then save the document. The header says this needs a professional or premium license.

If you build your own viewer on the demo’s PDFLayoutView, you get on-screen highlighting without any extra code. vFindStart::: starts a search, vFind: moves to the next (1) or previous (-1) match and paints it, and vFindEnd clears the highlight. PDFReaderCtrl uses these calls internally.

Swift equivalent

The repositories ship Objective-C sources only. Once you add PDFObjc.h to your bridging header, Swift imports the unlabeled selectors with _ parameters, int as Int32 and unannotated object returns as optionals:

func search(_ doc: RDPDFDoc, key: String,
            completion: @escaping ([(page: Int32, char: Int32)]) -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {
        var hits: [(page: Int32, char: Int32)] = []
        for pageno in 0..<doc.pageCount() {
            guard let page = doc.page(pageno) else { break }
            page.objsStart(false)
            guard let finder = page.find(key, false, false) else { continue }
            for i in 0..<finder.count() {
                hits.append((page: pageno, char: finder.objsIndex(i)))
            }
        }
        DispatchQueue.main.async { completion(hits) }
    }
}

In Swift, check the result of find for nil with guard let. In Objective-C, sending count to nil simply returns 0.

Related questions

How do I make the search case-sensitive or whole-word only?

Pass true as the second or third argument of find:::, which are match_case and whole_word. In the demo viewer, these options come from GLOBAL.g_case_sensitive and GLOBAL.g_match_whole_word, and both RDExtendedSearch and PDFLayoutView read them.

Why does a phrase that wraps onto the next line not match?

find::: matches the characters exactly as they appear on the page, including the line break. Use find2:::: with skip_blanks set to true, which treats line breaks as blank characters.

Do I need to call objsStart before every find?

Call it once per RDPDFPage object, before find:, objsCount, objsString:: or objsCharRect::. The RDPDFFinder header notes that objsIndex: expects objsStart to have been called on the page.

Can I search a document that is open in PDFReaderCtrl?

Yes. Get the document with [reader getDoc] and run the background loop on it. To jump to a result, call [reader PDFGoto:pageno] with the 0-based page number.

Related on radaeepdf.com

Where to go next

How to open a PDF from a URL on iOS without downloading the whole file first

Streaming a PDF from a URL to an iOS app without a full download

To open PDF from URL on iOS without waiting for the whole file, RadaeePDF reads the remote document through a stream that downloads only the blocks the parser needs.

Applies to: RadaeePDF Classic and Master SDK for iOS. Both demo projects include PDFHttpStream in PDFViewer/PDFLib/ and use the same RDPDFDoc and PDFReaderCtrl selectors.

Short answer: Create a PDFHttpStream and call [stream open:url :cacheFile]. Then open an RDPDFDoc with [doc openStream:stream :password] and pass it to the demo viewer with [reader setDoc:doc :YES]. The stream downloads 4 KB (Classic) or 8 KB (Master) blocks with HTTP Range requests only when the parser reads them, so the first page can appear before the rest of the file arrives. To make this efficient, call [RDPDFDoc setOpenFlag:3] before opening a linearized PDF.

A note on the older KB sample

The KB article How to open pdf from url on iOS? passes the stream to RDPDFViewController with PDFOpenStream::. Neither that class nor that selector is in the current Classic or Master iOS demo projects. In the current sources, the document object opens the stream (-[RDPDFDoc openStream::]) and the viewer is PDFReaderCtrl, which you load from PDFReaderCtrl.storyboard and give the document with setDoc:. The RadaeePDF Cordova plugin follows exactly this path for http:// and https:// URLs.

How PDFHttpStream works

PDFHttpStream is an Objective-C class that implements the SDK’s PDFStream protocol (writeable, read::, write::, position, length, seek:). Its source ships with the demo, so you can read or adapt it. Here is what it does, based on PDFHttpStream.m:

  1. open:: starts a GET with NSURLSession and blocks the calling thread until the response headers arrive.
  2. If the server answers with a status of 400 or higher, or doesn’t send a usable Content-Length, open:: returns NO.
  3. Otherwise it creates the cache file at the path you passed and fills it with zeros up to the full document size.
  4. Each time the PDF parser calls read::, the stream checks which blocks are missing and downloads them with a Range: bytes=start-end request. It writes them into the cache file and marks them as present, so a block is never fetched twice while the stream is open.
  5. close, which dealloc also calls, cancels the network task, closes the cache file and deletes it with unlink.

This tells you what the server and your app need:

  • The server must support byte-range requests and return Content-Length. Most static file servers and CDNs do both.
  • HTTPS works without extra code. The stream uses the standard NSURLSession default configuration, and the demo header’s test URL (testUrlPath) is an https:// link. App Transport Security applies as it does to any other request.
  • The cache isn’t persistent. It lives only as long as the stream, and it takes the full file size on disk as soon as open:: succeeds. To keep a file for offline use, download it separately and open it with open::.
  • The stream is read-only. writeable returns false and write:: returns 0, so open the viewer in read-only mode.

Open PDF from URL on iOS (Classic and Master)

Because open:: blocks and the first openStream:: call reads over the network, do both on a background queue. Switch back to the main queue to show the viewer:

#import "PDFHttpStream.h"
#import "PDFReaderCtrl.h"

@interface RemoteViewer : UIViewController
@property (strong, nonatomic) PDFHttpStream *httpStream; // keep it alive while the document is open
@end

@implementation RemoteViewer

- (void)openRemotePDF:(NSString *)url password:(NSString *)password
{
    NSString *cacheFile = [NSTemporaryDirectory() stringByAppendingPathComponent:@"remote-cache.pdf"];

    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
        PDFHttpStream *stream = [[PDFHttpStream alloc] init];
        if (![stream open:url :cacheFile]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showError:@"Server unreachable, HTTP error, or no Content-Length."];
            });
            return;
        }

        [RDPDFDoc setOpenFlag:3];          // load linearized hint table (bit 1) + same page size (bit 2)
        RDPDFDoc *doc = [[RDPDFDoc alloc] init];
        int err = [doc openStream:stream :password];
        int linearized = (err == err_ok) ? [doc getLinearizedStatus] : 0;

        dispatch_async(dispatch_get_main_queue(), ^{
            switch (err) {
                case err_ok: {
                    NSLog(@"linearized status: %d", linearized);
                    self.httpStream = stream;
                    PDFReaderCtrl *reader = [[UIStoryboard storyboardWithName:@"PDFReaderCtrl" bundle:nil]
                                             instantiateViewControllerWithIdentifier:@"rdpdfreader"];
                    [reader setDoc:doc :YES];   // read-only: PDFHttpStream is not writeable
                    [self presentViewController:reader animated:YES completion:nil];
                    break;
                }
                case err_password: [self showError:@"Password required."]; break;
                case err_encrypt:  [self showError:@"Unknown encryption."]; break;
                case err_bad_file: [self showError:@"Damaged or invalid PDF."]; break;
                default:           [self showError:@"Cannot open the document."]; break;
            }
        });
    });
}

- (void)showError:(NSString *)msg
{
    UIAlertController *a = [UIAlertController alertControllerWithTitle:@"Error" message:msg
                                                        preferredStyle:UIAlertControllerStyleAlert];
    [a addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:a animated:YES completion:nil];
}

@end

openStream:: returns a PDF_ERR value: err_ok, err_open, err_password, err_encrypt or err_bad_file. The demo’s PDFNavCtrl checks the same values when it opens local files. Pass nil as the password for unprotected files. Store the stream in a property, because releasing it runs close, which stops downloads and deletes the cache file. If you open more than one remote file at a time, give each stream its own cache path.

In the Master edition, PDFHttpStream.h imports the bundled ASIHttpRequest headers. Copy that folder along with PDFLib if you move the class into your own project.

Linearization and setOpenFlag

A linearized (“fast web view”) PDF stores the first page and a hint table at the start of the file, so a reader can show page one after downloading only the beginning. RadaeePDF uses the hint table only when you ask for it. +[RDPDFDoc setOpenFlag:] is a static, global setting that affects every subsequent open call:

  • flag & 1 loads the linearized hint table.
  • flag & 2 treats all pages as the same size as the first page, so the SDK reads only the first page object when it opens the document. This bit has an effect only when bit 1 is also set.

The Cordova plugin calls [RDPDFDoc setOpenFlag:3] before openStream::. Use bit 2 only when you know the pages share one size, because otherwise the viewer lays out every page at the first page’s size. Since the flag is global, set it again before you open other documents that need different behavior. The C-level equivalents are Document_setOpenFlag in Classic (PDFIOS.h) and PDF_Document_setOpenFlag in Master (RDPDF.h).

After opening, -[RDPDFDoc getLinearizedStatus] returns one of these values:

  • 0: no linearized header was loaded. You also get this when the open flag is 0.
  • 1: a header is present, but its entry check failed.
  • 2: the header is valid, but the hint table is damaged.
  • 3: the linearized header loaded successfully.

If you get 0 or 1 for a file you serve often, linearize it on the server. Otherwise the parser has to fetch the cross-reference data at the end of the file before it can render anything.

App Transport Security

Serve your PDFs over HTTPS and you don’t need to change anything. If you must load plain HTTP from your own host, add an exception for that domain instead of disabling ATS globally:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>files.example.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

The KB article suggests NSAllowsArbitraryLoads, which works but turns off ATS for every connection your app makes.

Related questions

Why does open:: return NO for a URL that works in Safari?

open:: needs a response with status below 400 and a positive expectedContentLength. Servers that stream with chunked encoding, or that send an HTML login page or a redirect to one, fail this check. Make sure the URL returns the PDF bytes directly with a Content-Length header.

Is the cache file reused the next time the app starts?

No. The stream creates it fresh in open:: and deletes it in close. If users need offline access, download the file with NSURLSession into your app’s Documents or Caches directory and open the local copy with [doc open:path :password].

Can users add annotations to a streamed document?

Not through PDFHttpStream, because it reports writeable as false and ignores writes. That’s why the example opens the viewer with setDoc:doc :YES. To edit, download the file first, or write your own PDFStream implementation that supports writing.

Can I open a PDF already held in memory instead?

Yes. -[RDPDFDoc openMem:::] takes a byte buffer, its length and a password. The buffer must stay allocated until the document is closed, and the KB notes that a document opened this way is read-only.

Related on radaeepdf.com

Where to go next

How to export and import PDF annotations between devices on iOS

Syncing PDF annotations between devices with XFDF

There are two ways to export PDF annotations on iOS with RadaeePDF and import them on another page or device: one annotation at a time, or the whole document as XFDF.

Applies to: Per-annotation export and import work in the RadaeePDF Classic and Master SDK for iOS. Document-level XFDF works only in the Master SDK for iOS. Both editions declare these selectors in PDFViewer/PDFLib/PDFObjc.h.

Short answer: You can serialize annotations at two levels:

  • One annotation at a time (Classic and Master): call -[RDPDFAnnot export::] to write the annotation into a byte buffer, save its rectangle with getRect:, and recreate it on any page with -[RDPDFPage importAnnot:::].
  • Every annotation in the document (Master only): call -[RDPDFDoc exportXFDF:] to get a single XML string, and apply it on another device with -[RDPDFDoc importXFDF:].

In both cases, your app sends the data over the network, and the SDK only does the serialization. Then save the target document.

Two ways to export PDF annotations on iOS

  • Per-annotation buffers are a compact binary format that only RadaeePDF can read. Use them to copy an annotation between pages or documents, or to sync single annotations as users create them. The headers say you need a premium license for both export:: and importAnnot:::.
  • XFDF is the standard XML format for PDF annotations. A single string holds the whole annotation set, so it suits backend storage and exchange with other tools. In the iOS headers, only the Master edition’s RDPDFDoc declares exportXFDF: and importXFDF:. These two methods wrap the C functions PDF_Document_exportXFDF and PDF_Document_importXFDF in RDPDF.h.

Export and import a single annotation (Classic and Master)

This follows the KB sample How to Export/Import annotations? (iOS). The KB uses the older PDFPage and PDFAnnot names and an argument-less objsStart. The current headers use RDPDFPage, RDPDFAnnot and objsStart:(bool). According to the KB, this works for ink, line, rectangle, ellipse and note annotations.

Export to a transferable payload

#import "PDFObjc.h"

// Serialize one annotation into a JSON-friendly dictionary.
- (NSDictionary *)exportAnnotAtIndex:(int)index page:(int)pageno doc:(RDPDFDoc *)doc
{
    RDPDFPage *page = [doc page:pageno];
    [page objsStart:false];                       // annotAtIndex: needs objsStart or a render
    if (index < 0 || index >= [page annotCount]) return nil;

    RDPDFAnnot *annot = [page annotAtIndex:index];
    PDF_RECT rect;
    [annot getRect:&rect];                        // position in PDF page coordinates

    unsigned char buf[4096];                      // size it for your densest ink strokes
    if ([annot export:buf :sizeof(buf)] < 0) {
        return nil;                               // -1 means the export failed
    }
    NSData *data = [NSData dataWithBytes:buf length:sizeof(buf)];
    return @{ @"page":   @(pageno),
              @"rect":   @[ @(rect.left), @(rect.top), @(rect.right), @(rect.bottom) ],
              @"data":   [data base64EncodedStringWithOptions:0] };
}

The header documents only that export:: returns -1 on failure. It doesn’t say the return value is a byte count. To stay on the safe side, the code sends the whole buffer, as the KB sample does. Choose a buffer size large enough for your annotations, as the KB suggests.

Import on another page or device

- (BOOL)importAnnot:(NSDictionary *)payload intoDoc:(RDPDFDoc *)doc
{
    int pageno = [payload[@"page"] intValue];
    NSArray<NSNumber *> *r = payload[@"rect"];
    NSData *data = [[NSData alloc] initWithBase64EncodedString:payload[@"data"] options:0];
    if (!data || r.count != 4) return NO;

    PDF_RECT rect;
    rect.left   = r[0].floatValue;
    rect.top    = r[1].floatValue;
    rect.right  = r[2].floatValue;
    rect.bottom = r[3].floatValue;

    RDPDFPage *page = [doc page:pageno];
    if (![page importAnnot:&rect :(const unsigned char *)data.bytes :(int)data.length]) {
        return NO;
    }
    return [doc save];                             // persist into the PDF file
}

importAnnot::: places the annotation at the rectangle you pass. To duplicate an annotation at another spot, change the rectangle. To send every annotation on a page, loop from 0 to annotCount - 1 and export each one.

Export and import all annotations as XFDF (Master only)

#import "PDFObjc.h"   // Master edition

// Device A: export
NSString *xfdf = [doc exportXFDF:nil];   // href: reference to the source PDF file, may be nil
if (xfdf.length == 0) {
    NSLog(@"XFDF export failed");
}

// Device B: import into the same PDF, then save
RDPDFDoc *target = [[RDPDFDoc alloc] init];
if ([target open:localPath :nil] == err_ok && [target canSave]) {
    if ([target importXFDF:xfdf]) {
        [target save];
    }
}

exportXFDF: returns an XML string with an encoding header, as the XFDF format defines. importXFDF: expects that same kind of string and returns true or false. The href argument becomes the reference to the source PDF inside the XFDF. Pass your file name or document ID if your backend needs one, or nil.

The header doesn’t say whether importXFDF: replaces annotations that are already on the page or adds to them. If you keep the full annotation set on the server, import it into a clean copy of the original PDF so the same annotation is never applied twice.

Sending the payload to your backend

The SDK has no networking layer. Use NSURLSession or any client you already have:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.example.com/docs/42/annotations"]];
req.HTTPMethod = @"PUT";
[req setValue:@"application/vnd.adobe.xfdf" forHTTPHeaderField:@"Content-Type"];
NSData *body = [xfdf dataUsingEncoding:NSUTF8StringEncoding];

[[[NSURLSession sharedSession] uploadTaskWithRequest:req fromData:body
    completionHandler:^(NSData *resp, NSURLResponse *response, NSError *error) {
        if (error) NSLog(@"upload failed: %@", error);
    }] resume];

For per-annotation sync, send the dictionary from exportAnnotAtIndex:page:doc: as JSON with NSJSONSerialization. Load annotations on the receiving device before you call setDoc: on PDFReaderCtrl. That way the viewer renders the merged result from the first frame.

Things to check

  • Licensing. The headers say you need a premium license for export::, importAnnot::: and flatAnnots. save always returns false with no license or a standard license.
  • The document must be writable. Check [doc canSave] before importing. A document opened from memory (KB 82) or through the read-only PDFHttpStream can’t be saved.
  • Coordinates are page-relative. Both approaches store positions in PDF page coordinates. Import into the same PDF, or at least into pages of the same size, or the annotations end up in the wrong place.
  • Keep the Master library current for XFDF. The Master iOS release notes list several XFDF fixes: v1.3.9 (“Fix issue with exporting/importing XFDF data”), v1.3.10 (“Fix coordinate error while importing XFDF data for some documents”) and v1.3.11 (“Fix XFDF data importing issue”). v1.3.12 also fixes ink annotations that could be lost in some documents. If imported annotations shift or go missing, update the library before you debug your own code.

XFDF in other RadaeePDF editions

XFDF is a Master-level feature across the product line. The same ExportXFDF and ImportXFDF pair is declared in the Master Android Document.java, in the Master Windows (UWP) UWPPDF.h and in the Java binding of RadaeePDF Server. An XFDF string exported on iOS can therefore be imported by an Android app or a server-side job built on those editions, and the other way around. The Classic iOS header doesn’t declare these methods.

Related questions

How do I make imported annotations permanent?

Call [page flatAnnots] on each page. It removes the annotations and draws them as normal page content that users can’t edit. PDFReaderCtrl also offers flatAnnots and +flatAnnotAtPage:doc:. KB 80 notes that you need a premium license.

Can I export only ink annotations?

Yes, with the per-annotation API. Loop over annotCount, check each RDPDFAnnot with its type method, and export only the types you want. XFDF export always covers the whole document.

Does XFDF include form field values?

The headers describe exportXFDF: only as an annotation export. For form data, RDPDFDoc has a separate exportForm method that returns an XML string. The header says it needs a premium license.

Can I use this from Swift?

Yes, through a bridging header that imports PDFObjc.h. The unlabeled selectors come into Swift with _ parameters. For example, doc.exportXFDF(nil), doc.importXFDF(xfdf) and page.importAnnot(&rect, bytes, len).

Related on radaeepdf.com

Where to go next