-
Hello ! I am trying to make a VSCode PDF viewer. I tried mupdf before PDFjs, but in both cases the problem is that you can't use module scripts in VSCode webviews. Because PDFjs is compiled to ESM (.mjs) I'm hurting a wall. Sorry if I mix up terms (ESM, modules, commonJS etc) i am not a js developer. I tried a simpler thing: update the most known vscode pdf viewer https://github.com/tomoki1207/vscode-pdfviewer from version 3.x to 3.11.174 without problems. Starting with PDFjs 4.x, the build script ( I tried to change the gulpfile to build back to commonjs, but some code wasn't compatible. Because I don't really know what I do, I prefered using a tool made by people that know what they do, so i used Babel to transpile ESM->commonJS. First I compile PDF.js from source (git cloned and compiled from master tbh):
Then babel:
{
"presets": [
[
"@babel/preset-env",
{
"modules": "commonjs"
}
]
]
} And it kinda worked because all the .mjs are now regular .js. Then I port the vscode viewer to 5.3.31 (this is basically 1. remove the default pdf, 2. copy paste the
So it looks like babel didn't do its work properly ? Since I'm really lost here, does anyone know how I can fix this babel issue ? Or maybe there is an alternative in the PDFjs build script ? Thank you very much for your help :-D edit: someone suggest to use webpack (#19588 (comment)) i should give it a try maybe |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ok forget about ES6 ! It actually works. I thought that because of an open issue on the vscode repo saying you could not. The PDFjs viewer API changed a bit from v3 to v5, you need to pass the PDF URI as an object to the const pdfWebviewUri = webview.asWebviewUri(vscode.Uri.file(pdfPath)).toString();
...
const injectScript = `
<script>
window.addEventListener('load', function () {
const pdfUri = '${pdfWebviewUri}';
if (!pdfUri) { return; }
if (window.PDFViewerApplication) {
PDFViewerApplication.initializedPromise.then(() => {
PDFViewerApplication.open({url: pdfUri}).then(() => {
console.log('PDF loaded: ', pdfUri);
}).catch(e => {
console.error('Error loading PDF:', e);
});
});
} else {
console.error('PDFViewerApplication not found');
}
}, { once: true });
</script>
`;
html = html.replace('</body>', `${injectScript}\n</body>`);
webview.html = html; Using the PDFjs backend and viewer v5.3.31, without any modification on it. |
Beta Was this translation helpful? Give feedback.
Ok forget about ES6 ! It actually works. I thought that because of an open issue on the vscode repo saying you could not.
The PDFjs viewer API changed a bit from v3 to v5, you need to pass the PDF URI as an object to the
open
function. Something like this: