hyzyla / pdfium

Typescript wrapper for the PDFium library, works in browser and node.js
https://pdfium.js.org
MIT License
35 stars 6 forks source link

Import error #20

Open kleenkanteen opened 3 days ago

kleenkanteen commented 3 days ago

Am on windows 10 using pnpm.

I am using pdfium inside a nextjs app route api route endpoint. When I upload a pdf to the endpoint, hoping to turn it into a png, I get this error:

Module not found: Can't resolve './'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./app/api/upload/route.ts
 ⨯ ../../../../node_modules/.pnpm/@hyzyla+pdfium@2.1.2/node_modules/@hyzyla/pdfium/dist/index.esm.js:1210:1

Here is the relevant code, I have installed both pdfium and sharp:

        const library = await PDFiumLibrary.init();
        const document = await library.loadDocument(fileBuffer);
        const page = await document.getPage(0);
        const image = await page.render({
          scale: 3,
          render: async (options: any): Promise<Uint8Array> => {
            return await sharp(options.data, {
              raw: {
                width: options.width,
                height: options.height,
                channels: 4,
              },
            })
              .png()
              .toBuffer();
          },
        });
kleenkanteen commented 3 days ago

silly mistake, @hyzyla/pdfium was not in packag.json

edit: actually that did not fix it. same error

kleenkanteen commented 3 days ago

The minimal reproduction in the readme works locally. Not sure why the error occurs in the nextjs api route.

hyzyla commented 3 days ago

@kleenkanteen could you create small project to reproduce the error?

kleenkanteen commented 3 days ago

@hyzyla https://github.com/kleenkanteen/pdfium-issue-reproduction

Steps to reproduce:

  1. Run pnpm install then pnpm run dev
  2. Open localhost:3000. You will get the same error upon load.
kleenkanteen commented 3 days ago

I forgot to add some code - just pushed a (more realistic) working reproduction

hyzyla commented 9 hours ago

I've checked several times and found that the problem lies in this line of code and the Webpack configuration of the Next.js project:

      scriptDirectory = require("url").fileURLToPath(new URL("./", import.meta.url));
screenshot

![CleanShot 2024-10-17 at 19 22 10@2x](https://github.com/user-attachments/assets/3c19c697-5558-4b2b-b886-dbcb28d67462)

This line is a combination of Emscripten code and a Rollup transformation applied to it.

But that’s it for now 😔. I don’t know how to solve it yet. I'll try to take another look at this problem over the weekend, but no promises for now.

kleenkanteen commented 8 hours ago

Np, I will try another library like pdf.js.

You might want to open a issue on the nextjs repo if you took a good look already. Someone there might be more familiar with this wizardry.