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

Viewer compact for Carbone #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
132 changes: 131 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,134 @@
# PDF.js [![Build Status](https://github.com/mozilla/pdf.js/workflows/CI/badge.svg?branch=master)](https://github.com/mozilla/pdf.js/actions?query=workflow%3ACI+branch%3Amaster)
# Light PDF.js


## Fork documentation


### Why a fork?

- Single bundled JS file: no need for additional requests to download files like `pdf.worker.js`
- Still utilizes web workers for performance optimization
- A lightweight package: 1.64 MB (or 499 KB compressed)
- No annotation editor (at least 100 KB of code)
- No thumbnail viewer
- No secondary toolbar
- No presentation mode
- No download/save feature
- No browser history support
- External toolbar/search bar with minimal CSS
- Fully functional within a Shadow DOM component. By default, the viewer adds a canvas and hidden divs to the global document body for the text layer...
- A new global `document.body` can be defined through `src/display/global_document_body.js` by passing `rootNode` during initialization
- Supports all the key features that make PDF.js a good viewer (lazy loading, selectable text, etc.)

### How to build

```sh
# Result => build/generic/web/viewer.mjs
npx gulp generic
# Or minified -> build/minified/web/viewer.min.mjs
npx gulp minified
```

### How to use it?

- Minimal JS:

```js
import { PDFViewerApplication, PDFViewerApplicationOptions } from './build/generic/web/viewer.mjs'

const config = {
// rootNode is a specific feature added to PDF.js, to avoid modyfing global DOM
rootNode : document.body, // or the first child of your shadow root document.getElementById("viewerRootNode")
mainContainer : document.getElementById("viewerContainer"),
viewerContainer : document.getElementById("viewer"),
}

// Init
PDFViewerApplication.run(config);

// Listen some events. For other events, see the orginal viewer code (web/app.js ...)
PDFViewerApplicationOptions.eventBus.on('documentloaded', (pdfDocument) => {} );
PDFViewerApplicationOptions.eventBus.on('pagechanging' , ({ pageNumber }) => {} );
PDFViewerApplicationOptions.eventBus.on('updateviewarea', ({location}) => {} );

// open a PDF, and set an initial position
const _initWithScrollPagePosition = `page=${location.pageNumber}&zoom=${location.scale},${location.left},${location.top}`;
await PDFViewerApplication.open({url : newState.lastRenderUrl, initHashView : _initWithScrollPagePosition });

// close PDF only
await PDFViewerApplication.close();

// close the viewer (stop all internal listeners)
await PDFViewerApplication.stop();
```

- Minimal HTML

```html
<div id="viewerRootNode">
<div id="viewerContainer">
<div id="viewer" class="pdfViewer"></div>
</div>
</div>
```

- Minimal CSS : `web/viewer-compact.css`


### Next Steps

- Document, add examples, and publish the NPM module
- Use `webpack-preprocessor-loader` to deactivate parts of the code with the builder instead of removing them from the code
- Create separate `web/app.js` and `web/viewer.js` files to keep the originals, and add a new build process in Gulp/Webpack

Optional:

- remove ./src/display/network.js ?
- remove code for NodeJS (fs, https, http, url)?
- remove XFA?
- remove Annotation Viewer?
- remove import { PDFDataTransportStream } from "./transport_stream.js"; ?
- remove import { PDFFetchStream } from "display-fetch_stream"; ?
- remove import { PDFNetworkStream } from "display-network"; ?
- remove import { PDFNodeStream } from "display-node_stream"; ?


### Best method to see unused code

- FIX_ME: the dev mode is broken when we inject the worker is injected inside src/display/api.js

```sh
npx gulp server

# test
http://localhost:8888/web/viewer.html
```

Go to Chrome DevTools and search for "Coverage"
- Remove everything that is not being used


```sh
npx gulp generic

# Test du viewer buildé
http://localhost:8888/build/generic/web/viewer.html
```


```sh
npx gulp minified

# Test du viewer buildé
http://localhost:8888/build/generic/web/viewer.html
```

-------------------------------------------------------------------------------------------------------------------------------------------------

Original README:


## PDF.js [![Build Status](https://github.com/mozilla/pdf.js/workflows/CI/badge.svg?branch=master)](https://github.com/mozilla/pdf.js/actions?query=workflow%3ACI+branch%3Amaster)

[PDF.js](https://mozilla.github.io/pdf.js/) is a Portable Document Format (PDF) viewer that is built with HTML5.

Expand Down
53 changes: 47 additions & 6 deletions gulpfile.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ function createWebpackConfig(
const babelExcludeRegExp = [
// `core-js`, see https://github.com/zloirock/core-js/issues/514,
// should be excluded from processing.
/node_modules[\\/]core-js/,
/(node_modules[\\/]core-js)|(pdf\.worker(?:\.min)?\.mjs)/, /* exclude the injected worker to avoid weird issue -> breaks JS code */
];

const babelPresets = skipBabel
Expand Down Expand Up @@ -372,6 +372,10 @@ function createWebpackConfig(
devtool: enableSourceMaps ? "source-map" : undefined,
module: {
rules: [
{
test: /pdf\.worker(?:\.min)?\.mjs$/, // when there is an import of this file
type: "asset/source", // insert the string directly in the code source
},
{
loader: "babel-loader",
exclude: babelExcludeRegExp,
Expand All @@ -381,6 +385,13 @@ function createWebpackConfig(
targets: BABEL_TARGETS,
},
},
{
test: /api\.js$/,
loader: "webpack-preprocessor-loader", // conditionnaly disable/entire JS part
options: {
params: defines, // GENERIC: true, MINIFIED : true ..
},
},
],
},
// Avoid shadowing actual Node.js variables with polyfills, by disabling
Expand Down Expand Up @@ -549,7 +560,7 @@ function createWebBundle(defines, options) {
const viewerFileConfig = createWebpackConfig(
defines,
{
filename: "viewer.mjs",
filename: defines.MINIFIED ? "viewer.min.mjs" : "viewer.mjs",
library: {
type: "module",
},
Expand Down Expand Up @@ -998,12 +1009,18 @@ function preprocessHTML(source, defines) {
return createStringSource(source.substr(i + 1), `${out.trimEnd()}\n`);
}

function buildGeneric(defines, dir) {
function buildWorker(defines, dir) {
// Build worker separately, to build it before the rest,
// and include the worker as a string in the final build
fs.rmSync(dir, { recursive: true, force: true });
return ordered([createWorkerBundle(defines).pipe(gulp.dest(dir + "build"))]);
}

function buildGeneric(defines, dir) {
// fs.rmSync(dir, { recursive: true, force: true });
return ordered([
// createWorkerBundle(defines).pipe(gulp.dest(dir + "build")),
createMainBundle(defines).pipe(gulp.dest(dir + "build")),
createWorkerBundle(defines).pipe(gulp.dest(dir + "build")),
createSandboxBundle(defines).pipe(gulp.dest(dir + "build")),
createWebBundle(defines, {
defaultPreferencesDir: defines.SKIP_BABEL
Expand Down Expand Up @@ -1059,6 +1076,14 @@ gulp.task(
async function prefsGeneric() {
await parseDefaultPreferences("generic/");
},
// Build worker separately, to build it before the rest,
// and include the worker as a string in the final build
function createWorker() {
console.log();
console.log("### Web Worker for later use in createGeneric");
const defines = { ...DEFINES, GENERIC: true };
return buildWorker(defines, GENERIC_DIR);
},
function createGeneric() {
console.log();
console.log("### Creating generic viewer");
Expand Down Expand Up @@ -1185,12 +1210,21 @@ gulp.task(
})
);

function buildMinified(defines, dir) {
function buildMinifiedWorker(defines, dir) {
// Build worker separately, to build it before the rest,
// and include the worker as a string in the final build
fs.rmSync(dir, { recursive: true, force: true });
return ordered([createWorkerBundle(defines).pipe(gulp.dest(dir + "build"))]);
}

function buildMinified(defines, dir) {
// fs.rmSync(dir, { recursive: true, force: true });
return ordered([
createMainBundle(defines).pipe(gulp.dest(dir + "build")),
createWorkerBundle(defines).pipe(gulp.dest(dir + "build")),
createWebBundle(defines, {
defaultPreferencesDir: "minified/"
}).pipe(gulp.dest(dir + "web")),
// createWorkerBundle(defines).pipe(gulp.dest(dir + "build")),
createSandboxBundle(defines).pipe(gulp.dest(dir + "build")),
createImageDecodersBundle({ ...defines, IMAGE_DECODERS: true }).pipe(
gulp.dest(dir + "image_decoders")
Expand All @@ -1213,6 +1247,13 @@ gulp.task(
async function prefsMinified() {
await parseDefaultPreferences("minified/");
},
function createMinifiedWorker() {
console.log();
console.log("### Creating minified worker");
const defines = { ...DEFINES, MINIFIED: true, GENERIC: true };

return buildMinifiedWorker(defines, MINIFIED_DIR);
},
function createMinified() {
console.log();
console.log("### Creating minified viewer");
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"typescript": "^5.6.2",
"vinyl": "^3.0.0",
"webpack": "^5.95.0",
"webpack-preprocessor-loader": "^1.3.0",
"webpack-stream": "^7.0.0",
"yargs": "^17.7.2"
},
Expand Down
4 changes: 2 additions & 2 deletions src/display/annotation_layer.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
PDFDateString,
setLayerDimensions,
} from "./display_utils.js";
import { AnnotationStorage } from "./annotation_storage.js";
// import { AnnotationStorage } from "./annotation_storage.js";
import { ColorConverters } from "../shared/scripting_utils.js";
import { XfaLayer } from "./xfa_layer.js";

Expand Down Expand Up @@ -3164,7 +3164,7 @@ class AnnotationLayer {
imageResourcesPath: params.imageResourcesPath || "",
renderForms: params.renderForms !== false,
svgFactory: new DOMSVGFactory(),
annotationStorage: params.annotationStorage || new AnnotationStorage(),
annotationStorage: params.annotationStorage, // || new AnnotationStorage(),
enableScripting: params.enableScripting === true,
hasJSActions: params.hasJSActions,
fieldObjects: params.fieldObjects,
Expand Down
Loading