2015-01-08 148 views
2

我想使PDF具有動態內容,如文本將是動態的,這些圖像將是動態的,所以取決於課程的網頁內容西港島線是動態的,以及,我按照這個教程http://code.tutsplus.com/tutorials/generating-pdf-documents--mobile-11265的iOS創建動態內容PDF

但在本教程中內容不是動態的。

+0

你想HTML轉換成PDF? –

+0

不,我有DB的內容,我想發送電子郵件作爲PDF文件。 –

+0

@NikitaKhandelwal我可以首先將我的內容轉換爲HTML,然後在pdf上編寫html?可以嗎? –

回答

2

您可以使用JavaScript這樣的傳遞值動態值

假設你有一個關鍵「的myKey」在你的HTML

<td><span class="fieldVal" id="myKey"></span></td> 

,並通過價值使用這樣

NSBundle *bundle = [NSBundle mainBundle]; 
NSURL *indexFileURL = [bundle URLForResource:@"name_of_your_local_html" withExtension:@"html"]; 
[wbView loadRequest:[NSURLRequest requestWithURL:indexFileURL]]; 
[wbView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('myKey').innerHTML='%@'",@"myValue"]]; 

現在將HTML轉換爲PDF,您可以使用此類別

https://github.com/iclems/iOS-htmltopdf/blob/master/NDHTMLtoPDF.h

2

我也使用了相同的工作很好希望這會對你有所幫助。

創建一個塊: - typedef void(^ PdfCompletion)(BOOL status,NSString * filePath,NSArray * fbArr);

-(void)addData 
{ 
    [MBProgressHUD showHUDAddedTo:self.view animated:YES]; 
    NSMutableDictionary *contactDict = [[NSMutableDictionary alloc] init]; 
    [contactDict setObject:contactTextField.text forKey:@"phonenumber"]; 
    [contactDict setObject:emailTextField.text forKey:@"emailid"]; 
    [contactDict setObject:userNameLabel.text forKey:@"displayname"]; 
    [self drawPdf:contactDict completion:^(BOOL status,NSString *filePath,NSArray *fbArr) 
    { 
     if (status) 
     { 
      NSMutableArray *arr; 
      arr = [[NSMutableArray alloc] init]; 
      NSData *filedata; 
      filedata = [NSData dataWithContentsOfFile:filePath]; 
      double locaTotalFileSize = filedata.length +498; 
      totalFileSize += locaTotalFileSize; 
      NSMutableDictionary *fileDict = [[NSMutableDictionary alloc] init]; 
      [fileDict setObject:userPicImageView.image forKey:@"image"]; 
      [fileDict setObject:filePath forKey:@"filePath"]; 
      [fileDict setObject:@"txt" forKey:@"fileType"]; 
      [fileDict setObject:[NSString stringWithFormat:@"%@_%@_%@",@"contact",[self getFbID],[self CurrentSystemTime]] forKey:@"fileName"]; 
      [fileDict setObject:@"1" forKey:@"uploadStatus"]; 
      [fileDict setObject:@"0 KB/0 KB" forKey:@"fileSizeStatus"]; 
      [fileDict setObject:@"0 KB/0 KB" forKey:@"ContentSize"]; 
      [arr addObject:fileDict]; 
      [self switchToReviewFiles:arr]; 
      //////NSLog(@"pdf convrt successfull"); 
     } 
     else 
     { 
      //////NSLog(@"Error to convert into pdf"); 
     } 
    }]; 
} 


// Then Call The DrawPDF Method::-- 

-(void)drawPdf:(NSMutableDictionary *)drawText completion:(PdfCompletion)callback 
{ 
    NSString* fileName = @"contact_card.txt"; 

NSArray *arrayPaths = 
NSSearchPathForDirectoriesInDomains(
            NSDocumentDirectory, 
            NSUserDomainMask, 
            YES); 
NSString *path = [arrayPaths objectAtIndex:0]; 
NSString* txtFileName = [path stringByAppendingPathComponent:fileName]; 

NSData *data = [NSJSONSerialization dataWithJSONObject:drawText options:NSJSONWritingPrettyPrinted error:nil]; 
[data writeToFile:txtFileName atomically:YES]; 
callback(YES,txtFileName,nil); 
1

來處理最簡單的方法,像可可或可可觸摸任何打印作業,就是首先要一個UIView(或UIViewController的)子畫/只要你想它打印佈局數據。即使您不打算在完成的應用程序的屏幕上顯示此視圖,也應該這樣做。 (你仍然可以將它放在開發中的屏幕上,以便看起來如何。)對於未知大小的模型,一個非常簡單的方法可能是UITableViewController。使用Autolayout或舊的UIViewAutoResizingMasks,這樣這個視圖將適應適度調整大小。當然,如果它是一個UIViewController子類,那麼你可以使用界面構建太做吧..

一旦你在這個位置繪製成PDF是微不足道

-(BOOL)writePDFtoPath:(NSString *)filePath{ 

NSMutableData *pdfData = [NSMutableData data]; 
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); 
//note that because I've passed in CGRectZero for the size the context //comes in its default size 

/* 
    default pdf.. 
    8.5 X 11 inch 
    612 x 792 
    */ 
//this is only 72dpi, but its the default. I have a trick where I zoom 
// out before drawing to improve resolution: 

NSInteger numberPages = 3; //work out how many pages you need 


for (NSInteger page = 0 : page < numberPages : page ++){ 

UIGraphicsBeginPDFPage(); 
CGContextRef pdfContext = UIGraphicsGetCurrentContext(); 
CGFloat scaleFactor = 3.0; 
CGContextSaveGState(pdfContext); 
CGContextScaleCTM(pdfContext, 1.0/scaleFactor, 1.0/scaleFactor); 


/// 
/// context size is now (612.0 * 3.0 , 792.0 * 3.0) , i.e. resolution 72.0 * 3.0 dpi.. 

[self.pdfGeneratingView setFrame: CGRectMake(0.0, 0.0, 612.0*scaleFactor, 792.0*scaleFactor) ]; //let autolayout make it fit 

//prepare your view for this page 

[self.pdfGeneratingView.layer renderInContext:pdfContext]; 
CGContextRestoreGState(pdfContext); 

}//page drawing loop 


BOOL success = [pdfData writeToFile:filePath atomically:YES]; 
return success; 
} 
0

使一些自定義的方法,並利用它們根據您的要求。下面是一些例子,

//創建作出任何大小的PDF任何地方的線路的方法,

- (void) drawLine:(CGFloat)ofWidth fromPoint:(CGPoint)from toPoint(CGPoint)to withColor:(UIColor *)color { 
//Get Current Graphics Context as a CGContextRef That Provides Graphic Environment for drawing in Quartz 2D 
CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

//Sets the width of line we going to draw. 
CGContextSetLineWidth(currentContext, ofWidth); 


//Sets the strok color of context 
CGContextSetStrokeColorWithColor(currentContext, color.CGColor); 

//Starting point of line as X,Y Value 
CGPoint startPoint = from; 

//Starting point of line as X,Y Value 
CGPoint endPoint = to; 

//Creates new empty path in given graphic context 
CGContextBeginPath(currentContext); 

//Begin a new subpath at given points 
CGContextMoveToPoint(currentContext, startPoint.x, startPoint.y); 

//Append line from the current points to the given points as parameter 
CGContextAddLineToPoint(currentContext, endPoint.x, endPoint.y); 

//Terminates the subpath of the context 
CGContextClosePath(currentContext); 

//Draw the corrunt path using drawing mode as paramete. 
CGContextDrawPath(currentContext, kCGPathFillStroke); 

}

這裏是方法把任何尺寸,任何顏色的文字和任何字體的任何地方,

- (void) drawText:(NSString *)text ofColor:(CGFloat)red Green:(CGFloat)green Blue:(CGFloat)blue withAlpha:(CGFloat)alpha withFont:(UIFont *)font atPoint:(CGRect)Point havingTextAlignment:(UITextAlignment)textAlignment{ 
//Get Current Graphics Context as a CGContextRef That Provides Graphic Environment for drawing in Quartz 2D 
CGContextRef currentContext = UIGraphicsGetCurrentContext(); 

//Fill the current context with the color. 
CGContextSetRGBFillColor(currentContext,red,green,blue,alpha); 


//String to Draw 
NSString *textToDraw = text; 


[textToDraw drawInRect:Point 
       withFont:font 
     lineBreakMode:UILineBreakModeWordWrap 
      alignment:textAlignment];} 

同樣會去的形象,

- (void) drawImage:(UIImage *)image atFrame:(CGRect)frame{ 

[image drawInRect:frame];} 

現在,您可以創建一個使用這些方法的任何類型的PDF,

- (void) generatePdfWithFilePath: (NSString *)thefilePath ofData:(NSDictionary *)data andPageSize:(CGSize) pageSize{ 

    UIGraphicsBeginPDFContextToFile(thefilePath, CGRectZero, nil); 

     // For exampl 
    [self drawLine:65.0 fromPoint: CGPointMake(10, 50) toPoint:CGPointMake(pageSize.width - 100) withColor:[UIColor colorWithRed:239.0/255.0 green:239.0/255.0 blue:239.0/255.0 alpha:1.0]]; 

    [self drawText:@"Testing text" ofColor:0.0 Green:0.0 Blue:0.0 withAlpha:1.0 withFont:[UIFont systemFontOfSize:16.0] atPoint:CGRectMake(60,200, pageSize.width - 200,30.0) havingTextAlignment:UITextAlignmentLeft]; 

UIGraphicsEndPDFContext(); 
} 

而且你可以從以下幫助,

http://www.raywenderlich.com/6581/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-1
http://www.raywenderlich.com/6818/how-to-create-a-pdf-with-quartz-2d-in-ios-5-tutorial-part-2