Skip to content

Instantly share code, notes, and snippets.

@flyingeek
Last active January 13, 2024 20:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flyingeek/70f5e09887f17dbfcd11a4b620a68b28 to your computer and use it in GitHub Desktop.
Save flyingeek/70f5e09887f17dbfcd11a4b620a68b28 to your computer and use it in GitHub Desktop.
scriptable-pdfjs-demo.js a demo (sort of) for scriptable-pdfs

This is a sort of demo file for scriptable-pdfjs

First copy scriptable-pdfjs.html into your Scriptable Documents folder.

Then copy paste below in a new script. Run and watch your console !

const fm = FileManager.iCloud();
const htmlDirectory = fm.joinPath(fm.documentsDirectory(), "");
//console.log(htmlDirectory);
const htmlFile = fm.joinPath(htmlDirectory, "scriptable-pdfjs.html");
console.log(htmlFile);
let wv = new WebView();
let [filePath] = args.fileURLs;
await fm. downloadFileFromiCloud(htmlFile);
await wv.loadFile(htmlFile);
if (!filePath) {
[filePath] = await DocumentPicker.open(["com.adobe.pdf"]);
}
/*
In the WebView your javascript will have access to the pdfjs global var.
pdfjs.pdfjsLib is the pdfjs module
pdfjs.getText is a convenience wrapper
pdfjs.getTextFromBase64String must be used instead for base64 string
*/
//console.log(htmlPdfPath);
wv.shouldAllowRequest = (request) => {
console.log(request);
return true;
}
console.log("using base64 works (tested up to 3.7Mo file size)");
let javascript = "";
javascript += 'pdfjs.getTextFromBase64String(';
javascript += '"' + fm.read(filePath).toBase64String() + '"';
javascript += ');'
result = await wv.evaluateJavaScript(javascript, true);
console.log(result.substring(0, 80) + "...");
console.log("Now with a remote pdf");
wv = new WebView();
await wv.loadFile(htmlFile);
javascript = "";
javascript += 'pdfjs.getText(';
javascript += '{"url": "https://cors-anywhere.herokuapp.com/https://github.com/mozilla/pdf.js/raw/master/examples/learning/helloworld.pdf"}';
javascript += ');'
result = await wv.evaluateJavaScript(javascript, true);
console.log(result.substring(0, 80) + "...");
const debug = false;
if (debug) {
// when url is local, does not work, (wait forever) why ?
const pdfPath = fm.joinPath(htmlDirectory, "scriptable-pdfjs.pdf");
if (fm.fileExists(pdfPath)) {
fm.remove(pdfPath);
}
fm.copy(filePath, pdfPath);
const regex = new RegExp(`^${htmlDirectory}`, "u")
const htmlPdfPath = pdfPath.replace(regex, "");
console.log(`local pdf url: ${htmlPdfPath}`);
wv = new WebView();
await wv.loadFile(htmlFile);
javascript = "";
javascript += 'pdfjs.getText(';
javascript += '{"url": "' + htmlPdfPath + '"}';
javascript += ');'
//console.log(javascript);
result = await wv.evaluateJavaScript(javascript, true);
console.log(result.substring(0, 80) + "...");
}
console.log("finished !");
return;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment