简体   繁体   English

使用 node.js 和 express 打开本地 pdf 文件

[英]Opening a local pdf file using node.js and express

I am attempting to make a pdf viewer app using electron and electron-pdf-window the code below works when i want to open from a URL file path, but when i tried to open a pdf from my local files using the file:/// the application download the pdf instead of viewing it on my window.我正在尝试使用 electron 和 electron-pdf-window 创建一个 pdf 查看器应用程序,当我想从 URL 文件路径打开时,下面的代码有效,但是当我尝试使用file:///从我的本地文件打开 pdf 时file:///应用程序下载 pdf 而不是在我的 window 上查看它。

const { app } = require('electron')
const PDFWindow = require('electron-pdf-window')

app.on('ready', () => {
  const win = new PDFWindow({
    width: 800,
    height: 600
  })

  win.loadURL('file://///C://username/desktop/myfile.pdf')
})

I tried also below code but below error displays.我也尝试了下面的代码,但下面的错误显示。

TypeError: Cannot match against 'undefined' or 'null'.类型错误:无法匹配“未定义”或“空”。

const { BrowserWindow } = require('electron').remote
const PDFWindow = require('electron-pdf-window')

const win = new BrowserWindow({ width: 800, height: 600 })

PDFWindow.addSupport(win)

win.loadURL('file://///C://username/desktop/myfile.pdf')

Is there another way to open local pdf files from my PC directory?还有其他方法可以从我的 PC 目录打开本地 pdf 文件吗?

Base on this readme, https://github.com/electron/electron/blob/master/docs/api/browser-window.md 基于此自述文件, https://github.com/electron/electron/blob/master/docs/api/browser-window.md

you can do it something like 你可以做类似的事情

win.loadURL(`file://${__dirname}/app/index.html`)

but you have to put this inside app.on('ready', function() {} to avoid getting the Cannot create BrowserWindow before app is ready error. 但您必须将其放入app.on('ready', function() {}以避免Cannot create BrowserWindow before app is ready错误。

Reason why that error appears Because the app is not yet ready and is still loading 出现该错误的原因,因为该应用程序尚未准备好并且仍在加载

You need Modify electron-pdf-window package.您需要修改 electron-pdf-window package。

Open electron-pdf-window/index.js打开 electron-pdf-window/index.js

Go to comment line 23 const->let fileUrl = url.replace(/^file:///i, ''); Go 注释行 23 const->let fileUrl = url.replace(/^file:///i, '');

firstly change const via let,then add after this code首先通过 let 更改 const,然后在这段代码之后添加

fileUrl = fileUrl.replace('/', '');

you can use normally;可以正常使用;

const w= new BrowserWindow({ width: 1200, height: 920, webPreferences: { nodeIntegration: true, contextIsolation: true } }); PDFWindow.addSupport(w)

w.loadURL(url.format ({ pathname: path.join(__dirname, '../pdf/123.pdf'), protocol: 'file:', slashes: true }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM