I have a website made in asp.net mvc, in it I have to have a pdf viewer, I chose to choose the Mozilla one , but when viewing the pdf I get the following error:
Access to XMLHttpRequest at 'file:///C:Ruta/pdf/pdf_example4.pdf' from origin ' http://localhost:57130 ' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
I have looked at this solution, but it seems very specific to your problem, adding things to classes that I don't have.
The code I use to call the pdf is:
function cargarPdf(ruta) {
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = ruta;
// Loaded via <script> tag, create shortcut to access PDF.js exports.
var pdfjsLib = window['pdfjs-dist/build/pdf'];
//console.log(pdfjsLib);
// The workerSrc property shall be specified.
pdfjsLib.GlobalWorkerOptions.workerSrc = '../Public/js/PDFJS/pdf.worker.js';
var pdfDoc = null,
pageNum = 1,
pageRendering = false,
pageNumPending = null,
scale = 0.65,
canvas = document.getElementById('the-canvas'),
ctx = canvas.getContext('2d');
/**
* Get page info from document, resize canvas accordingly, and render page.
* param num Page number.
*/
function renderPage(num) {
pageRendering = true;
// Using promise to fetch the page
pdfDoc.getPage(num).then(function (page) {
var viewport = page.getViewport({ scale: scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
// Render PDF page into canvas context
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
var renderTask = page.render(renderContext);
// Wait for rendering to finish
renderTask.promise.then(function () {
pageRendering = false;
if (pageNumPending !== null) {
// New page rendering is pending
renderPage(pageNumPending);
pageNumPending = null;
}
});
});
// Update page counters
document.getElementById('page_num').textContent = num;
}
/**
* If another page rendering in progress, waits until the rendering is
* finised. Otherwise, executes rendering immediately.
*/
function queueRenderPage(num) {
if (pageRendering) {
pageNumPending = num;
} else {
renderPage(num);
}
}
/**
* Displays previous page.
*/
function onPrevPage() {
if (pageNum <= 1) {
return;
}
pageNum--;
queueRenderPage(pageNum);
}
document.getElementById('prev').addEventListener('click', onPrevPage);
/**
* Displays next page.
*/
function onNextPage() {
if (pageNum >= pdfDoc.numPages) {
return;
}
pageNum++;
queueRenderPage(pageNum);
}
document.getElementById('next').addEventListener('click', onNextPage);
/**
* Asynchronously downloads PDF.
*/
pdfjsLib.getDocument(url).promise.then(function (pdfDoc_) {
pdfDoc = pdfDoc_;
document.getElementById('page_count').textContent = pdfDoc.numPages;
// Initial/first page rendering
renderPage(pageNum);
});
}
When executing this code I get two errors:
ERROR 1 pdf.js:23842 Uncaught TypeError: Cannot read property 'xhr' of undefined at NetworkManager.getRequestXhr (pdf.js:23842) at PDFNetworkStreamFullRequestReader._onHeadersReceived (pdf.js:23969) at NetworkManager.onStateChange (pdf.js:23779 ) at NetworkManager.request (pdf.js:23751) at NetworkManager.requestFull (pdf.js:23707) at new PDFNetworkStreamFullRequestReader (pdf.js:23944) at PDFNetworkStream.getFullReader (pdf.js:23897) at WorkerTransport. (pdf.js:11495) at _callee$ (pdf.js:16870) at tryCatch (pdf.js:12428)
ERROR 2: pdf.js:24035 Uncaught TypeError: Cannot read property 'reject' of undefined at PDFNetworkStreamFullRequestReader._onError (pdf.js:24035) at XMLHttpRequest.xhr.onerror (pdf.js:23741) at NetworkManager.request (pdf. js:23751) at NetworkManager.requestFull (pdf.js:23707) at new PDFNetworkStreamFullRequestReader (pdf.js:23944) at PDFNetworkStream.getFullReader (pdf.js:23897) at WorkerTransport. (pdf.js:11495) at _callee$ (pdf.js:16870) at tryCatch (pdf.js:12428) at Generator.invoke [as _invoke] (pdf.js:12603)
If I pass a string as a parameter to the loadPdf function with the path written from the web, it does display the pdf, but when collecting the path from the database, the error pops up.
In principle, the same origin policy governs , in short, by default, resources cannot be shared between different origins. This policy has been in force since approximately 1995.
The Cross-Origin Resource Sharing (CORS) policy was born around 2004 to be able to securely share resources between different origins.
Doing an
XMLHttpRequest
(ajax) tofile://
violates both policies, even thoughlocalhost
theyfile
are the same machine, it is understood that they are different origins. A source is understood to be the scheme + host + port combination, rfc6454 .Let's imagine this case:
passwords.txt
on his desktop.file://usuarioA/escritorio/passwords.txt
and then another ajax sending the content to his server.To be able to access the pdf, or any other resource via XMLHttpRequest you have to take this into account:
They must be in the same origin (scheme + host + port) an exception would be
http
the resource is requiredhttps
but not the other way around. view Mixed Content or...If they are in different origins, CORS becomes relevant, where only GET, HEAD and POST are allowed and the schemes
http
andhttps
(with exceptions), in addition the server must respond with the Access-Control-Allow-Origin header explicitly accepting the server that makes the request.The error message:
Approximate translation:
That is, from a URL that begins with
http:
(which is common) you are trying to access a resource whose URL begins withfile:
, which is not on the list of allowed schemes.Actually the problem is more serious than that: the PDF file you are trying to access is searched on the client device, not on the server. It would only work if the server and client were always the same machine. You must serve the PDF file from the web server, via HTTP(S).