How to display a PDF in React Native

As I move up the learning curve on React Native, I thought it would helpful to share a few tips and tricks I’ve learned.  One of the more challenging things I’ve come across was how to show a PDF file in your app. I couldn’t find any tutorial to demonstrate how to do this across both iOS and Android, so I thought I would write my own:

iOS

This one is fairly easy. The WebView in iOS has native support for PDF rendering. It’s just a matter of tell it where to find your PDF:

render: function() {
  return <WebView source={{uri: 'Your.pdf'}}/>
}

The one trick part is that you need to include Your.pdf into your project in Xcode and make sure it’s added to your build target.

Just copying it into your React Native project folder isn’t enough. It has to be part of the Xcode project itself.

Android

This one took a bit more work to figure out.

It appears that Android did not provide a native PDF viewer until version 5.0 (Lollipop). To provide a solution with broader support for older Android devices, you will need to make use of three key techniques:

  1. Pull the PDF out of my APK bundle and store it in the files folder for your app. This Stack Overflow answer was very helpful in accomplishing this:

Android: How to copy files from ‘assets’ folder to sdcard?

I tweaked the code a bit so that the file wasn’t going to an sdcard but to your app’s files folder. Here’s what to add to your MainActivity.java file:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  AssetManager assetManager = getAssets();
  String[] files = null;

  try {
      files = assetManager.list("pdf");
  } catch (IOException e) {
      Log.e("tag", "Failed to get asset file list.", e);
  }

  if (files != null) for (String filename : files) {
      InputStream in = null;
      OutputStream out = null;

      try {
        in = assetManager.open("pdf/" + filename);

        File outFile = new File(getFilesDir(), filename);
        out = new FileOutputStream(outFile);
        copyFile(in, out);
        Log.e("tag", "Copy was a success: " + outFile.getPath());
      } catch(IOException e) {
        Log.e("tag", "Failed to copy asset file: " + "pdf/" + filename, e);
      }
      finally {
          if (in != null) {
              try {
                  in.close();
              } catch (IOException e) {
                  // NOOP
              }
          }
          if (out != null) {
              try {
                  out.close();
              } catch (IOException e) {
                  // NOOP
              }
          }
      }
  }
}

private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Make sure to place your PDF file in the assets/pdf folder under android/app/src/main

  1. Next you’ll be using the react-native-fs package to get the absolute URL to your PDF, which is now in the files folder:
    var RNFS = require('react-native-fs');
    var absolutePath = RNFS.DocumentDirectoryPath + '/Your.pdf';
    
  2. With all of this in place, use react-native-pdf-view to actually load and display the PDF:
    import PDFView from 'react-native-pdf-view';
    
    render: function() {
      var absolutePath = RNFS.DocumentDirectoryPath + '/Your.pdf';
    
      return <PDFView
        ref={(pdf)=>{this.pdfView = pdf;}}
        src={absolutePath}
        style={ActharStyles.fullCover} />
    }
    

Not exactly dirt simple, but it works well enough.

So there you go!  You can now display a PDF file in your React Native project on either iOS or Android. FYI, I also wrote this up as an answer to my own Stack Overflow question. If you have suggestions for how to improve the technique, you may want to post them there.

Posted in Mobile, Tips & Tricks

WWDC 2015 Predictions

We’re only a week away from WWDC, so it’s time to speculate on what we’ll see:

Apple Watch – This one is a no-brainer.  Expect the Apple Watch to be the star of WWDC 2015.  We already know that Apple will announce a native SDK for the watch, so expect to see a parade of featured partners showing off their native apps.  I suspect we’ll see a few new watch band announced during the keynote, and perhaps even a couple more Disney themed watch faces as well (Minnie?  Donald?).

Apple TV – Rumors about a new TVKit exploded across the blogosphere a few weeks back, so I expect that it will be one of the big announcements at WWDC.  Hopefully this will mean full-blown native TV apps and not just WebKit shells that just grab content from out on the Internet.

What I would really like to see is Apple make a major commitment to this platform, including:

  • A comprehensive offering for cable-cutters.  Something that addresses local news, live sports, all of the popular network shows and maybe even gives equal footing to new-media offerings like popular YouTube channels and video podcasts.
  • Gaming.  Apple has systematically put themselves in position to take on Sony, Microsoft and Nintendo (remember them?) in the console battle.  They’ve got robust development tools (Xcode), a distribution platform (the App Store), gaming frameworks (SpriteKit, SceneKit and Metal), hardware controller support (GameController Framework), a match-making service (Game Center) and tons of developers.  All they really need is access to your television and headset support.
  • New hardware.  Imagine a new box with an A8 processor and a half terabyte disc.  It’s got the app store, all your favorite movie, tv and streaming content, and a ton of games from all the big name publishers.  Sound compelling?  Well here’s how it could get better – Bluetooth game controllers.  Maybe not bundled with the box itself, but $30 or $40 extras.  Now you can play games with your iPhone as the controller if you wish – giving you all the touch and swipe gestures you’re already used to – or you can have the joystick and shoulder button gaming experience that hard-core gamers demand.  That’s an offering that I think millions of people would love.

Beats Music – Not exactly sure what to expect here, but probably something like a Spotify clone with Apple / Beats branding.  This is Apple hedging its bet.  You want to buy music?  We’ve got you covered. You just want to stream it?  We’ve got that too.

HomeKit – I wouldn’t be shocked if this one drops out of the keynote, but it’s been a year since it was originally announced without much in the way of progress.  It could be as simple as a bunch of partners showing off their gadgets with HomeKit support, or maybe there’s a hardware hub that ties everything together.  It might even be the new Apple TV box – further adding to it’s utility.

iOS 9 – This prediction is about a risky as saying that the sun will rise tomorrow.  I’m sure there will be one or two snazzy new features to keep us talking, but mostly I expect a few visual flourishes and a lot of bug fixes and performance improvements.

OS 10.11 – Second verse, same as the first.  As with iOS 9 I suspect this will be a lot of tweaks and adjustments (WiFi anyone?), but nothing too Earth-shattering in terms of features.  Just keep the motor running.

What don’t expect I to see?

iPad Pro – This is an intuition thing, but I just don’t see a larger iPad being released yet.  The Apple Watch is the bell of the ball right now.  I suspect that Apple will want to let it breathe a bit before introducing another new portable device.  If anything, they may do another hint but don’t reveal move like they did with new iPhone sizes last year – reveal iOS features that would be useful in a huge new iPad (side-by-side apps?), but not actually show off the physical hardware yet.

So there you go, my predictions for WWDC 2015.  Feel free to bookmark this page and tell me how foolish I was once the announcements have been made next week.  Regardless, it should be a lot of fun to watch!

Posted in Business, Mobile

FCC Gets Serious About Broadband Speeds

FCC changes broadband definition to 25 Mbps

The Federal Communications Commission on Thursday voted to change the definition of broadband to connection speeds of 25 megabits per second or higher, casting aside the previous standard of 4 megabits per second.

If speeds don’t reach the threshold, Internet providers cannot call the connection “broadband.”

Huge news from Washington. The US is currently 26th in consumer broadband speeds. Pretty shameful for the country that invented the Internet.

Let’s hope some public shaming from the FCC will push Internet Providers to step up their games.

Posted in Uncategorized

Apple Shows Its Metal

Inside Metal: How Apple plans to unlock the secret graphics performance of the A7 chip

Recall that when Apple first introduced the iPhone 5s’ advanced A7 chip, it was first greeted with media skepticism wondering if it was even “truly 64-bit,” followed by a communal (and wholly incorrect) story that suggested 64-bit mobile chips didn’t matter until devices had “4GB of addressable RAM,” and that, in the most extremely ignorant coverage, the A7 was “marketing fluff and won’t improve performance.”

We’re only just beginning to see the fruits of Apple’s purchase of P.A. Semi back in 2008. For $278 million (or 1/70th the price Facebook paid for WhatsApp), Apple was able to take control of its technological roadmap and ensure it would have the most power-efficient CPUs in the mobile industry.  With the help of Metal, they’ve now shown that the A7 might be the fastest GPU in the industry as well.

The A7 is both literally and figuratively a game changer.

Posted in Mobile

Frequency of Miracles

Miracles Over Time

Posted in Entertainment

Analyst Baffled by Quality

Mac sales success “defies the laws of economics”

The only explanation that we see is the now-mythical halo effect. […] we view the Mac’s success as the rare instance where sales increased in the face of rising prices.

That pull quote comes from “Digital Lifestyle Analyst” Charlie Wolf of Needham & Company. Let me propose a better one:

I don’t understand how making better quality, easier to use products results in higher sales.

How jackasses like this maintain employment is beyond me.

Posted in Business

Code Like A Champion Today

Code Like A Champion Today

Posted in Tips & Tricks

Samsung paying for favorable product reviews

Samsung payola in action

The close relationship between Android licensees like Samsung and journalists covering the consumer electronics industry has grown increasingly sketchy. During this year’s Consumer Electronics Show in Las Vegas, non [sic] other than the Associated Press inked a deal with Samsung that allowed the Korean conglomerate to tweet out sponsored messages as part of the official Associated Press news stream.

Sounds ethical…

CNET reportedly accepted funds from both Samsung and Microsoft to republish and promote positive reviews of their products, including a gushing CNET “editor’s choice” that called Samsung’s Galaxy S4 the “everything phone for (almost) everyone.”

Paying for good reviews is a hell of a lot easier than just making products consumers love.

Posted in Business, Mobile

The Origins of Apple’s Move From PowerPC to Intel

Fantastic story about how Apple’s switch from PowerPC to Intel began:

No one has ever reported that, for 18 months, Project Marklar existed only because a self-demoted engineer wanted his son Max to be able to live closer to Max’s grandparents.

Posted in Uncategorized

PC Makers are looking past Windows

Nearly All Of Microsoft’s PC Partners Now Offer Google Chromebooks

To recap, that’s Dell, HP, Acer, Samsung, Lenovo, Acer, and Toshiba selling Chromebooks with some vendors, like HP, offering multiple models.

Remember when Microsoft ruled the computer industry with an iron fist? Now they’re struggling just to remain relevant.

Posted in Business