Foxit PDF SDK for Web

How to Create a Custom Screenshot Tool with Foxit PDF SDK for Web

This article will demonstrate creating a custom screenshot tool with Foxit PDF SDK for Web. You can get a free 30 day trial here.

Platform: Web

Programming Language: JavaScript

License Key Requirement: Standard

SDK Version: Foxit PDF SDK 9.0

Step 1:

Create a customized screenshot image storage service to upload the snapshots.

//Custom screenshot image storage service
const SnapshotServer = PDFViewCtrl.SnapshotServer;
const pdfui = new PDFUI({
...
viewerOptions: {
snapshotServer: new SnapshotServer({
origin: location.origin,
uploadSnapshotAPIPath: 'snapshot/upload',
payloadFieldName: 'file',
method: 'POST',
render: function(resp) {
return resp;
}
})
...
}
})
var pdfviewer = await pdfui.getPDFViewer();
// Capture the picture of the specified area on the page.
var imageBlob = await pdfviewer.takeSnapshot(0, 0, 0, 200, 200);
// Upload images to a specified server.
var uploadResult = await pdfviewer.uploadImage(imageBlob);
// Capture the picture and copy it to the clipboard
var copyResult = await pdfviewer.copySnapshot(uploadResult);

Step 2:

Capture a specified page area, upload it to a server (Node), and make it available to the clipboard. Before defining the image upload/retrieval interface, use the framework Koa to create a cache object for the image buffer.

To do this, create a new ‘test’ directory in the ‘test’ folder:

npm init

In the ‘test’ folder, add ‘index.js’:

//Import dependence packages
const Koa = require('koa');
const Router = require('koa-router');
const cors = require('koa-cors');
const app = new Koa();
const getRawBody = require('raw-body');
const LRU = require('lru-cache');

const router = Router();

// Create a cache object for saving the img buffer
const cache = new LRU({
max: 500
});

// Define upload img interface
router.post('/snapshot/upload', async (ctx) => {
let id = Date.now();
return getRawBody(ctx.req).then(buffer => {
const fileid = (id++).toString(16);
cache.set(fileid, {
type: 'image/png',
buffer: buffer
});
ctx.type = 'text/plain';
ctx.body = `/snapshot/image/${fileid}`;
});
});
// Define get img interface
router.get('/snapshot/image/:fileid', async (ctx) => {
const file = cache.get(ctx.params.fileid);
if(!file) {
ctx.type = 'image/svg';
ctx.body = '<svg></svg>';
return;
}
ctx.type = file.type;
ctx.body = file.buffer;
});

app.use(cors());
app.use(router.routes());
app.use(router.allowedMethods());

const port = 8080;
app.listen(port, function () {
console.log(`file upload server is listening on port ${port}`);
});

Updated on May 18, 2023

Was this article helpful?
Thanks for your feedback. If you have a comment on how to improve the article, you can write it here: