如何在 Rails 中显示 PDF?
How do I show a PDF in Rails?
我正在使用 pdfjs_viewer-rails gem,当我尝试以这种方式加载自定义 PDF 时
<%= pdfjs_viewer pdf_url: "http://biblioteca2.ucab.edu.ve/anexos/biblioteca/marc/texto/AAM8264.pdf", style: :full %>
我收到这个错误:
PDF.js v1.10.100 (build: ea29ec83)
Message: file origin does not match viewer's
我在互联网上搜索过,据我所知,我必须设置 CORS,但我不明白如何设置。
如果有任何其他方法可以显示 PDF 而无需打印和下载按钮,这不是 google toobar 方法,我很感激。 (我知道不可能阻止 PDF 被下载,这只是我大学的分配作品)。
您可以通过自己的服务器代理PDF文件。这应该可以解决您遇到的任何 CORS 问题或其他跨域问题。
第 1 步 - 为代理控制器添加新路由
get "proxy/:url" => "proxy#index", :constraints => { :url => /.*/ }
第 2 步 - 创建代理控制器
require 'open-uri'
class ProxyController < ApplicationController
def index
url = params[:url]
url.gsub!(/(https?:\/)/, '/')
# Note there is no error handling here.
# This is only proof of concept.
data = open(url)
send_data data.read,
:type => data.content_type,
:disposition => 'inline'
end
end
第 3 步 - 修改视图以使用代理
<%= pdfjs_viewer
pdf_url: "/proxy/http://remote-server.com/remotefile.pdf",
style: :full %>
如果从 https 下载时得到 OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: dh key too small
,您应该使用 Net::HTTP 而不是设置 ciphers
选项:
class ProxyController < ApplicationController
def index
url = Base64.urlsafe_decode64(params[:url])
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ciphers = "DEFAULT:!DH"
response = http.get(uri.request_uri)
send_data(response.body, type: response.content_type, disposition: :inline)
end
end
我正在使用 pdfjs_viewer-rails gem,当我尝试以这种方式加载自定义 PDF 时
<%= pdfjs_viewer pdf_url: "http://biblioteca2.ucab.edu.ve/anexos/biblioteca/marc/texto/AAM8264.pdf", style: :full %>
我收到这个错误:
PDF.js v1.10.100 (build: ea29ec83)
Message: file origin does not match viewer's
我在互联网上搜索过,据我所知,我必须设置 CORS,但我不明白如何设置。
如果有任何其他方法可以显示 PDF 而无需打印和下载按钮,这不是 google toobar 方法,我很感激。 (我知道不可能阻止 PDF 被下载,这只是我大学的分配作品)。
您可以通过自己的服务器代理PDF文件。这应该可以解决您遇到的任何 CORS 问题或其他跨域问题。
第 1 步 - 为代理控制器添加新路由
get "proxy/:url" => "proxy#index", :constraints => { :url => /.*/ }
第 2 步 - 创建代理控制器
require 'open-uri'
class ProxyController < ApplicationController
def index
url = params[:url]
url.gsub!(/(https?:\/)/, '/')
# Note there is no error handling here.
# This is only proof of concept.
data = open(url)
send_data data.read,
:type => data.content_type,
:disposition => 'inline'
end
end
第 3 步 - 修改视图以使用代理
<%= pdfjs_viewer
pdf_url: "/proxy/http://remote-server.com/remotefile.pdf",
style: :full %>
如果从 https 下载时得到 OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=error: dh key too small
,您应该使用 Net::HTTP 而不是设置 ciphers
选项:
class ProxyController < ApplicationController
def index
url = Base64.urlsafe_decode64(params[:url])
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ciphers = "DEFAULT:!DH"
response = http.get(uri.request_uri)
send_data(response.body, type: response.content_type, disposition: :inline)
end
end