pdf.js rendering as PDF with base64 - pdf.js

I am stuck at last point of my application, i am supposed to display user form in PDF which works fine on desktop browsers as they has pdf viewer built in, but for Android / iOS its not working as pdf viewer is missing.
So i was trying to use PDF.js to display it, (to be honest, this is very widely used but documentation is lacking), only catch is i am getting data in base64 format. PDF.js has example on site which shows how to render the base64 data but its not PDF, for that displaying PDF as "PDF" i need to user their "viewer.html" but that does not take base64 data?
closest i have come to Pdf.js: rendering a pdf file using base64... on stack overflow, but i dont know how to use it after PDFJS.getDocument(pdfAsArray)?.
Other link that came across was other link
I dont want to rely on Google / Third party PDF viewer as i dont know how long they will support this.

There are no end-to-end answers on this topic in community so here is my attempt to put something here. (maybe it will help others)
Okay, PDF.js is one way of showing PDF in browser, specially when you don't want to rely on PDF plugin to be installed. In my case, my application generates report in PDF and that can be viewed before downloading but on handheld devices it was not working because of missing PDF viewer plugin.
In my case PDF was sent to browse in base64 string, that I can use to display PDF with <object src="base64-data"...></object>. This works like charm on Chrome / FF but switch to mobile view and it stops working.
<object type="application/pdf" id="pdfbin" width="100%" height="100%" title="Report.pdf">
<p class="text-center">Looks like there is no PDF viewer plugin installed, try one of the below approach...</p>
</object>
In above code it will try to show the PDF or fall back to <p> and show error message. And I Was planning to add the PDF viewer at this point, PDF.js was the choice but was not able to display it. One example on PDF.js with Base64 data shows how to do this but that renders it as an Image not PDF, and I was not able to find solution for that and hence the question, here is what I did,
First add the JavaScript code to convert base64 to array
convert to blob and use viewer.html file packaged with PDF.js to display it as PDF
In case if you are wondering why base64 data, then answer is simple I can create the PDF, read it, send the data to client and delete the file, I don't have to run any cleaner service/cron job to delete generated PDF files
Few Things To Note
Below code is using Flask + Jinja2, change the way base64 is read in html if you are using something else
viewer.html needs to be changed to have required js & css files in proper location (by default their location is relative; you need them to be referred from static folder)
viewer.js looks for pdf.worker.js in predefined location, change that in case its throwing error as above file not found.
viewer.js might throw file origin does not match viewer error in that case as a quick fix comment the code which throws this error and see if that solves the issue (look for that error in viewer.js)
I am not the author of below code, I have just put it together from different places.
Now to the code (so PDF will be displayed when user clicks on button with id="open_id")
Jquery
var pdfDataX = '{{ base64Pdf }}';
var BASE64_MARKER = ';base64,';
PDFJS.workerSrc = "{{ url_for('static', filename='js/pdf.worker.js') }}";
$('#open_id').click(function() {
PDFJS.disableWorker = true;
var pdfAsDataUri = "data:application/pdf;base64," + pdfDataX ;
PDFJS.workerSrc = "{{ url_for('static', filename='js/pdf.worker.js') }}";
// Try to show in the viewer.html
var blob = base64toBlob(pdfDataX, 'application/pdf');
var url = URL.createObjectURL(blob);
var viewerUrl = "{{ url_for('static', filename='viewer.html') }}" + '?file=' + encodeURIComponent(url);
$('#pdfViewer').attr('src', viewerUrl);
// Finish
var mdObj = $('#pdfbin');
mdObj.hide();
mdObj.attr('data', pdfAsDataUri);
mdObj.show();
$('#myModal').modal();
});
var base64toBlob = function(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i=0; i<slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {type: contentType});
return blob;
}
$('.save').click(function(e) {
e.preventDefault();
var blob = base64toBlob(pdfDataX, 'application/pdf');
saveAs(blob, 'abcd.pdf'); // requires https://github.com/eligrey/FileSaver.js/
return false;
});
HTML
<object type="application/pdf" id="pdfbin" width="100%" height="100%" title="Resume.pdf">
<p class="text-center">Looks like there is no PDF viewer plugin installed, try one of the below approach...</p>
<iframe id="pdfViewer" style="width: 100%; height: 100%;" allowfullscreen="" webkitallowfullscreen=""></iframe>
</object>
Hope this will be useful for others in future.

Related

iTextSharp returns a pdf that can not be opened

I have followed the answer in this question and tried to output a pdf from an MVC view with iTextSharp to test the rendering fidelity.
I have the following code:
var ms = new MemoryStream();
var document = new Document(PageSize.A4, 10, 10, 10, 10);
var writer = PdfWriter.GetInstance(document, ms);
document.Open();
var html = this.RenderView(GetViewName(), reportVM);
var css = System.IO.File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "\\Content\\site.css"));
var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(css));
var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html));
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, msHtml, msCss);
document.Close();
return File(ms, "application/pdf");
Unfortunately it returns a window in the browser with the message:
Failed to load PDF
What are the main causes of this behavior?
Note: I have produced a pdf from the same html with PdfSharp which is based on iTextSharp too, so I guess I am not using iTextSharp properly.
EDIT:
I have followed Bruno's suggestion in the comments, so I changed the return to :
bytes = ms.ToArray();
return File(new MemoryStream(bytes), "application/pdf");
And now the result is a 2 pages empty pdf, so it is better, but is it possible to make it more accurate, since the content of the pdf should have some text inside?
After I saw the answer in this question and removed the width tags inside divs, and also ran an online XHtml validator to adjust everything else, I was able to generate a pdf relatively according to the coresponding HTML.

No pdf generated

i use jsPDF and plugin jsPDF-AutoTable
I have a html table i want to print
$('#printFreeRoom').on('click', function (e) {
freeRoomAvailableReport($("#freeRoomTableResult"));
});
function freeRoomAvailableReport(tableId) {
var doc = new jsPDF('p', 'pt');
doc.text("From HTML", 40, 50);
var res = doc.autoTableHtmlToJson(tableId);
doc.autoTable(res.columns, res.data, {
startY: 60
});
doc.output('dataurlnewwindow');
doc.save('test.pdf');
}
nothing is generated when i click on the button.
I created a example on jsfiddle
http://jsfiddle.net/8da5e1fj/
seem like a chrome problem...
tried other example: http://jsfiddle.net/8tLt9yof/10/ and get same result.
You need to add FileSaver.js to use doc.save() also, Chrome has issues with doc.output('dataurlnewwindow')
Hence, here is a working fiddle for doc.save fiddle
And, to open the PDF in new window try this -
var blob = doc.output("blob");
window.open(URL.createObjectURL(blob));
Just an additional "Enter" on the browser address bar will show the PDF in chrome.
UPDATE
Longer URL's are not supported by Chrome as per this. Canvas in the fiddle is generating base64 URL which Chrome fails to load.

Google drive embed NO iframe

Is there any way to embed google drive video without using iframes?
Just like you can do with youtube video:
<object width="320" height="180">
<param name="movie" value="http://www.youtube.com/v/UHk6wFNDA5s&showinfo=0">
<param name="wmode" value="transparent">
<embed src="http://www.youtube.com/v/UHk6wFNDA5s&showinfo=0" type="application/x-shockwave-flash" wmode="transparent" width="320" height="180">
</object>
The suggested embed code from google docs (using iframe) is:
<iframe src="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview" width="640" height="385"></iframe>
It's possible but not officially supported.
After some study of the result generated by the iframe embed from Google Drive and the iframe from YouTube I've digged into the YouTube JS Player API and found out that it's possible using SWFObject embed
Here is the code that I use to add the player object:
function YT_createPlayer(divId, videoId) {
var params = {
allowScriptAccess: "always"
};
var atts = {
id: videoId
};
//Build the player URL SIMILAR to the one specified by the YouTube JS Player API
var videoURL = '';
videoURL += 'https://video.google.com/get_player?wmode=opaque&ps=docs&partnerid=30'; //Basic URL to the Player
videoURL += '&docid=' + videoId; //Specify the fileID ofthe file to show
videoURL += '&enablejsapi=1'; //Enable Youtube Js API to interact with the video editor
videoURL += '&playerapiid=' + videoId; //Give the video player the same name as the video for future reference
videoURL += '&cc_load_policy=0'; //No caption on this video (not supported for Google Drive Videos)
swfobject.embedSWF(videoURL,divId, widthVideo, heightVideo, "8", null, null, null, null);
}
You need to fetch the fileId from Google Drive some how (JS or server side, you can use a GAS Servlet if you want to host the site on Google Drive).
Most of the YouTube Player Parameters works, and events to control the playing status from JS are fired; so basically anything from the Youtube Documentation works.
Do you mean like this:
<object width="420" height="315" data="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview">
<embed width="420" height="315" src="https://docs.google.com/file/d/0B7CQ5XvLuIGrQlJUNUhpQVltZ0U/preview">
I have tested the code and it works.
I used the example code from W3Schools, but cannot paste the code here as it is their copyright, just follow the link to see it.
The second part is to get the link to the images correct. I found using the link directly from Drive didn't work, so I created a new page in my site and added all the images I wanted. I disabled the page from navigation so it wouldn't be found unless they use search. After publishing, I opened the page and used Inspect on the browser to find the tag for each image. I then copied the element which looked like this.
<img src="https://lh3.googleusercontent.com/qt ... 4jM=w1175" class="CENy8b" role="img" style="width: 100%; margin: 0%">
I added the title attribute to this, so it is possible to see which images are included. I also removed the class="CENy8b" attribute as it doesn't seem to be required.
<img src="https://lh3.googleusercontent.com/qt ... 4jM=w1175" role="img" style="width: 100%; margin: 0%" title = "image 1">
I then pasted this over the tag in the code from W3Schools, repeating for each of the images. The W3Schools code has a where they have dots under the images to show which image from the set is being displayed. The number of dots needs to match the number of images.
Having done all the above I copied the code from the editor and used Embed code on Sites to paste it in. You can see the images ticking over in the Sites editor and after publishing it works fine on the live page.
The W3Schools code uses a 2 s delay between images. It is fairly easy to find where this is set in the code to change it to an appropriate value for your site.

PhoneGap on iOS with absolute path URLs for assets?

Porting a web app to phoneGap on iOS, we have asset (and ajax) URLs that are absolute paths, e.g.:
<img src="/img/logo.png">
We have the img directory packaged under PhoneGap's www directory. The image will not load with the absolute path, but only with a relative path, e.g.:
<img src="img/logo.png">
Could someone please explain how the URL is being prefixed or translated in this context? I.e.:
<img src="/www/img/logo.png">
does not work either. So what is the URL base used by PhoneGap on iOS?
We've also tried, e.g.:
<img src="file://img/logo.png">
<img src="file:///img/logo.png">
but no go.
We would like to avoid changing the URLs to relative for the port, as absolute path URLs are used throughout the CSS, Ajax code, are set by Sprockets with the Rails backend, etc. How can we just get PhoneGap/UIWebView on iOS to load the assets using the absolute path URLs as written?
I see this question is asked a lot in various forms here on StackOverflow, but I've yet to see a correct answer.
One can get the path to the application in JavaScript by:
cordova.file.applicationDirectory
Since I'm on Android, it says: "file:///android_asset/" ...for example:
var img_path = cordova.file.applicationDirectory + 'www/img/logo.png';
Like this all resources would be found when cross-building for various platforms.
Did some testing and maybe a bit of JavaScript hackery can make it a bit more manageable. This will change all <a> and <img> tags with URL starting with / to be relative to the current file.
Put this into a file and include it with a <script> tag or inject it with stringByEvaluatingJavaScriptFromString:
document.addEventListener("DOMContentLoaded", function() {
var dummy = document.createElement("a");
dummy.setAttribute("href", ".");
var baseURL = dummy.href;
var absRE = /^\/(.*)$/;
var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
var groups = absRE.exec(img.getAttribute("src"));
if (groups == null) {
continue;
}
img.src = baseURL + groups[1];
}
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
var link = links[i];
var groups = absRE.exec(link.getAttribute("href"));
if (groups == null) {
continue;
}
link.href = baseURL + groups[1];
}
});
When checking the absolute path through your iPhone/iPad you would see something like this:
<img src="file:///var/mobile/Applications/7D6D107B-D9DC-479B-9E22-4847F0CA0C40/YourApplication.app/www/logo.png" />
And it will be different on Android or Windows devices so I don't think it's actually a good idea to reference assets using absolute paths in this case.
As an alternative you could consider using the base64 strings in your CSS files:
div#overview
{
background-image: url('data:image/jpeg;base64, <IMAGE_DATA>');
background-repeat: no-repeat;
}
In ionic 5 / angular 12 I have
this.file.applicationDirectory+'/www/assets/pdf/my.pdf'
and it works for my app with
https://ionicframework.com/docs/native/file
https://ionicframework.com/docs/native/document-viewer.

Show PDF in HTML in web

I'm using the object tag to render PDF in HTML, but I'm doing it in MVC like this:
<object data="/JDLCustomer/GetPDFData?projID=<%=ViewData["ProjectID"]%>&folder=<%=ViewData["Folder"] %>"
type="application/pdf" width="960" height="900">
</object>
and Controller/Action is
public void GetPDFData(string projID, Project_Thin.Folders folder)
{
Highmark.BLL.Models.Project proj = GetProject(projID);
List<File> ff = proj.GetFiles(folder, false);
if (ff != null && ff.Count > 0 && ff.Where(p => p.FileExtension == "pdf").Count() > 0)
{
ff = ff.Where(p => p.FileExtension == "pdf").ToList();
Response.ClearHeaders();
Highmark.BLL.PDF.JDLCustomerPDF pdfObj = new JDLCustomerPDF(ff, proj.SimpleDbID);
byte[] bArr = pdfObj.GetPDF(Response.OutputStream);
pdfObj = null;
Response.ContentType = "application/" + System.IO.Path.GetExtension("TakeOffPlans").Replace(".", "");
Response.AddHeader("Content-disposition", "attachment; filename=\"TakeOffPlans\"");
Response.BinaryWrite(bArr);
Response.Flush();
}
}
The problem is, as I'm downloading data first from server and then return the byte data, it is taking some time in downloading, so I want to show some kind of progress to show processing.
Please help me on this.
You may try the following (not tested under all browsers):
<div style="background: transparent url(progress.gif) no-repeat">
<object
data="<%= Url.Action("GetPDFData, new { projID = ViewData["ProjectID"], folder = ViewData["Folder"] }") %>"
type="application/pdf"
width="640"
height="480">
<param value="transparent" name="wmode"/>
</object>
</div>
Unfortunatly, there is no way (afaik) to interact with the Acrobat plugin and see when it's ready to display your PDF document.
There are components available that replace Acrobat and provide a proper Javascript interface.
I work for TallComponents on their PDFWebViewer.NET product which will display PDF without any plugins and works with ASP.NET MVC.
You do have some other options though. If you need the progress indicator because the PDF generation is taking longer than you would like you can poll the server for progress using AJAX calls.
On the server you would need to have some sort of progress information available that you can return as the result of the ajax call. In the browser you'd use the result to provide progress info to the user. There are several good examples available online (this blog for example). There are also other questions here on SO (for example here) with good pointers to more info.
If the generation process only takes a couple of seconds can you probably get way with showing a busy indicator. That could be as simple as showing a div in your page when you trigger the download from the server.
By the way, if I'm not mistaken you should replace the attachment keyword with inline in the Content-Disposition header. Setting that to attachment will cause the entire PDF to be downloaded before any content is displayed. If you set it to inline, Acrobat will start showing the first page as soon as it has downloaded enough data to do so.

Resources