Code Monkey home page Code Monkey logo

svelte-pdfjs's Introduction

svelte-pdfjs

A wrapper around Mozilla's PDFJS renderer. Only cares about loading and showing the PDF and nothing else, all the fancy stuff such as styling the viewer is left up to the consumer. Still in early stages so feel free to create an issue or a PR for any bugs that you find, any improvements or feature requests.

Usage

You'll have to install pdfjs-dist and provide a worker to the Document component through svelte's context. For vite/sveltekit users a convenience function is exported through svelte-pdfjs/utils/vite which takes care of browser checks, resolving the url to the worker, setting the context and cleaning up when the component is destroyed.

See src/routes/+page.svelte and src/routes/+layout.svelte Demo

SSR

For now this package cannot be used with SSR, contributions to improve in that area are more than welcome. Because of how pdfjs-dist is packaged, there is an eval which prevents bundlers from properly minifying whatever chunk it ends up in. To get around it, you can patch your installation of pdfjs-dist such that all instances of _is_node.isNodeJs are replaced with false since those parts aren't going to be used anyway.

TODOs:

  • Text layer rendering
  • SvelteKit compatibility
  • SVG renderer
  • Annotation layer
  • Error handling
  • Expose more stuff

License

MIT

svelte-pdfjs's People

Contributors

eltigerchino avatar gtm-nayan avatar immortalin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

svelte-pdfjs's Issues

Dispatch an event when a page has finished loading

I want to be able to listen for an event that is emitted when a page has finished loading so that I can fade-in the page once all its content has rendered as opposed to the current rendering (part by part).

Make the component compatible with SSR

I thought it was compatible with SSR but that apparently only works in dev mode.

Build fails with different errors presumably also at different stages depending on what adapter is used

> Using @sveltejs/adapter-node
> Cannot find module 'projectdir\node_modules\pdfjs-dist\build\pdf' imported from projectdir\.svelte-kit\output\server\app.js
Did you mean to import [email protected]/node_modules/pdfjs-dist/build/pdf.js?
Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'projectdir\node_modules\pdfjs-dist\build\pdf' imported from projectdir\.svelte-kit\output\server\app.js
Did you mean to import [email protected]/node_modules/pdfjs-dist/build/pdf.js?
    at new NodeError (node:internal/errors:371:5)
    at finalizeResolution (node:internal/modules/esm/resolve:416:11)
    at moduleResolve (node:internal/modules/esm/resolve:932:10)
    at defaultResolve (node:internal/modules/esm/resolve:1044:11)
    at ESMLoader.resolve (node:internal/modules/esm/loader:422:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:222:40)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:40)
    at link (node:internal/modules/esm/module_job:75:36)
 ERROR  Command failed with exit code 1.
> Using @sveltejs/adapter-netlify
 > node_modules/.pnpm/[email protected]/node_modules/pdfjs-dist/build/pdf.js:4452:29: error: Could not resolve "canvas" (mark it as external to exclude it from the bundle, or surround it with try/catch to handle the failure at run-time)
    4452 │       const Canvas = require("canvas");
         ╵                              ~~~~~~~~

> Build failed with 1 error:
node_modules/.pnpm/[email protected]/node_modules/pdfjs-dist/build/pdf.js:4452:29: error: Could not resolve "canvas" (mark it as external to exclude it from the bundle, or surround it with try/catch to handle the failure at run-time)
Error: Build failed with 1 error:
node_modules/.pnpm/[email protected]/node_modules/pdfjs-dist/build/pdf.js:4452:29: error: Could not resolve "canvas" (mark it as external to exclude it from the bundle, or surround it with try/catch to handle the failure at run-time)
    at failureErrorWithLog (projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1493:15)
    at projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1151:28
    at runOnEndCallbacks (projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1069:65)
    at buildResponseToResult (projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1149:7)
    at projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:1258:14
    at projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:629:9
    at handleIncomingPacket (projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:726:9)
    at Socket.readFromStdout (projectdir\node_modules\.pnpm\[email protected]\node_modules\esbuild\lib\main.js:596:7)
    at Socket.emit (node:events:390:28)
    at addChunk (node:internal/streams/readable:315:12)
 ERROR  Command failed with exit code 1.

npm run build gives error

with the default example:
npm run dev , it works just fine,
but when npm run build , it gives error:

import { getDocument } from "pdfjs-dist";
^^^^^^^^^^^
SyntaxError: Named export 'getDocument' not found. The requested module 'pdfjs-dist' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'pdfjs-dist';
const { getDocument } = pkg;

at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:190:5)

file:///C:/svelte/tes/svelte-pdfjs/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:35
throw new Error(format(details));
^

Error: 500 /
at file:///C:/svelte/tes/svelte-pdfjs/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:35:11
at save (file:///C:/svelte/tes/svelte-pdfjs/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:360:4)
at visit (file:///C:/svelte/tes/svelte-pdfjs/node_modules/@sveltejs/kit/src/core/prerender/prerender.js:210:3)

Node.js v18.13.0
[vite-plugin-sveltekit-build] Prerendering failed with code 1
error during build:
Error: Prerendering failed with code 1
at ChildProcess. (file:///C:/svelte/tes/svelte-pdfjs/node_modules/@sveltejs/kit/src/exports/vite/index.js:483:15)
at ChildProcess.emit (node:events:513:28)
at ChildProcess._handle.onexit (node:internal/child_process:291:12)

how to solve this? thanks.

Rethink onMount abstraction

Currently, the Document and Page components dynamically import internal Document and Page components, for compatibility with SvelteKit, this was done to avoid having to do it in the consumer.

However, people using the lib would probably not use the Document and Page components directly, instead create their own PDFViewer component using these. In which case, dynamically importing them in the consumer wouldn't really be that big of a deal.

So, is it really necessary to do the dynamic imports within the library?

SSR compatibility

The library is currently incompatible with SSR. Disabling SSR solves the issue, but prevents advantages such as opengraph meta generation.

  • Could this be solved by only rendering if it's in the browser environment?
  • Additionally, would lazy-loading the library in the browser help with SSR bundle size?

Text rendering is broken in build mode

dunno how I didn't notice this for so long, but text rendering hasn't been working since this commit 719cd17

If anything I'd expect it to be broken from the one before but apparently not, I'm assuming esbuild does some unsafe transformation when it tries to minify the worker which doesn't happen for a url import

Having no joy with this component - "exports is not defined"

I have a new sveltekit project, I have added svelte-pdfjs (using: npm -i svelte-pdfjs), but my page with the component which is taken more or less from your routes/index.svelte just gives me an error 500:-

exports is not defined
ReferenceError: exports is not defined
    at http://localhost:3000/node_modules/svelte-pdfjs/node_modules/pdfjs-dist/lib/pdf.js?v=96c44fcc:24:23

I can see pdfjs-dist in my node_modules @ 2.12.313. I've tried earlier version but still get the same.

My page.svelte contains:

<script lang="ts">
	import { Document, Page, PDFJS, preferThisHeight } from 'svelte-pdfjs';
	import type { MultipleOf90 } from 'svelte-pdfjs';
	import workerSrc from 'pdfjs-dist/build/pdf.worker.js?url';
	import { browser } from '$app/env';
	import { selectedPart } from '$lib/stores';

	import { MEDIA_URL } from '$lib/variables';

	if (PDFJS.GlobalWorkerOptions) {
		PDFJS.GlobalWorkerOptions.workerSrc = workerSrc;
	}

	let scale: number = 1;
	let num: number = 1;
	let maxPages = 1;
	let renderTextLayer: boolean;
	let targetHeight = 500;
	let rotation: MultipleOf90 = 0;

	const file = `${MEDIA_URL}${$selectedPart.partfile}`;
	console.log(file);
</script>

{#if browser}
	<Document
		{file}
		on:loadsuccess={(e) => console.log((maxPages = e.detail.numPages))}
		on:loaderror={console.log}
	>
		<div>
			<Page
				{scale}
				{num}
				{renderTextLayer}
				{rotation}
				getViewport={preferThisHeight(targetHeight)}
			/>
		</div>
	</Document>
{/if}

What am I missing? Thanks.
Hamish

Support local file path or array buffer

Currently the PDF must be accessible by URL, but for more flexibility and supporting different use cases it'd be nice to be able to provide a local file path or the contents directly.

Specifically in my case, I'm looking for something to use with Tauri; so I can either provide the data directly from a non-HTTP API call, or first write it to a temporary file, but I can't really conveniently make it available at a URL.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.