display pdf with the returned data - not iframe - by using ajax call - JQuery












1















This question is not answering my situation as it is not providing a solution, and I am wondering if now (by 2018) we have a better approach.



So the problem is I would like to call my server which is creating pdf file (not physically) and giving the contents of the file as stream to the http response. Now, with an ajax call to this web service, I want to display the returned data as a pdf file if possible.



function callProducePdf(webServiceUrl, resultAreaId){
var jqxhr = $.ajax({
type:"GET",
url: webServiceUrl
});

jqxhr.done(function(data){
//data contains the pdf in inputStream form
//how can I display the pdf in resultAreaId which is a div?

//if I do something like this it works but this is not what I want
var iframe = $('<iframe height="500px">');
iframe.attr('src', webServiceUrl);
resultAreaId.prepend(iframe, "<br>");
});

jqxhr.fail(function(){
//I have this function defined which is working fine
appendError(resultAreaId);
});
}


server side code:



@GetMapping("/producePdfWithDefault")
public ModelAndView producePdfWithDefault(HttpServletRequest request, HttpServletResponse response) {
Resource resource = new ClassPathResource("/path/a/static/pdf/file.pdf");
InputStream resourceAsStream;
try {
resourceAsStream = resource.getInputStream();
byte resourceInBytes = Base64.encodeBase64(IOUtils.toByteArray(resourceAsStream));
response.reset();
response.setContentType("application/pdf");
response.setHeader("content-disposition","inline; filename=documentPreview.pdf");
response.setContentLength(resourceInBytes.length);
OutputStream output = response.getOutputStream();
output.write(resourceInBytes);
output.flush();
output.close();
} catch (IOException e) {
response.setStatus(500);
}
return null;
}


Any help is much appreciated. Thank you..










share|improve this question

























  • if return data is byte array. browser will download that data into pdf format.

    – Negi Rox
    Nov 20 '18 at 13:35











  • I can convert it to byteArray on the server side. let me try it.

    – sticky_elbows
    Nov 20 '18 at 13:36











  • @NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

    – sticky_elbows
    Nov 20 '18 at 13:50











  • no i am talking about your response is it byteArray?

    – Negi Rox
    Nov 20 '18 at 13:53













  • @NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

    – sticky_elbows
    Nov 20 '18 at 14:00
















1















This question is not answering my situation as it is not providing a solution, and I am wondering if now (by 2018) we have a better approach.



So the problem is I would like to call my server which is creating pdf file (not physically) and giving the contents of the file as stream to the http response. Now, with an ajax call to this web service, I want to display the returned data as a pdf file if possible.



function callProducePdf(webServiceUrl, resultAreaId){
var jqxhr = $.ajax({
type:"GET",
url: webServiceUrl
});

jqxhr.done(function(data){
//data contains the pdf in inputStream form
//how can I display the pdf in resultAreaId which is a div?

//if I do something like this it works but this is not what I want
var iframe = $('<iframe height="500px">');
iframe.attr('src', webServiceUrl);
resultAreaId.prepend(iframe, "<br>");
});

jqxhr.fail(function(){
//I have this function defined which is working fine
appendError(resultAreaId);
});
}


server side code:



@GetMapping("/producePdfWithDefault")
public ModelAndView producePdfWithDefault(HttpServletRequest request, HttpServletResponse response) {
Resource resource = new ClassPathResource("/path/a/static/pdf/file.pdf");
InputStream resourceAsStream;
try {
resourceAsStream = resource.getInputStream();
byte resourceInBytes = Base64.encodeBase64(IOUtils.toByteArray(resourceAsStream));
response.reset();
response.setContentType("application/pdf");
response.setHeader("content-disposition","inline; filename=documentPreview.pdf");
response.setContentLength(resourceInBytes.length);
OutputStream output = response.getOutputStream();
output.write(resourceInBytes);
output.flush();
output.close();
} catch (IOException e) {
response.setStatus(500);
}
return null;
}


Any help is much appreciated. Thank you..










share|improve this question

























  • if return data is byte array. browser will download that data into pdf format.

    – Negi Rox
    Nov 20 '18 at 13:35











  • I can convert it to byteArray on the server side. let me try it.

    – sticky_elbows
    Nov 20 '18 at 13:36











  • @NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

    – sticky_elbows
    Nov 20 '18 at 13:50











  • no i am talking about your response is it byteArray?

    – Negi Rox
    Nov 20 '18 at 13:53













  • @NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

    – sticky_elbows
    Nov 20 '18 at 14:00














1












1








1


1






This question is not answering my situation as it is not providing a solution, and I am wondering if now (by 2018) we have a better approach.



So the problem is I would like to call my server which is creating pdf file (not physically) and giving the contents of the file as stream to the http response. Now, with an ajax call to this web service, I want to display the returned data as a pdf file if possible.



function callProducePdf(webServiceUrl, resultAreaId){
var jqxhr = $.ajax({
type:"GET",
url: webServiceUrl
});

jqxhr.done(function(data){
//data contains the pdf in inputStream form
//how can I display the pdf in resultAreaId which is a div?

//if I do something like this it works but this is not what I want
var iframe = $('<iframe height="500px">');
iframe.attr('src', webServiceUrl);
resultAreaId.prepend(iframe, "<br>");
});

jqxhr.fail(function(){
//I have this function defined which is working fine
appendError(resultAreaId);
});
}


server side code:



@GetMapping("/producePdfWithDefault")
public ModelAndView producePdfWithDefault(HttpServletRequest request, HttpServletResponse response) {
Resource resource = new ClassPathResource("/path/a/static/pdf/file.pdf");
InputStream resourceAsStream;
try {
resourceAsStream = resource.getInputStream();
byte resourceInBytes = Base64.encodeBase64(IOUtils.toByteArray(resourceAsStream));
response.reset();
response.setContentType("application/pdf");
response.setHeader("content-disposition","inline; filename=documentPreview.pdf");
response.setContentLength(resourceInBytes.length);
OutputStream output = response.getOutputStream();
output.write(resourceInBytes);
output.flush();
output.close();
} catch (IOException e) {
response.setStatus(500);
}
return null;
}


Any help is much appreciated. Thank you..










share|improve this question
















This question is not answering my situation as it is not providing a solution, and I am wondering if now (by 2018) we have a better approach.



So the problem is I would like to call my server which is creating pdf file (not physically) and giving the contents of the file as stream to the http response. Now, with an ajax call to this web service, I want to display the returned data as a pdf file if possible.



function callProducePdf(webServiceUrl, resultAreaId){
var jqxhr = $.ajax({
type:"GET",
url: webServiceUrl
});

jqxhr.done(function(data){
//data contains the pdf in inputStream form
//how can I display the pdf in resultAreaId which is a div?

//if I do something like this it works but this is not what I want
var iframe = $('<iframe height="500px">');
iframe.attr('src', webServiceUrl);
resultAreaId.prepend(iframe, "<br>");
});

jqxhr.fail(function(){
//I have this function defined which is working fine
appendError(resultAreaId);
});
}


server side code:



@GetMapping("/producePdfWithDefault")
public ModelAndView producePdfWithDefault(HttpServletRequest request, HttpServletResponse response) {
Resource resource = new ClassPathResource("/path/a/static/pdf/file.pdf");
InputStream resourceAsStream;
try {
resourceAsStream = resource.getInputStream();
byte resourceInBytes = Base64.encodeBase64(IOUtils.toByteArray(resourceAsStream));
response.reset();
response.setContentType("application/pdf");
response.setHeader("content-disposition","inline; filename=documentPreview.pdf");
response.setContentLength(resourceInBytes.length);
OutputStream output = response.getOutputStream();
output.write(resourceInBytes);
output.flush();
output.close();
} catch (IOException e) {
response.setStatus(500);
}
return null;
}


Any help is much appreciated. Thank you..







javascript jquery ajax






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 '18 at 13:59







sticky_elbows

















asked Nov 20 '18 at 13:31









sticky_elbowssticky_elbows

35710




35710













  • if return data is byte array. browser will download that data into pdf format.

    – Negi Rox
    Nov 20 '18 at 13:35











  • I can convert it to byteArray on the server side. let me try it.

    – sticky_elbows
    Nov 20 '18 at 13:36











  • @NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

    – sticky_elbows
    Nov 20 '18 at 13:50











  • no i am talking about your response is it byteArray?

    – Negi Rox
    Nov 20 '18 at 13:53













  • @NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

    – sticky_elbows
    Nov 20 '18 at 14:00



















  • if return data is byte array. browser will download that data into pdf format.

    – Negi Rox
    Nov 20 '18 at 13:35











  • I can convert it to byteArray on the server side. let me try it.

    – sticky_elbows
    Nov 20 '18 at 13:36











  • @NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

    – sticky_elbows
    Nov 20 '18 at 13:50











  • no i am talking about your response is it byteArray?

    – Negi Rox
    Nov 20 '18 at 13:53













  • @NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

    – sticky_elbows
    Nov 20 '18 at 14:00

















if return data is byte array. browser will download that data into pdf format.

– Negi Rox
Nov 20 '18 at 13:35





if return data is byte array. browser will download that data into pdf format.

– Negi Rox
Nov 20 '18 at 13:35













I can convert it to byteArray on the server side. let me try it.

– sticky_elbows
Nov 20 '18 at 13:36





I can convert it to byteArray on the server side. let me try it.

– sticky_elbows
Nov 20 '18 at 13:36













@NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

– sticky_elbows
Nov 20 '18 at 13:50





@NegiRox unfortunately after converting the returned data to byte array, it displays the data as it is (byte array)

– sticky_elbows
Nov 20 '18 at 13:50













no i am talking about your response is it byteArray?

– Negi Rox
Nov 20 '18 at 13:53







no i am talking about your response is it byteArray?

– Negi Rox
Nov 20 '18 at 13:53















@NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

– sticky_elbows
Nov 20 '18 at 14:00





@NegiRox yea I converted the output to byte array on the server side, so the data I am getting with my ajax request is in byte array form. see the edited section of my question.

– sticky_elbows
Nov 20 '18 at 14:00












2 Answers
2






active

oldest

votes


















1














I would do something like this...



...
jqxhr.done(function(data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "<ANY_FILENAME_WITH_EXTENSION>";
link.click();
}),
...


(untested)



Client will download the file and open it in the default PDF reader.






share|improve this answer
























  • thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

    – sticky_elbows
    Nov 20 '18 at 14:26



















0














You can use PDF.js to render your PDF into a canvas element.



The demo below is from their examples






// atob() is used to convert base64 encoded PDF to binary-like data.
// (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
// Base64_encoding_and_decoding.)
var pdfData = atob(
'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];

// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

// Using DocumentInitParameters object to load binary data.
var loadingTask = pdfjsLib.getDocument({
data: pdfData
});
loadingTask.promise.then(function(pdf) {
console.log('PDF loaded');

// Fetch the first page
var pageNumber = 1;
pdf.getPage(pageNumber).then(function(page) {
console.log('Page loaded');

var scale = 1.5;
var viewport = page.getViewport(scale);

// Prepare canvas using PDF page dimensions
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;

// Render PDF page into canvas context
var renderContext = {
canvasContext: context,
viewport: viewport
};
var renderTask = page.render(renderContext);
renderTask.then(function() {
console.log('Page rendered');
});
});
}, function(reason) {
// PDF loading error
console.error(reason);
});

<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

<h1>PDF.js 'Hello, base64!' example</h1>

<canvas id="the-canvas"></canvas>








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394123%2fdisplay-pdf-with-the-returned-data-not-iframe-by-using-ajax-call-jquery%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I would do something like this...



    ...
    jqxhr.done(function(data) {
    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "<ANY_FILENAME_WITH_EXTENSION>";
    link.click();
    }),
    ...


    (untested)



    Client will download the file and open it in the default PDF reader.






    share|improve this answer
























    • thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

      – sticky_elbows
      Nov 20 '18 at 14:26
















    1














    I would do something like this...



    ...
    jqxhr.done(function(data) {
    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "<ANY_FILENAME_WITH_EXTENSION>";
    link.click();
    }),
    ...


    (untested)



    Client will download the file and open it in the default PDF reader.






    share|improve this answer
























    • thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

      – sticky_elbows
      Nov 20 '18 at 14:26














    1












    1








    1







    I would do something like this...



    ...
    jqxhr.done(function(data) {
    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "<ANY_FILENAME_WITH_EXTENSION>";
    link.click();
    }),
    ...


    (untested)



    Client will download the file and open it in the default PDF reader.






    share|improve this answer













    I would do something like this...



    ...
    jqxhr.done(function(data) {
    var blob = new Blob([data]);
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = "<ANY_FILENAME_WITH_EXTENSION>";
    link.click();
    }),
    ...


    (untested)



    Client will download the file and open it in the default PDF reader.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Nov 20 '18 at 13:37









    MarcoSMarcoS

    9,5781765135




    9,5781765135













    • thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

      – sticky_elbows
      Nov 20 '18 at 14:26



















    • thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

      – sticky_elbows
      Nov 20 '18 at 14:26

















    thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

    – sticky_elbows
    Nov 20 '18 at 14:26





    thank you for the response, the requirement is to display the pdf on the page. The way my application works is, user starts a test with a given time intervals to see if the server is able to create and return the pdf files. The test keeps running until the user stops it. So as the test is running, after each call I need to display what is returned in the resultArea

    – sticky_elbows
    Nov 20 '18 at 14:26













    0














    You can use PDF.js to render your PDF into a canvas element.



    The demo below is from their examples






    // atob() is used to convert base64 encoded PDF to binary-like data.
    // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
    // Base64_encoding_and_decoding.)
    var pdfData = atob(
    'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
    'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
    'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
    'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
    'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
    'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
    'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
    'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
    'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
    'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
    'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
    'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
    'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

    // Loaded via <script> tag, create shortcut to access PDF.js exports.
    var pdfjsLib = window['pdfjs-dist/build/pdf'];

    // The workerSrc property shall be specified.
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

    // Using DocumentInitParameters object to load binary data.
    var loadingTask = pdfjsLib.getDocument({
    data: pdfData
    });
    loadingTask.promise.then(function(pdf) {
    console.log('PDF loaded');

    // Fetch the first page
    var pageNumber = 1;
    pdf.getPage(pageNumber).then(function(page) {
    console.log('Page loaded');

    var scale = 1.5;
    var viewport = page.getViewport(scale);

    // Prepare canvas using PDF page dimensions
    var canvas = document.getElementById('the-canvas');
    var context = canvas.getContext('2d');
    canvas.height = viewport.height;
    canvas.width = viewport.width;

    // Render PDF page into canvas context
    var renderContext = {
    canvasContext: context,
    viewport: viewport
    };
    var renderTask = page.render(renderContext);
    renderTask.then(function() {
    console.log('Page rendered');
    });
    });
    }, function(reason) {
    // PDF loading error
    console.error(reason);
    });

    <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

    <h1>PDF.js 'Hello, base64!' example</h1>

    <canvas id="the-canvas"></canvas>








    share|improve this answer




























      0














      You can use PDF.js to render your PDF into a canvas element.



      The demo below is from their examples






      // atob() is used to convert base64 encoded PDF to binary-like data.
      // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
      // Base64_encoding_and_decoding.)
      var pdfData = atob(
      'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
      'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
      'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
      'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
      'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
      'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
      'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
      'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
      'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
      'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
      'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
      'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
      'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

      // Loaded via <script> tag, create shortcut to access PDF.js exports.
      var pdfjsLib = window['pdfjs-dist/build/pdf'];

      // The workerSrc property shall be specified.
      pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

      // Using DocumentInitParameters object to load binary data.
      var loadingTask = pdfjsLib.getDocument({
      data: pdfData
      });
      loadingTask.promise.then(function(pdf) {
      console.log('PDF loaded');

      // Fetch the first page
      var pageNumber = 1;
      pdf.getPage(pageNumber).then(function(page) {
      console.log('Page loaded');

      var scale = 1.5;
      var viewport = page.getViewport(scale);

      // Prepare canvas using PDF page dimensions
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;

      // Render PDF page into canvas context
      var renderContext = {
      canvasContext: context,
      viewport: viewport
      };
      var renderTask = page.render(renderContext);
      renderTask.then(function() {
      console.log('Page rendered');
      });
      });
      }, function(reason) {
      // PDF loading error
      console.error(reason);
      });

      <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

      <h1>PDF.js 'Hello, base64!' example</h1>

      <canvas id="the-canvas"></canvas>








      share|improve this answer


























        0












        0








        0







        You can use PDF.js to render your PDF into a canvas element.



        The demo below is from their examples






        // atob() is used to convert base64 encoded PDF to binary-like data.
        // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
        // Base64_encoding_and_decoding.)
        var pdfData = atob(
        'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
        'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
        'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
        'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
        'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
        'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
        'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
        'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
        'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
        'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
        'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
        'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
        'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        var pdfjsLib = window['pdfjs-dist/build/pdf'];

        // The workerSrc property shall be specified.
        pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

        // Using DocumentInitParameters object to load binary data.
        var loadingTask = pdfjsLib.getDocument({
        data: pdfData
        });
        loadingTask.promise.then(function(pdf) {
        console.log('PDF loaded');

        // Fetch the first page
        var pageNumber = 1;
        pdf.getPage(pageNumber).then(function(page) {
        console.log('Page loaded');

        var scale = 1.5;
        var viewport = page.getViewport(scale);

        // Prepare canvas using PDF page dimensions
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render PDF page into canvas context
        var renderContext = {
        canvasContext: context,
        viewport: viewport
        };
        var renderTask = page.render(renderContext);
        renderTask.then(function() {
        console.log('Page rendered');
        });
        });
        }, function(reason) {
        // PDF loading error
        console.error(reason);
        });

        <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

        <h1>PDF.js 'Hello, base64!' example</h1>

        <canvas id="the-canvas"></canvas>








        share|improve this answer













        You can use PDF.js to render your PDF into a canvas element.



        The demo below is from their examples






        // atob() is used to convert base64 encoded PDF to binary-like data.
        // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
        // Base64_encoding_and_decoding.)
        var pdfData = atob(
        'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
        'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
        'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
        'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
        'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
        'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
        'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
        'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
        'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
        'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
        'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
        'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
        'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        var pdfjsLib = window['pdfjs-dist/build/pdf'];

        // The workerSrc property shall be specified.
        pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

        // Using DocumentInitParameters object to load binary data.
        var loadingTask = pdfjsLib.getDocument({
        data: pdfData
        });
        loadingTask.promise.then(function(pdf) {
        console.log('PDF loaded');

        // Fetch the first page
        var pageNumber = 1;
        pdf.getPage(pageNumber).then(function(page) {
        console.log('Page loaded');

        var scale = 1.5;
        var viewport = page.getViewport(scale);

        // Prepare canvas using PDF page dimensions
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render PDF page into canvas context
        var renderContext = {
        canvasContext: context,
        viewport: viewport
        };
        var renderTask = page.render(renderContext);
        renderTask.then(function() {
        console.log('Page rendered');
        });
        });
        }, function(reason) {
        // PDF loading error
        console.error(reason);
        });

        <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

        <h1>PDF.js 'Hello, base64!' example</h1>

        <canvas id="the-canvas"></canvas>








        // atob() is used to convert base64 encoded PDF to binary-like data.
        // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
        // Base64_encoding_and_decoding.)
        var pdfData = atob(
        'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
        'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
        'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
        'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
        'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
        'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
        'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
        'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
        'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
        'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
        'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
        'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
        'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        var pdfjsLib = window['pdfjs-dist/build/pdf'];

        // The workerSrc property shall be specified.
        pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

        // Using DocumentInitParameters object to load binary data.
        var loadingTask = pdfjsLib.getDocument({
        data: pdfData
        });
        loadingTask.promise.then(function(pdf) {
        console.log('PDF loaded');

        // Fetch the first page
        var pageNumber = 1;
        pdf.getPage(pageNumber).then(function(page) {
        console.log('Page loaded');

        var scale = 1.5;
        var viewport = page.getViewport(scale);

        // Prepare canvas using PDF page dimensions
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render PDF page into canvas context
        var renderContext = {
        canvasContext: context,
        viewport: viewport
        };
        var renderTask = page.render(renderContext);
        renderTask.then(function() {
        console.log('Page rendered');
        });
        });
        }, function(reason) {
        // PDF loading error
        console.error(reason);
        });

        <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

        <h1>PDF.js 'Hello, base64!' example</h1>

        <canvas id="the-canvas"></canvas>





        // atob() is used to convert base64 encoded PDF to binary-like data.
        // (See also https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/
        // Base64_encoding_and_decoding.)
        var pdfData = atob(
        'JVBERi0xLjcKCjEgMCBvYmogICUgZW50cnkgcG9pbnQKPDwKICAvVHlwZSAvQ2F0YWxvZwog' +
        'IC9QYWdlcyAyIDAgUgo+PgplbmRvYmoKCjIgMCBvYmoKPDwKICAvVHlwZSAvUGFnZXMKICAv' +
        'TWVkaWFCb3ggWyAwIDAgMjAwIDIwMCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0K' +
        'Pj4KZW5kb2JqCgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAg' +
        'L1Jlc291cmNlcyA8PAogICAgL0ZvbnQgPDwKICAgICAgL0YxIDQgMCBSIAogICAgPj4KICA+' +
        'PgogIC9Db250ZW50cyA1IDAgUgo+PgplbmRvYmoKCjQgMCBvYmoKPDwKICAvVHlwZSAvRm9u' +
        'dAogIC9TdWJ0eXBlIC9UeXBlMQogIC9CYXNlRm9udCAvVGltZXMtUm9tYW4KPj4KZW5kb2Jq' +
        'Cgo1IDAgb2JqICAlIHBhZ2UgY29udGVudAo8PAogIC9MZW5ndGggNDQKPj4Kc3RyZWFtCkJU' +
        'CjcwIDUwIFRECi9GMSAxMiBUZgooSGVsbG8sIHdvcmxkISkgVGoKRVQKZW5kc3RyZWFtCmVu' +
        'ZG9iagoKeHJlZgowIDYKMDAwMDAwMDAwMCA2NTUzNSBmIAowMDAwMDAwMDEwIDAwMDAwIG4g' +
        'CjAwMDAwMDAwNzkgMDAwMDAgbiAKMDAwMDAwMDE3MyAwMDAwMCBuIAowMDAwMDAwMzAxIDAw' +
        'MDAwIG4gCjAwMDAwMDAzODAgMDAwMDAgbiAKdHJhaWxlcgo8PAogIC9TaXplIDYKICAvUm9v' +
        'dCAxIDAgUgo+PgpzdGFydHhyZWYKNDkyCiUlRU9G');

        // Loaded via <script> tag, create shortcut to access PDF.js exports.
        var pdfjsLib = window['pdfjs-dist/build/pdf'];

        // The workerSrc property shall be specified.
        pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';

        // Using DocumentInitParameters object to load binary data.
        var loadingTask = pdfjsLib.getDocument({
        data: pdfData
        });
        loadingTask.promise.then(function(pdf) {
        console.log('PDF loaded');

        // Fetch the first page
        var pageNumber = 1;
        pdf.getPage(pageNumber).then(function(page) {
        console.log('Page loaded');

        var scale = 1.5;
        var viewport = page.getViewport(scale);

        // Prepare canvas using PDF page dimensions
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render PDF page into canvas context
        var renderContext = {
        canvasContext: context,
        viewport: viewport
        };
        var renderTask = page.render(renderContext);
        renderTask.then(function() {
        console.log('Page rendered');
        });
        });
        }, function(reason) {
        // PDF loading error
        console.error(reason);
        });

        <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>

        <h1>PDF.js 'Hello, base64!' example</h1>

        <canvas id="the-canvas"></canvas>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 '18 at 18:59









        darklightcodedarklightcode

        1,256109




        1,256109






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53394123%2fdisplay-pdf-with-the-returned-data-not-iframe-by-using-ajax-call-jquery%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)