gpt4 book ai didi

c# - 使用 CefSharp 显示本地 PDF 文件

转载 作者:行者123 更新时间:2023-11-30 23:02:23 26 4
gpt4 key购买 nike

我正在尝试使用自定义 LocalSchemeHandler 显示本地 pdf 文件,它从文件中读取内存流。

文件存在,正在正确读取内存流。但是浏览器窗口中没有显示任何内容。通过文件方案显示相同的文件是可行的。

资源处理器:

public class LocalSchemeHandler : ResourceHandler
{
public override bool ProcessRequestAsync(IRequest request, ICallback callback)
{
var uri = new Uri(request.Url);
var file = uri.AbsolutePath;

Task.Run(() =>
{
using (callback)
{
if (!File.Exists(file))
{
callback.Cancel();
return;
}

byte[] bytes = File.ReadAllBytes(file);

var stream = new MemoryStream(bytes);
if (stream == null)
{
callback.Cancel();
}
else
{
stream.Position = 0;
ResponseLength = stream.Length;

var fileExtension = Path.GetExtension(file);
MimeType = GetMimeType(fileExtension);
StatusCode = (int)HttpStatusCode.OK;
Stream = stream;

callback.Continue();
}
}
});

return true;
}
}

ISchemeHandlerFactory:

public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "local";

public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
return new LocalSchemeHandler();
}
}

设置:

var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory()
});
// Increase the log severity so CEF outputs detailed information, useful for debugging
settings.LogSeverity = LogSeverity.Default;
Cef.Initialize(settings);

编辑尝试通过 ResourceHandler.FromFilePath 显示 PDF 文件也不起作用(不显示任何内容)。

public class CustomProtocolSchemeHandlerFactory : ISchemeHandlerFactory
{
public const string SchemeName = "local";

public IResourceHandler Create(IBrowser browser, IFrame frame, string schemeName, IRequest request)
{
var uri = new Uri(request.Url);
var file = uri.AbsolutePath;

var fileExtension = Path.GetExtension(file);
var mimeType = ResourceHandler.GetMimeType(fileExtension);
return ResourceHandler.FromFilePath(file, mimeType);
}
}

EDIT2

将 LogSeverity 设置为 Default 后,日志显示:[0524/150955.108:INFO:CONSOLE(20)] “Refused to load plugin data from 'local://c/Users/abidh/Desktop/pdf.pdf ' 因为它违反了以下内容安全策略指令:“object-src * blob: externalfile: file: filesystem: data:”。

最佳答案

没有找到使用谷歌的解决方案。感谢amaitland ,使用 IsCSPBypassing 属性解决了问题:

var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = CustomProtocolSchemeHandlerFactory.SchemeName,
SchemeHandlerFactory = new CustomProtocolSchemeHandlerFactory(),
IsCSPBypassing = true
});
settings.LogSeverity = LogSeverity.Error;
Cef.Initialize(settings);

关于c# - 使用 CefSharp 显示本地 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50503398/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com