Open PDFs in a converted iOS app

One of the apps I ported from iOS to Windows 10 using WinObjC was using the web view to open up pdf files that were deployed with the app. While this works fine in iOS it does not port well to Win10 since the Edge browser does not support (yet ?) opening up a PDF file directly.

I’ve thought of a few approaches like use another web browser component - Awesomium or render the PDF yourself using the Windows.Data.PDF classes, but these require extensive changes to your code base which is not something you want in this process.

However, I found a couple of solutions that worked out.

Solution 1: Convert the PDF to HTML

Depending on the complexity of the PDF or the requirement, you could simply convert the pdf to a HTML file.
The best tool I’ve found to achieve this is pdf2htmlex. The best thing about the tool is that it generates the HTML in one file (embedding the images as Base64 strings) so it’s super easy to just add that file and replace the PDF reference.

Solution 2: Change the code to open the PDF in the default PDF reader on the system

Sometimes the conversion will simply not work due to the formatting or layout of the PDF. In this case, the only viable solution is to change the original code to open the PDF in the native PDF reader application rather than in the web view.

Here’s how you would write this code in a regular UWP app:

1
2
3
var fileUri = new Uri("ms-appx:///mypdf.pdf");
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(fileUri);
await Launcher.LaunchFileAsync(storageFile);

But we need to write it all using ObjectiveC so here’s the final code that you can put in your iOS app to achieve the same functionality:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 #import <UWP/WindowsStorage.h>
#import <UWP/WindowsSystem.h>
---

//Open pdf the Windows way
WFUri* fileUri = [WFUri makeUri:@"ms-appx:///mypdf.pdf"];
[WSStorageFile getFileFromApplicationUriAsync:fileUri
success:^void(WSStorageFile* result) {
NSLog(@"Storage File retrieved");
[WSLauncher launchFileAsync:result
success:^void(BOOL result) {
NSLog(@"File opened");
}
failure:^(NSError* err) {
NSLog(@"Hit error %@ when attempting to launch pdf!", err);
}];
}
failure:^(NSError* err) {
NSLog(@"Hit error %@ when attempting to open pdf!", err);
}];
Share Comments