Reputation: 2684
I have a Xamarin WindowsRT project where I am able to load a local PDF and view it within the WebView of the app using PDF.js.
I have created a custom renderer to override the Xamarin WebView and I simply call:
Control.Source = new Uri("ms-appx-web:///Assets/pdf/pdfjs/web/viewer.html?file=mypdf.pdf");
And this works great for opening and viewing the PDF.
The thing is, the PDFs I will need to view are in the form of base64 encoded strings downloaded from a server. Is there a way to pass the base64 to PDF.js somehow?
Update:
Just to see if I can get this working using javascript, I am loading a basic html page into the webview with the following script, but I just get a blank page:
<script>
var pdfAsArray = convertDataURIToBinary('data:application/pdf;base64,JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwogIC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAvTWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0KPj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAgL1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9udAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2JqCgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJUCjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVuZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4gCjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAwMDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9vdCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');
PDFJS.getDocument(pdfAsArray);
</script>
I know the html page is loading because above the script i put TEST and that renders. And it is executing the javascript. It is also properly creating the pdfAsArray, because I also iterated through it and it has a lot of values.
Upvotes: 2
Views: 2238
Reputation: 4995
Fetch your pdf string using C# and then inject it as a variable in your WebView
in order to pass it (since you're using Xamarin.Forms, you can use HybridWebView's InjectJavaScript)
Then, use the function from this gist to convert that string into an array that can be accepted by pdf.js, as pointed in this answer.
var pdfAsDataUri = //Your string;
var pdfAsArray = convertDataURIToBinary(pdfAsDataUri);
PDFJS.getDocument(pdfAsArray)
You can also create a function that wraps the conversion and the PDFJS.getDocument
and call it directly from C#:
//JS
function loadPdfFromBase64(pdfString) {
var pdfAsArray = convertDataURIToBinary(pdfString);
PDFJS.getDocument(pdfAsArray)
}
//C#
hybridWebView.CallJsFunction("loadPdfFromBase64", yourPdfString);
Upvotes: 1