I created a PDF with the code below:
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = #"test.pdf";
NSURL *fileURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:documentsDirectory, filename, nil]];
CGContextRef pdfContext = CGPDFContextCreateWithURL((CFURLRef)fileURL, NULL, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
CGRect bounds = CGContextGetClipBoundingBox(pdfContext);
CGContextScaleCTM(pdfContext, 1.0, -1.0);
CGContextTranslateCTM(pdfContext, 0.0, -bounds.size.height);
UIFont *headerFont = [UIFont fontWithName:#"Arial" size:8];
NSDictionary *headerAttributes = #{ NSFontAttributeName: headerFont};
[#"Task" drawAtPoint:CGPointMake(10, 10) withAttributes:headerAttributes];
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);
My question is, can I add a background colour as an attribute? for this
[#"Task" drawAtPoint:CGPointMake(10, 10) withAttributes:headerAttributes];
I will be adding multiple items and they will all have different background colours, I am just asking if this is possible?
You can definitely do this by using NSAttributedString and the relative properties, but for sanity I would recommend this library. I've found NSAttributedString to be insanely verbose and (personally) have enjoyed having my styling happen in a leaner language. Note that I have nothing to do with this library but it really helped
Related
I know this question has been asked many times, but none of the answers I read helped me to fix my problem...
In my iOS app, I'm generating a PDF file using default frameworks (UIGraphicsBeginPDFContextToFile...).
Everything works fine, I can change text colors, underlying styles, etc.
But I don't manage to strike a string.
Here's my code:
[toBeConfirmedText addAttributes:#{ NSBaselineOffsetAttributeName: #(0), NSStrikethroughStyleAttributeName: #(NSUnderlineStyleThick), NSStrikethroughColorAttributeName: [UIColor redColor] } range:NSMakeRange(0, toBeConfirmedText.length)];
But that does not work...
Does anyone has an idea?
I should add a comment that your code has no problem in Xcode 10. But because I need to add test codes, so you may treat it as an answer.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myTest.pdf"];
BOOL result = UIGraphicsBeginPDFContextToFile(filePath, CGRectZero, nil);
UIGraphicsBeginPDFPage();
NSMutableAttributedString * toBeConfirmedText = [[NSMutableAttributedString alloc]initWithString:#"mytest"];
[toBeConfirmedText addAttributes:#{ NSBaselineOffsetAttributeName: #(0), NSStrikethroughStyleAttributeName: #(NSUnderlineStyleThick), NSStrikethroughColorAttributeName: [UIColor redColor] } range:NSMakeRange(0, toBeConfirmedText.length)];
[toBeConfirmedText drawInRect: CGRectMake(0, 0, 600, 200)];
UIGraphicsEndPDFContext();
when I add some text in the textview, onclick of convert to pdf,then i have to convert textview text to pdf file.
can anyone give some solution for this problem.
Thanks for quick response
Refer this code.
NSString *text = #"this is textField's text";
NSMutableData *pdfData = [[NSMutableData alloc] init];
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, 320, 480), nil);
UIGraphicsBeginPDFPage();
[text drawInRect:UIGraphicsGetPDFContextBounds() withAttributes:#{NSFontAttributeName:[UIFont boldSystemFontOfSize:17]}];
UIGraphicsEndPDFContext();
NSString *file = #"file.pdf"; //this is the file name.
NSArray<NSURL *> *dir = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
if (dir.count > 0){
NSURL *path = [[dir firstObject] URLByAppendingPathComponent:file];
[pdfData writeToFile:path.path atomically:false];
}
You can provide any formatting options you want in the withAttributes dictionary in the draw method.
And if you want multiple pages in your PDF just put this code in a loop
UIGraphicsBeginPDFPage();
[text drawInRect:UIGraphicsGetPDFContextBounds() withAttributes:#{NSFontAttributeName:[UIFont boldSystemFontOfSize:17]}];
UIGraphicsEndPDFContext();
and change the text that draws. You can draw images too if you want them in your PDF.
Check the created PDF
Hope this helps.
I'm trying to create a new PDF with custom font.
I load my custom font and I can use it in all app, but when I tried to use it creating my PDF, the System font is printed.
I'm using NSString UIKit Additions.
+(UIFont *)imagoBook:(float)size{
return [UIFont fontWithName:#"Imago-Book" size:size];
}
-(NSData *)createPDFfromUIView
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, self.bounds, nil);
UIGraphicsBeginPDFPage();
UIFont *imagoBook13 = [ROCTextsInformation imagoBook:13];
[#"Test" drawAtPoint:CGPointZero withFont:imagoBook13];
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:#"t.pdf"];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
return pdfData;
}
In fact I'm drawing the same context in a view and the font is written perfectly but not in the pdf.
I'm using otf files for the font.
Thankssss
Finally I have solved the problem converting the file .otf to .ttf, and it works!
I need to create a multipage PDF with signature (UIImage) at the bottom. I would also like to have a line created so that the signature could be on a line. Here's the code I have so far:
- (IBAction)saveAsPDF:(id)sender
{
NSMutableData *pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, CGRectMake(0, 0, 612, 792), nil);
UIGraphicsBeginPDFPage();
[nameTextField.text drawInRect:CGRectMake(50, 40, 512, 30) withFont:[UIFont systemFontOfSize:16] lineBreakMode:NSLineBreakByWordWrapping alignment:NSTextAlignmentCenter];
[TextView.text drawInRect:CGRectMake(50, 90, 512, 672) withFont:[UIFont systemFontOfSize:12]];
[SignatureImageView.image drawInRect:CGRectMake(30, 500, 190, 71)];
UIGraphicsEndPDFContext();
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentNameWithExtention = [NSString stringWithFormat:#"%#.pdf", nameTextField.text];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:documentNameWithExtention];
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
}
So, I need to know how to make it multipage and I need to know how to add the signature at the end of the body text.
Any help would be appreciated.
From the docs
The functions you use to create a PDF graphics context allow you to
specify a default page size but they do not automatically open a page.
After creating your context, you must explicitly open a new page using
either the UIGraphicsBeginPDFPage or UIGraphicsBeginPDFPageWithInfo
function. And each time you want to create a new page, you must call
one of these functions again to mark the start of the new page. The
UIGraphicsBeginPDFPage function creates a page using the default size,
while the UIGraphicsBeginPDFPageWithInfo function lets you customize
the page size and other page attributes.
I'm currently creating and saving a PDF of a UIView. It is working great, but now I'm trying to create a PDF from text data saved to the disk rather than from the UIView. Ideally, I would like to create a PDF based on the text in the UITextView. The below code writes the first part of the text view just fine, but it doesn't create the PDF from the entire text view. It is quite a bit of text, so it only created the PDF from the amount of text that would fit on the view. The code that I'm currently using is this:
- (void)createPDFfromUIView:(UITextView*)view saveToDocumentsWithFileName:(NSString*)aFilename
{
NSMutableDictionary *myDictionary = CFBridgingRelease(CFDictionaryCreateMutable(NULL, 0,
&kCFTypeDictionaryKeyCallBacks,
&kCFTypeDictionaryValueCallBacks));
// Creates a mutable data object for updating with binary data, like a byte array
NSMutableData *pdfData = [NSMutableData data];
// Points the pdf converter to the mutable data object and to the UIView to be converted
UIGraphicsBeginPDFContextToData(pdfData, textview.bounds, myDictionary);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[textview.layer renderInContext:pdfContext]; // this line
// remove PDF rendering context
UIGraphicsEndPDFContext();
// Retrieves the document directories from the iOS device
NSArray* documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString* documentDirectory = [documentDirectories objectAtIndex:0];
NSString* documentDirectoryFilename = [documentDirectory stringByAppendingPathComponent:#"filename"];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
}
And to call it / save it, I put this message send in an IBAction: [self createPDFfromUIView:textview saveToDocumentsWithFileName:#"pdflocation"];
Now, I've been parsing through this code and the docs for hours, and cannot figure out how to create a PDF based upon a saved text file rather than the view. I'm still new to programming, so a lot of this is going over my head. Does anyone know how ot change the above code to have it create a PDF based upon saved text rather than the view?
Options: I could create a PDF based on output of an NSString. I could also throw the saved text into a UITextView and create the PDF based upon that (original plan) I however don't know how to do either.
This article from Apple explains how to create Pdf files and draw text on Pdf pages.
For those still looking for some sample code, this works:
- (NSData *)createPDFforText: (NSString *)text
{
NSMutableData *pdfData = [NSMutableData data];
NSMutableDictionary* attributes = [NSMutableDictionary dictionary];
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil);
UIGraphicsBeginPDFPage();
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
paragraphStyle.alignment = NSTextAlignmentLeft;
[attributes setObject: paragraphStyle forKey: NSParagraphStyleAttributeName];
[attributes setObject: [UIFont fontWithName: LATO_REGULAR size: 20.f] forKey: NSFontAttributeName];
[attributes setObject: [UIColor blackColor] forKey: NSForegroundColorAttributeName];
[text drawAtPoint: CGPointMake(20.f, 44.f) withAttributes: attributes];
UIGraphicsEndPDFContext();
return pdfData;
}
The CGRectZero bounds value sets the PDF document to the default page size of 8.5 by 11 inches (612 by 792 points).