How to embed the PDFjs into your C# Project

TL;DR

If you needed to add PDF support feature into your C# based project, then using the PDFium & PDFViewer will be the easiest approach. Just include the PDFium via nugget package. You can also find the PdfiumViewer is on the github(https://github.com/pvginkel/PdfiumViewer).

However, the wrapper control only provides basic features so that you might need to consider different solutions in case you required another features such as highlighting text, searching keyword(PdfiumViewer supports the search, but it only returns position information rather actually selecting searched keywords). That’s why I tried to embed the PDFjs into a C# project.

The overall process will be like this:

  1. Include the web browser control into the target project
  2. Download PDFjs and make the C# code locate it.
  3. Navigate the web browser control to the viewer.html which is located at ‘pdfjs-1.4.20-dist/web/viewer.html’
  4. [From C#] Convert the pdf file into base64 string. I did on purpose because the C# application currently I’m writing only handles the PDF as memory buffer. If you could refer to the target PDF as local file, then go with it.
  5. [From viewere.js] Add a helper function which decodes the base64 into an ArrayBuffer and call PDFViewerApplication.open with it.

Code#1. PDF file into base64 and pass it to webbrowser control

Code#2. Open PDFjs with viewer.js and base64 string

The complete example is https://github.com/heejune/WinForm-PDFjs

Got hints following:

http://stackoverflow.com/questions/21797299/convert-base64-string-to-arraybuffer

http://stackoverflow.com/questions/8219694/how-can-i-show-an-image-in-webbrowser-control-directly-from-memory

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s