2014-01-23 38 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工作? –

相關問題