在Objective - C中使用适当的格式和图像创建PDF

时间:2017-04-25 07:05:44

标签: ios objective-c pdf

请仔细阅读我的情景,

我有一个UITextView和一个UIImageView底部的TextView。 每次在TextView中都会有动态内容,相应地,我要求用户进行签名,它将在底部的ImageView中显示为图像。

现在要求我必须在服务器上将这些详细信息与Signature一起传递到一个PDF文件中,因此我必须创建包含TextView文本和ImageView图像的PDF文件。

注意:TextView也包含Html文本,因此它也应以PDF格式显示。

根据需要检查以下图片和当前的PDF格式。

这是必需的PDF This is required PDF

这是当前的PDF This is current PDF

仅放置对HTML支持和图像合并对文本有用的代码。请不要像我已经完成的那样显示简单的PDF创建。

2 个答案:

答案 0 :(得分:2)

你不需要第三方库,Cocoa和Cocoa touch有丰富的PDF支持。我已经把你开了一点,在你的viewController中做这个。可能会有一些小错误,我已经使用swift几年了,但我在这里使用了非常生锈的objC,因为你用这种方式标记了问题。让我知道任何问题,祝你好运

  -(NSData *)drawPDFdata{

    //  default pdf..
    // 8.5 X 11 inch @72dpi
    // = 612 x 792
    CGRect rct = {{0.0 , 0.0 } , {612.0 , 792.0}}
    NSMutableData *pdfData = [[NSMutableData alloc]init];
    UIGraphicsBeginPDFContextToData(pdfData, rct, nil);
    CGContextRef pdfContext = UIGraphicsGetCurrentContext();


    UIGraphicsBeginPDFPage();


 //textView drawing
    CGContextSaveGState(pdfContext);
    CGContextConcatCTM(pdfContext, CGAffineTransformMakeTranslation(50.0,50.0));//this  is  just an offset for the textView drawing. You will  want to play with the values, espeecially if supporting multiple screen sizes you might tranform the scale  as well..

    [textView.layer renderInContext:pdfContext]
    CGContextRestoreGState(pdfContext);


//imageView drawing
    CGContextSaveGState(pdfContext);
    CGContextConcatCTM(pdfContext, CGAffineTransformMakeTranslation(50.0,50.0)); //this  is  just an offset for the imageView drawing. Thee same stuff applies as above..
    [imageView.layer renderInContext:pdfContext]
    CGContextRestoreGState(pdfContext);



//cleanup
    UIGraphicsEndPDFContext();
    return pdfData;

}

这里有几个使用此NSData的客户端函数

   //ways to use the pdf Data
-(Bool)savePDFtoPath: (NSString *)path {

    return [ [self drawPDFdata]  writeToFile:path atomically:YES] ;

}

//requires Quartz framework.. (can be  drawn straight to a UIView)
// note you MAY owe a CGPDFDocumentRelease() on the  result  of this function (sorry i've not used objC in a couple of years...)
-(CGPDFDocument *)createPDFdocument {

    NSData *data = [self  drawPDFdata];
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL , data , sizeof(data) ,NULL);

    CGPDFDocument result = CGPDFDocumentCreateWithProvider(provider);

    CGDataProviderRelease(provider); //not sure if this is still required under ARC??  (def not in swift)

    return result;
}

答案 1 :(得分:1)

试试这个有用的第三方库:

https://github.com/iclems/iOS-htmltopdf

使用此功能解决您的问题:

+ (id)createPDFWithHTML:(NSString*)HTML pathForPDF:(NSString*)PDFpath pageSize:(CGSize)pageSize margins:(UIEdgeInsets)pageMargins successBlock:(NDHTMLtoPDFCompletionBlock)successBlock errorBlock:(NDHTMLtoPDFCompletionBlock)errorBlock;
相关问题