Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PDFJS new promise approach password and progress callback #11420

Closed
eromano opened this issue Dec 20, 2019 · 2 comments
Closed

PDFJS new promise approach password and progress callback #11420

eromano opened this issue Dec 20, 2019 · 2 comments

Comments

@eromano
Copy link

eromano commented Dec 20, 2019

Attach (recommended) or Link to PDF file here:

Configuration:

  • Web browser and its version: chrome 78
  • Operating system and its version: N/A
  • PDF.js version: 2.3.200
  • Is a browser extension: no

Steps to reproduce the problem:

Hi I am trying to migrate this piece of code:

        const loadingTask = pdfjsLib.getDocument(pdfOptions);

        loadingTask.onPassword = (callback, reason) => {
        };

        loadingTask.onProgress = (progressData) => {
        };

        loadingTask.then((pdfDocument: PDFDocumentProxy) => {

        });

To the new promise logic without success

I tought looking to the @types/pdfjs-dist types

declare function getDocument(
    source: PDFSource,
    pdfDataRangeTransport?: PDFDataRangeTransport,
    passwordCallback?: (fn: (password: string) => void, reason: string) => string,
    progressCallback?: (progressData: PDFProgressData) => void
): PDFLoadingTask<PDFDocumentProxy>;

that this would have been ok:

      this.pdfDocument = await pdfjsLib.getDocument({
            source: pdfOptions,
            passwordCallback: onPassword,
            progressCallback: onProgress
        }).promise;

But it seems not and I didn't find any good example as well in the documentation or in the example app. Any help is appreciated

What went wrong?
The passwordCallback and progressCallback are not valid parameters infact I don't see them in the implementation.

Link to a viewer (if hosted on a site other than mozilla.github.io/pdf.js or as Firefox/Chrome extension):

@Snuffleupagus
Copy link
Collaborator

Snuffleupagus commented Dec 20, 2019

Hi I am trying to migrate this piece of code:

        const loadingTask = pdfjsLib.getDocument(pdfOptions);

        loadingTask.onPassword = (callback, reason) => {
        };

        loadingTask.onProgress = (progressData) => {
        };

        loadingTask.then((pdfDocument: PDFDocumentProxy) => {

        });

But, that's already almost the correct format. The only change necessary is that the last part needs to be loadingTask.promise.then((pdfDocument: PDFDocumentProxy) => { ... }); instead; please also refer to the documentation in

pdf.js/src/display/api.js

Lines 422 to 506 in 693240c

const PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() {
let nextDocumentId = 0;
/**
* The loading task controls the operations required to load a PDF document
* (such as network requests) and provides a way to listen for completion,
* after which individual pages can be rendered.
*/
class PDFDocumentLoadingTask {
constructor() {
this._capability = createPromiseCapability();
this._transport = null;
this._worker = null;
/**
* Unique document loading task id -- used in MessageHandlers.
* @type {string}
*/
this.docId = 'd' + (nextDocumentId++);
/**
* Shows if loading task is destroyed.
* @type {boolean}
*/
this.destroyed = false;
/**
* Callback to request a password if wrong or no password was provided.
* The callback receives two parameters: function that needs to be called
* with new password and reason (see {PasswordResponses}).
*/
this.onPassword = null;
/**
* Callback to be able to monitor the loading progress of the PDF file
* (necessary to implement e.g. a loading bar). The callback receives
* an {Object} with the properties: {number} loaded and {number} total.
*/
this.onProgress = null;
/**
* Callback to when unsupported feature is used. The callback receives
* an {UNSUPPORTED_FEATURES} argument.
*/
this.onUnsupportedFeature = null;
}
/**
* Promise for document loading task completion.
* @type {Promise}
*/
get promise() {
return this._capability.promise;
}
/**
* Aborts all network requests and destroys worker.
* @returns {Promise} A promise that is resolved after destruction activity
* is completed.
*/
destroy() {
this.destroyed = true;
const transportDestroyed = !this._transport ? Promise.resolve() :
this._transport.destroy();
return transportDestroyed.then(() => {
this._transport = null;
if (this._worker) {
this._worker.destroy();
this._worker = null;
}
});
}
/**
* Registers callbacks to indicate the document loading completion.
* @ignore
*/
then(onFulfilled, onRejected) {
throw new Error('Removed API method: ' +
'PDFDocumentLoadingTask.then, use the `promise` getter instead.');
}
}
return PDFDocumentLoadingTask;
})();

I tought looking to the @types/pdfjs-dist types
...

That was the old format, which was removed more than two years ago. Please note that the types you're referring to are maintained in a different project, and as such there's no guarantee that they're correct and/or up-to-date.

But it seems not and I didn't find any good example as well in the documentation or in the example app.

Please see e.g.

pdf.js/web/app.js

Lines 668 to 713 in 693240c

let loadingTask = getDocument(parameters);
this.pdfLoadingTask = loadingTask;
loadingTask.onPassword = (updateCallback, reason) => {
this.pdfLinkService.externalLinkEnabled = false;
this.passwordPrompt.setUpdateCallback(updateCallback, reason);
this.passwordPrompt.open();
};
loadingTask.onProgress = ({ loaded, total, }) => {
this.progress(loaded / total);
};
// Listen for unsupported features to trigger the fallback UI.
loadingTask.onUnsupportedFeature = this.fallback.bind(this);
return loadingTask.promise.then((pdfDocument) => {
this.load(pdfDocument);
}, (exception) => {
if (loadingTask !== this.pdfLoadingTask) {
return undefined; // Ignore errors for previously opened PDF files.
}
let message = exception && exception.message;
let loadingErrorMessage;
if (exception instanceof InvalidPDFException) {
// change error message also for other builds
loadingErrorMessage = this.l10n.get('invalid_file_error', null,
'Invalid or corrupted PDF file.');
} else if (exception instanceof MissingPDFException) {
// special message for missing PDF's
loadingErrorMessage = this.l10n.get('missing_file_error', null,
'Missing PDF file.');
} else if (exception instanceof UnexpectedResponseException) {
loadingErrorMessage = this.l10n.get('unexpected_response_error', null,
'Unexpected server response.');
} else {
loadingErrorMessage = this.l10n.get('loading_error', null,
'An error occurred while loading the PDF.');
}
return loadingErrorMessage.then((msg) => {
this.error(msg, { message, });
throw new Error(msg);
});
});

@eromano
Copy link
Author

eromano commented Dec 20, 2019

Ok thanks for the fast response

  const loadingTask = pdfjsLib.getDocument(pdfOptions);

        loadingTask.onPassword = (callback, reason) => {
        };

        loadingTask.onProgress = (progressData) => {
        };

        loadingTask.promise.then((pdfDocument) => {

        });

works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants