2014-01-23 37 views
0

您可以帮助我将特定的PDF文件页面转换为文本文件或提供链接来编辑PDF文件iOS应用程序。如何将pdf页面转换为ios应用程序中的文本文件

在此先感谢

+0

可能重复[如何从PDF页面获取文本?](http://stackoverflow.com/questions/9427634/how-can-i-get-the-text-from-pdf-page) – Tirth

+0

对不起,哥们,我不想从PDF页面的文本。我需要一个单独的文本文件。 –

+0

老兄,它给你从pdf文件的文本,你需要写在文本文件使用简单的I/O操作的字符串读取和写入。我必须先了解您最初需要的内容,而不依赖于第三方库或API。 – Tirth

回答

1

当加载自定义文档类型(DOC,PPT,PDF等)转换成一个UIWebView,web视图返回零HTML字符串,即使是通过JavaScript。提取PDF文本here有几点建议。

但是将字符串转换回PDF是不同的。如果你想保留原始PDF的格式,我相当确定这是不可能的,因为iOS上的NSAttributedString并没有太大的作用。但是,如果可能的话,这将适用于纯文本或NSAttributedString:

NSData *PDFDataFromString(NSString *str) { 
NSMutableData *data = [NSMutableData data]; 

//Create an NSAttributedString for CoreText. If you find a way to translate 
//PDF into an NSAttributedString, you can skip this step and simply use an 
//NSAttributedString for this method's argument. 

NSAttributedString* string = [[[NSAttributedString alloc] initWithString:str] autorelease]; 

//612 and 792 are the dimensions of the paper in pixels. (8.5" x 11") 
CGRect paperRect = CGRectMake(0.0, 0.0, 612, 792); 

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef) string); 
CGSize requiredSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, [string length]), NULL, CGSizeMake(paperRect.size.width - 144, 1e40), NULL); 

//Subtract the top and bottom margins (72 and 72), so they aren't factored in page count calculations. 
NSUInteger pageCount = ceill(requiredSize.height/(paperRect.size.height - 144)); 
CFIndex resumePageIndex = 0; 
UIGraphicsBeginPDFContextToData(data, paperRect, nil); 

for(NSUInteger i = 0; i < pageCount; i++) 
{ 

//After calculating the required number of pages, break up the string and 
//draw them into sequential pages. 

    UIGraphicsBeginPDFPage(); 
    CGContextRef currentContext = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState (currentContext); 
    CGContextSetTextMatrix(currentContext, CGAffineTransformIdentity); 
    CGMutablePathRef framePath = CGPathCreateMutable(); 

    //72 and 72 are the X and Y margins of the page in pixels. 
    CGPathAddRect(framePath, NULL, CGRectInset(paperRect, 72.0, 72.0)); 

    CTFrameRef frameRef = CTFramesetterCreateFrame(framesetter, CFRangeMake(resumePageIndex, 0), framePath, NULL); 
    resumePageIndex += CTFrameGetVisibleStringRange(frameRef).length; 
    CGPathRelease(framePath); 
    CGContextTranslateCTM(currentContext, 0, paperRect.size.height); 
    CGContextScaleCTM(currentContext, 1.0, -1.0); 
    CTFrameDraw(frameRef, currentContext); 
    CFRelease(frameRef);  
    CGContextRestoreGState (currentContext); 
} 
CFRelease(framesetter); 
UIGraphicsEndPDFContext(); 
return data; 
} 

快乐编码!

+0

thanx的答复老兄你可以解释它对我产生的结果是什么? –

+0

它会给我一个单独的文本文件或任何其他? –

+0

我已经将文件集成到我的应用程序从我已发布的链接,但我得到一些错误,可能是beccode的xcode版本问题它在版本4.2工作? –

相关问题