1

我们正在尝试在 UIWebview 中打开受密码保护的 PDF/DOC 文件。出于安全考虑,我们只能从服务器中检索文件并存储到内存中(即 NSData),而不能存储为文件。

我们尝试在 UIWebiew 中使用 loaddata 功能,它只能成功加载没有密码保护的 doc/xls/ppt/pdf。

对于带有密码的doc/xls文件,它显示“无法读取文档。操作无法完成(QuickLookErrorDomain错误44820/912”。请问如何在UIWebview中打开文件?

对于带有密码的 pdf 文件,它显示“文档“空白”受密码保护”。请问我们如何显示正确的文档名称而不是“Blank”?

我还搜索了 cgpdf 并知道如何将 pdf 文件解锁为 CGPDFDocumentRef,但找不到将其更改回 NSData 并直接输入 UIWebview 的方法。

谢谢。

4

2 回答 2

1

在本地写入文件并读取数据并在 Web 视图中显示

//convert file data(ie : NSData) as string
NSData *fileData;//This is the data from your request
NSString *fileString = [[NSString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];

//get the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"sample.pdf"];

//Save as file
NSError *error;
BOOL hasFileWritten = [fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];

if(!hasFileWritten)
{
    NSLog(@"Write file error: %@", error);
}

//open pdf in webview
NSURL *targetURL = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

更新 本地不写入文件数据,处理内存中的数据并在webview中显示pdf文件

@interface ViewController ()
{
    IBOutlet UIWebView *webView;
    CATiledLayer *tiledLayer;
    CGPDFPageRef pageRef;
}
@end


CGPDFDocumentRef pdf = CGPDFDocumentCreateWithURL((CFURLRef)url);

BOOL success = CGPDFDocumentUnlockWithPassword(pdf, "test");

if(success)
{
    pageRef = CGPDFDocumentGetPage(pdf, 1);

    CGRect pageRect = self.view.frame;

    tiledLayer = [CATiledLayer layer];
    tiledLayer.delegate = self;
    tiledLayer.tileSize = CGSizeMake(1024.0, 1024.0);
    tiledLayer.levelsOfDetail = 1000;
    tiledLayer.levelsOfDetailBias = 1000;
    tiledLayer.frame = pageRect;

    UIView *contentView = [[UIView alloc] initWithFrame:pageRect];
    [contentView.layer addSublayer:tiledLayer];

    [webView addSubview:contentView];
}


- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
    CGContextSetRGBFillColor(ctx, 1.0, 1.0, 1.0, 1.0);
    CGContextFillRect(ctx, CGContextGetClipBoundingBox(ctx));
    CGContextTranslateCTM(ctx, 0.0, layer.bounds.size.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);
    CGContextConcatCTM(ctx, CGPDFPageGetDrawingTransform(pageRef, kCGPDFCropBox, layer.bounds, 0, true));
    CGContextDrawPDFPage(ctx, pageRef);
}
于 2016-04-18T08:19:58.310 回答
0

为了解锁受保护的 PDF 文件,您必须使用CGPDFDocument

然后使用CGPDFDocumentUnlockWithPassword你可以解锁你的文件, UIWebView 要简单得多,但你的情况需要CGPDFDocument

这是一个可能对您有用的

于 2016-04-18T09:14:55.183 回答