gerhardberger / electron-pdf-window

view PDF files in electron browser windows
MIT License
282 stars 92 forks source link

Only prompting to download #3

Open selabie68 opened 7 years ago

selabie68 commented 7 years ago

I am attempting to have the plugin load a pdf file after it is downloaded to a temporary location but it just prompts to save the file.

My Code Example:

session.defaultSession.on('will-download', (e, item, webContents) => {
    // Set the save path, making Electron not to prompt a save dialog.
    //item.setSavePath('/tmp/' + item.getFilename())
    item.setSavePath('/tmp/saved.pdf')
    var savedHere = item.getSavePath()

    item.on('updated', (event, state) => {
        if (state === 'interrupted') {
            console.log('Download is interrupted but can be resumed')
            item.resume()
        } else if (state === 'progressing') {
            if (item.isPaused()) {
                console.log('Download is paused')
            } else {
                console.log(`Received bytes: ${item.getReceivedBytes()}`)
            }
        }
    })
    item.once('done', (event, state) => {
        if (state === 'completed') {
            var pdfWindow = new PDFWindow({
                title: item.getFilename(),
                icon: path.join(__dirname, "img/64x64.png")
            });
            var fileLocation = url.format({
                pathname: path.join("C:", savedHere),
                protocol: 'file:',
                slashes: true
            })
            console.log("File Location: " + fileLocation)
            pdfWindow.loadURL(fileLocation)
        } else {
            console.log(`Download failed: ${state}`)
        }
    })
})
mrcatj commented 7 years ago

I am having a similar issue. I was able to get the electron-pdf-window to display the PDF document when it came from a web address (http, https), but when it is a local file, it only prompts to download.

Is there anyway to force the viewing of a local PDF?

mrcatj commented 7 years ago

@selabie68 I am not sure if you are still having the issue with handling local files, but I was able to resolve it on my end. The electron-pdf-window index.js file needed to be edited as an escaped / was missing from the local file portion Promise statement. I submitted pull request #4 , but in the mean time:

Change this

 } else if (url.match(/^file:\/\//i)) {
  const fileUrl = url.replace(/^file:\/\//i, '')

to this

 } else if (url.match(/^file:\/\/\//i)) {
  const fileUrl = url.replace(/^file:\/\/\//i, '')
gerhardberger commented 7 years ago

how are the URLs that are failing look?

from the above it seems it is on windows where paths don't begin with / so @mrcatj's solution just simply skips that condition and probably succeeds because it is matched in the following condition where it is checked to end with .pdf.

mrcatj commented 7 years ago

in Windows, this is the File Path (local) that is being passed into it (File:///PathHere/file.pdf): image

Since there are three /// at the end of file:, I added a third / into the RegEx. After that addition, it works as expected on my end.

gerhardberger commented 7 years ago

@mrcatj this solution wouldn't work on unix though.

what if you remove the third / and just pass in file://C:/Users... to loadURL?

mrcatj commented 7 years ago

@gerhardberger I am new at this, so excuse any mistakes I make please.

I tried as you suggested and it seemed to work, I took out the extra / in the isPDF function tests, created a new function to strip the third / if it is there and replace with file:// and called this from the construct. It is still loading my local PDFs. I did not modify the .addSupport. Would this be suitable for unix enviro?

From isPDF

    } else if (url.match(/^file:\/\//i)) {
      const fileUrl = url.replace(/^file:\/\//i, '')

New function

function stripChar(url) {
    if (url.match(/^file:\/\/\//i)) {
        return url.replace(/^file:\/\/\//i, 'file://')
    } else {
        return url
    }
}

from the construct

loadURL (url) {
    const newUrl = stripChar(url)
    isPDF(newUrl).then(isit => {
      if (isit) {
          super.loadURL(`file://${
          path.join(__dirname, 'pdfjs', 'web', 'viewer.html')}?file=${newUrl}`)
      } else {
          super.loadURL(newUrl)
      }
    }).catch(() => super.loadURL(url))
  }

I am now encountering a new problem. If the directory to the PDF has spaces or the filename has %20 it fails to load the file.

If a %20 exists in the filename, the system appears to convert to a space and pdfjs viewer opens, but no file is displayed.

If a space exists in the path/filename, it appears to convert to a %20 and it reverts to the download window again rather than opening pdfjs viewer.

gerhardberger commented 7 years ago

@mrcatj try out the new version, now the URI is encoded, maybe it fixes the space character problem.

mrcatj commented 7 years ago

Unfortunately it seems to not work. I updated to your latest and had my original issue. Made changes to eliminate the leading / for Windows, and still it would only prompt to "download" the local PDFs. I tried changing from encodeURIcomponent to encodeURI just experimenting, and it puts me able to open local PDFs again, but with the same results as above.

Here is the top of the download box, showing the string passed to it. The original file name has spaces: BIO T BR_Overview.pdf

image

Here is a different file with %20 in the name. The grab shows the viewer open but no file loaded: UNITED%20KINGDOM_ENGLISH_1658.pdf

image

Xosmond commented 6 years ago

On Mac works fine, and when I add "file://" the file is downloaded.

island67 commented 6 years ago

I would like to know if you have solved this problem, I am looking for a desperate solution, thanks to everyone

AlexandreKilian commented 5 years ago

I have the same issue on mac… weirdly enough, in development it works, in production it prompts to download…