如何使用文本和图像生成自定义PDF

时间:2014-11-10 04:19:13

标签: ios

我还要求生成带有文本和图像的自定义PDF文件.PDF应该至少5页。请允许任何人帮助我。谢谢提前!

1 个答案:

答案 0 :(得分:1)

以下是我从OS X项目中获得的一些代码,但它在iOS中非常相似。我希望这能以正确的方式引导你。

// create PDF context to file path; these measures are for the european DIN format A4
CGRect mediaBox = CGRectMake(0, 0, 595, 842);
CGContextRef context = CGPDFContextCreateWithURL((__bridge CFURLRef)fileURL, &mediaBox,
                                                 (__bridge CFDictionaryRef)@{(NSString *)kCGPDFContextAuthor: NSFullUserName(), (NSString *)kCGPDFContextCreator: @"mubi begum's great iOS PSD generator", (NSString *)kCGPDFContextTitle: fileName});

// create paragraph style for string drawing
NSMutableParagraphStyle *paragraphStyle = [NSParagraphStyle defaultParagraphStyle];
[paragraphStyle setLineBreakMode:NSLineBreakByWordWrapping];

// create attributes for string drawing
NSMutableDictionary *drawingAttributes = [@{NSParagraphStyleAttributeName: paragraphStyle,
                                            NSForegroundColorAttributeName: [NSColor blackColor],
                                            NSFontAttributeName:            [NSFont systemFontOfSize:13]} mutableCopy];

// finally draw the string
[@"YOUR STRING" drawInRect:frameForYourString withAttributes:drawingAttributes];

// create new page
CGContextEndPage(context);
CGContextBeginPage(context, NULL);

// load image to draw
NSImage *logoImage = [NSImage imageNamed:@"logo"];

// calculate image ratio and current size for drawing 
CGFloat ratio = logoImage.size.width / logoImage.size.height;

CGFloat imageHeight = 50; // or whatever fits your needs
CGFloat imageWidth = imageHeight * ratio;

// draw the image in the right top corner with 20px padding
[logoImage drawInRect:CGRectMake(mediaBox.size.width - imageWidth - 20, mediaBox.size.height - imageHeight - 20, imageWidth, imageHeight)];

// close the PDF context
CGContextEndPage(context);
CGPDFContextClose(context);
CFRelease(context);

编辑您还可以使用自定义字体,CoreGraphics会将相应的字体正确嵌入到PDF文件中。