iOS创建具有动态内容的PDF

iOS创建具有动态内容的PDF,ios,objective-c,iphone,pdf-generation,Ios,Objective C,Iphone,Pdf Generation,我想使PDF与动态内容一样,文本将是动态的,图像将是动态的,所以取决于内容的课程网页也将是动态的,我遵循了本教程 但在本教程中,内容不是动态的。您可以像这样使用javaScript传递动态值 假设您的HTML中有一个键“myKey” <td><span class="fieldVal" id="myKey"></span></td> 现在,为了将HTML转换为PDF,您可以使用这个类 我也使用了同样的方法,它工作良好,希望这对您有所帮助 创建块:

我想使PDF与动态内容一样,文本将是动态的,图像将是动态的,所以取决于内容的课程网页也将是动态的,我遵循了本教程


但在本教程中,内容不是动态的。

您可以像这样使用javaScript传递动态值

假设您的HTML中有一个键“myKey”

<td><span class="fieldVal" id="myKey"></span></td>
现在,为了将HTML转换为PDF,您可以使用这个类


我也使用了同样的方法,它工作良好,希望这对您有所帮助

创建块:-

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);

与Cocoa或Cocoa Touch中的任何打印作业一样,处理此问题的最简单方法是首先创建UIView(或UIViewController)子类,以便按照您希望的打印方式绘制/布局数据。即使你不打算在完成的应用程序的屏幕上显示此视图,也应该这样做。(在开发过程中,您仍然可以将其放在屏幕上,以使其看起来符合您的要求。)对于未知大小的模型,一种非常简单的方法可能是UITableViewController。使用Autolayout或旧的UIViewAutoResizingMasks,以便此视图能够优雅地调整大小。当然,如果它是UIViewController子类,那么您也可以使用interface builder来实现

一旦你处于这个位置,绘制一个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;
}
-(BOOL)writepDfPath:(NSString*)文件路径{
NSMutableData*pdfData=[NSMutableData];
UIGraphicsBeginPDFContextToData(pdfData、CGRectZero、nil);
//请注意,因为我已经为大小传入了CGRectZero,所以上下文//是默认大小
/*
默认pdf。。
8.5 X 11英寸
612x792
*/
//这只是72dpi,但它是默认值。我有一个缩放的技巧
//为提高分辨率,请在绘图前进行以下操作:
NSInteger numberpage=3;//计算出您需要多少页
对于(NSInteger page=0:page
制作一些自定义方法,并根据需要使用它们。这里有一些例子

// Create a method to draw Line of any size anywhere in the 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();
}
此外,您还可以从以下方面获得帮助:



我知道这是一个老问题,但现在你会用

在目标C中:

@import PDFKit;
然后:

PDFDocument *doc = [[PDFDocument alloc] init];
PDFPage *page = [[PDFPage alloc] init];
[doc insertPage:page atIndex:0];
CGRect bounds = [page boundsForBox:kPDFDisplayBoxMediaBox];
PDFAnnotation *textField = [[PDFAnnotation alloc] initWithBounds:bounds forType:PDFAnnotationSubtypeWidget withProperties:nil];
textField.widgetFieldType = PDFAnnotationWidgetSubtypeText;
textField.fontColor = UIColor.whiteColor;
textField.backgroundColor = UIColor.blueColor;
textField.font = [UIFont systemFontOfSize:14];
textField.widgetStringValue = @"WWDC 2017";
[page addAnnotation:textField];

NSURL *fileURL = [[[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:nil] URLByAppendingPathComponent:@"test.pdf"];
if (![doc writeToURL:fileURL]) {
    NSLog(@"save failed");
}
或者,用Swift:

import PDFKit
以及:


请参阅,以下代码段是从中提取的。

您想将HTML转换为PDF吗?不,我有数据库中的内容,我想将其作为PDF文件发送电子邮件。@NikitaKhandelwal我可以先将我的内容转换为HTML,然后再将其写入PDF吗?可能吗?动态是什么意思?您在说明中提供的链接有三个功能,用于添加线条、文本和图像,以及您希望在PDF中添加它们的位置。除此之外,您还需要什么?用于将HTML转换为PDF
import PDFKit
let doc = PDFDocument()
let page = PDFPage()
doc.insert(page, at: 0)
let bounds = page.bounds(for: .mediaBox)
let textField = PDFAnnotation(bounds: bounds, forType: .widget, withProperties: nil)
textField.widgetFieldType = .text
textField.fontColor = .white
textField.backgroundColor = .blue
textField.font = .systemFont(ofSize: 14.0)
textField.widgetStringValue = "WWDC 2017"
page.addAnnotation(textField)

let fileURL = try! FileManager.default
    .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    .appendingPathComponent("test.pdf")

if !doc.write(to: fileURL) {
    print("save failed")
}