Writing text to a PDF via from an NSString - objective-c

I am fairly new to iOS development and this one is killing me. I have not found one complete (simple) example of how to write text to a pdf on the iPhone. The Apple documentation on the subject is code snippets and difficult to follow (for me anyway), and having downloaded the Quartz demo I discovered that all it did was display a pdf that already existed.
Simply put I have the world's simplest view-based app at this point. The view has one button in it. When the button is pressed an NSString is built that contains the numbers 1 through 15. I am able to write a text file to the device that contains the contents of the NSString, but would much prefer it be a pdf.
The bottom line is that I want to build a pdf file from the NSString, ultimately to be emailed as an attachment.
If anyone can point me somewhere that has a complete project that writes text to a pdf I would sure appreciate it.

// Create URL for PDF file
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = #"test.pdf";
NSURL *fileURL = [NSURL fileURLWithPathComponents:[NSArray arrayWithObjects:documentsDirectory, filename, nil]];
// Create PDF context
CGContextRef pdfContext = CGPDFContextCreateWithURL((CFURLRef)fileURL, NULL, NULL);
CGPDFContextBeginPage(pdfContext, NULL);
UIGraphicsPushContext(pdfContext);
// Flip coordinate system
CGRect bounds = CGContextGetClipBoundingBox(pdfContext);
CGContextScaleCTM(pdfContext, 1.0, -1.0);
CGContextTranslateCTM(pdfContext, 0.0, -bounds.size.height);
// Drawing commands
[#"Hello World!" drawAtPoint:CGPointMake(100, 100) withFont:[UIFont boldSystemFontOfSize:72.0f]];
// Clean up
UIGraphicsPopContext();
CGPDFContextEndPage(pdfContext);
CGPDFContextClose(pdfContext);

Related

Storing an array of CGLayer to file

I'm working on an OSX application where I need to store 446 CGLayers that get placed in a PDF context and am wondering if there's a way to write and read them from a file, rather than generating them when the application loads
I've read that CGLayer is no longer recommended, but I feel they really fit what I need. Also, if I use bitmapGraphicsContexts, they can pixelate when zooming in.
I am able to store them in NSArrays, both by storing them in NSValue and puting them into the array by bridging. I've also tried storing them in C arrays, but that didn't work out.
My problem comes when trying to store these arrays in a file. writeToFile: doesn't work with CGLayers, but NSKeyedArchiver/NSKeyedUnarchiver hasn't worked either, both when the layers are in NSValues or bridged.
Here's my method that attempts to write and read an array containing a single layer from a file.
+(CGLayerRef) colorAnnotations:(CGContextRef)context{
float symbolSize = 8;
CGRect glyphBox = CGRectMake(0,0, 8, 8);
CGLayerRef annotationLayer = CGLayerCreateWithContext (context,glyphBox.size, NULL);
CGContextRef annotaionLayerContext = CGLayerGetContext(annotationLayer);
CGMutablePathRef annot = CGPathCreateMutable();
//Drawing annotation
/*...*/
NSMutableArray *test = [[NSMutableArray alloc]init];
[test addObject:[[NSValue alloc] initWithBytes:&annotationLayer objCType:#encode(CGLayerRef)]];
//Getting file path in Documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/annots.data"];
[NSKeyedArchiver archiveRootObject:test toFile:dataPath];
NSMutableArray *testLoads = [NSKeyedUnarchiver unarchiveObjectWithFile:dataPath];
CGLayerRef layerToReturn;
[[testLoads objectAtIndex:0]getValue:&layerToReturn];
return layerToReturn;
}
I get [NSKeyedArchiver encodeValueOfObjCType:at:]: unknown type encoding ('^')') was raisedfrom this, pretty sure because of the CGLayerRef type.
The lines needed to draw the different annotations I need are pretty long, so I've been trying to figure out a way to have them made and stored in a file without having to make them on startup each time. So far I'm not seeing a way to do this, but was hoping someone here may know of one and would appreciate any help.

PDF writing from iPad

I am able to generate a PDF with the following code. Can someone please help me with how I would add text to this? Thanks in advance.
-(void)createPDFfromUIView:(UIView*)aView saveToDocumentsWithFileName:(NSString*)aFilename
{
// 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, aView.bounds, nil);
UIGraphicsBeginPDFPage();
// draws rect to the view and thus this is captured by UIGraphicsBeginPDFContextToData
[aView drawRect:aView.bounds];
// 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:aFilename];
// instructs the mutable data object to write its context to a file on disk
[pdfData writeToFile:documentDirectoryFilename atomically:YES];
NSLog(#"documentDirectoryFileName: %#",documentDirectoryFilename);
}
I've never done this (yet, I plan getting on it tomorrow). But I think the right place to go is the Quartz 2D programming guide. It's also available from your developer documentation if you need it offline.
Basically you the same as you posted but appart from calling drawRect: you perform all the text drawing you want on that context.
There's useful information on writing simple strings on this guide
I hope it helps. It sure helped me!

TIFF image format for iphone application

I am working on iphone app and i need to save image into .tiff format.
It is possible to save image into png format using UIImagePNGRepresentation method and JPEG format using UIImageJPEGRepresentation. But i need to save signature captured by imageview into tiff format.
I unable to use NSImage class so that i can call TIFFRepresentation method.
How can i do it.Send me suggestion...
Thanks in advance...
I don't know what you mean by "captured by imageview". The means to save as TIFF wasn't introduced until iOS 4. Here is example code to save an arbitrary file as a TIFF; you can do this with any file-format data, no matter how you obtained it. You need to link to ImageIO framework and do #import <ImageIO/ImageIO.h>:
NSURL* url = [[NSBundle mainBundle] URLForResource:#"colson" withExtension:#"jpg"];
CGImageSourceRef src = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
NSFileManager* fm = [[NSFileManager alloc] init];
NSURL* suppurl = [fm URLForDirectory:NSApplicationSupportDirectory
inDomain:NSUserDomainMask
appropriateForURL:nil
create:YES error:NULL];
NSURL* tiff = [suppurl URLByAppendingPathComponent:#"mytiff.tiff"];
CGImageDestinationRef dest = CGImageDestinationCreateWithURL((CFURLRef)tiff,
(CFStringRef)#"public.tiff", 1, NULL);
CGImageDestinationAddImageFromSource(dest, src, 0, NULL);
bool ok = CGImageDestinationFinalize(dest);
NSLog(#"result %i", ok); // 1, all went well
// and don't forget memory management, release source and destination, NSFileManager
[fm release]; CFRelease(src); CFRelease(dest);
Hmm, I don't develop for the iPhone, so can't tell you if there's a magic API way of doing this, but many years ago I had to create TIFF images manually.
The TIFF format is a bit whacky if you're used to just using a framework's CreateThisStuffAsAnImage() methods, but you can get the spec here and create the file yourself:
http://partners.adobe.com/public/developer/tiff/index.html#spec

Why does my data successfully write to a file on the iPhone simulator, but not my device?

I have the following code that saves the users sketch data to a file...
//Auto Save the sketch
NSString *filename = [NSString stringWithFormat:#"%#.png", sketchID];
CGImageRef imageRef = CGBitmapContextCreateImage(paintView.canvas.mBitmapContext);
UIImage* image = [[UIImage alloc] initWithCGImage:imageRef];
NSData* imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:filename atomically:YES];
CGImageRelease(imageRef);
[image release];
the SketchID is a unique alphanumeric value, so an example of the filename I'm saving to is "p1.png". The code I use to read the file is...
//Load the sketch where the user left off, if there is one
if(fileName != nil)
{
UIImage* image = [UIImage imageWithContentsOfFile:fileName];
if(image != nil)
{
.
.
This code seems to work fine when running on the simulator, but when I run it on the device, the fails to load the image. I new to iOS development and I'm still learning how files are stored. My questions are...
Why would saving/loading the file work on the simulator, but not the device?
When I create the filename that I want to save the data to, do I need to also include a path to a specific directory on the iPhone where the data should be properly stored? Or should "p1.png" work fine when I call the writeToFile: method? And what about the imageWithContentsOfFile: method?
Why would saving/loading the file work
on the simulator, but not the device?
There are tons of reasons, but the most common is trying to write to a location that isn't writable on the device, and the most common reason for that is writing to the application bundle itself.
All iPhone apps are "sandboxed" on the device, meaning they cannot access the filesystem outside of the directory the application is installed into.
When I create the filename that I want
to save the data to, do I need to also
include a path to a specific directory
on the iPhone where the data should be
properly stored? Or should "p1.png"
work fine when I call the writeToFile:
method? And what about the
imageWithContentsOfFile: method?
You can write to your application's temp directory (if you just need a temporarily place to put something during a run) or the Documents directory (if you need to store something more permanently, and also have it backed up by iTunes).
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
I found that the simulator is very forgiving in writing files but the devices of course are not. My problem was that I was creating filePath incorrectly that the simulator did not catch. Simulator should have caught this one.
Here was my wrong and correct swift code
docsDir!+"filename.dat" // wrong does not have path separator between dir and file
docsDir!.stringByAppendingPathComponent("filename.dat") // works since it puts the "/" in between the two.

best way to get text from a plain .txt file into a Scroll View

Can someone please help me out with this I'm actually going nuts!
What is the best way to get text from a plain .txt file into a Scroll View, thats all I need just text.
I've tried so many different solutions but can't get any of them working I was hoping someone could give me a fresh overview.
Is the file a resource in your application or are you loading it from a network resource? If embedded, you can load it into an NSString object and then set the text property of the UITextView with that. Something like:
UITextView *myTextView = [[UITextView alloc] init];
NSString *pathToFile = [[NSBundle mainBundle] pathForResource:#"yourTextFile" ofType:#"txt"];
NSString *theText = [NSString stringWithContentsOfFile:pathToFile encoding:NSUTF8StringEncoding error:nil];
myTextView.text = theText;