PDF Password not working properly in Objective C - ios

I am creating a PDF using UIGraphicsBeginPDFContextToData( pdfData, self.rect, dictionary);
I set dictionary=[[NSDictionary alloc] initWithObjectsAndKeys:masterPassword,kCGPDFContextOwnerPassword,password, kCGPDFContextUserPassword, kCFBooleanFalse, kCGPDFContextAllowsCopying, kCFBooleanTrue, kCGPDFContextAllowsPrinting, nil];
When i give kCGPDFContextUserPassword with more than five characters, the kCGPDFContextOwnerPassword is not working. Please someone help me with this issue.
You can find a pdf example here.
This pdf contains: kCGPDFContextOwnerPassword as "admin", kCGPDFContextUserPassword as "qwerty".

Related

Create custom metaData on a PDF with iOS

I'm working on a project and I need to create and set my own metadata on a PDF (in order to set a GUID directly into the file).
I am currently able to set classic metadata (e.g creator, keywords...etc) but I can't figure out how to add a custom field.
Here's how I set the metadata:
CFMutableDictionaryRef auxInfo = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, NULL);
CFDictionaryAddValue(auxInfo, kCGPDFContextCreator, CFSTR("John doo"));
CFDictionaryAddValue(auxInfo, kCGPDFContextAuthor, CFSTR("foo bar"));
CFDictionaryRef auxillaryInformation = CFDictionaryCreateCopy(kCFAllocatorDefault, auxInfo);
CFRelease(auxInfo);
// create a context to draw into
CGContextRef graphicContext = CGPDFContextCreate(PDFDataConsumer, &mediaRect, auxillaryInformation);
CFRelease(auxillaryInformation);
CGDataConsumerRelease(PDFDataConsumer);
I tried to replace the kCGPDFContextThing by a custom name but then when I read the metadata, it doesn't appear at all.
For reading the meta I used that
CGPDFDictionaryRef dict = CGPDFDocumentGetInfo(*pdfDoc);
CGPDFDictionaryGetString(dict, "Creator", &objectValue);
I also try that to add a meta :
NSString* str= #"Hello World";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
CFDataRef cfdata = CFDataCreate(NULL, [data bytes], [data length]);
CGPDFContextAddDocumentMetadata(graphicContext, cfdata);
But it doesn't seems to work neither, and I'm not sure I understand correctly what's done there.
I am also using PDFNet SDK to help the editing, but it doesn't seems to provide any help about metadata so I'm using quartz.
Any help or advice or anything would be welcome, quite lost and I am not an iOS expert at all !!!
You can do low-level editing of a PDF in PDFNet. Briefly:
Create a new custom entry (on the document's root):
Obj* cust_dict = [[myPDFDoc GetRoot] PutDict:#"_MyCustomData" ];
[cust_dict PutText:#"_myGUID" value:#"123-4567-890"];
Read the custom entry:
Obj* dict = [[myPDFDoc GetRoot] FindObj:#"_MyCustomData"];
DictIterator* itr = [dict Get:#"_myGUID"];
Obj* strObj = [itr Value];
NSString* str = [strObj GetAsPDFText];
NSLog(#"guid is %#", str);
Delete a custom entry:
[[myPDFDoc GetRoot] EraseDictElementWithKey:#"_MyCustomData"];
You could also place metadata on a page's root, or in a more standard location, as outlined here: https://groups.google.com/d/msg/pdfnet-sdk/gtPjLZVbRSQ/Tv5DTb9pRXkJ
For more specific information about adding XMP metadata (as your tag implies you're interested in), try searching XMP on the PDFNet support forum: https://groups.google.com/forum/#!searchin/pdfnet-sdk/XMP
I'm not sure how you would do this with Quartz.
Disclosure: I work for PDFTron, maker of PDFNet.

NSString with Cyrillic to UTF8/Latin encoding

I have a string coming in from a web service, it's a mixture of Cyrillic and Latin/English characters. When building an array by separating the words in the sentence it show's the unicode in place of the letters when using NSLog. I want to know how to convert any of the cyrillic/unicode characters to a proper readable latin/english word. For example..
NSString *sentence = #"The Tobе Elіte"; (e in Tobe is Cyrillic, and i in Elite)
After putting each word in the string into an array, when printing I get this:
(
The,
"Tob\U0435",
"El\U0456te"
)
I need this to transliterate to latin "Tobe" and latin "Elite". If I try comparing what I have now by doing
if(![#"Tobe" isEqualToString:[array objectAtIndex:1]])
//Tobe is not Equal to Tob\U0435
I do apologize if I explained this horribly, if you have any questions to help better understand my problem feel free to ask. I have tried several things to get this encoded to proper UTF8. For example, this does not work:
NSMutableString *buffer = [string mutableCopy];
CFMutableStringRef bufferRef = (__bridge CFMutableStringRef)buffer;
CFStringTransform(bufferRef, NULL, kCFStringTransformToLatin, false);
Ultimately I need to search the array for matching words by using NSPredicate, but with the Unicode in the array it does not allow me to do so. Any help is appreciated.
This works for me:
NSString *sentence = #"The Tobе Elіte";
NSMutableString *buffer = [sentence mutableCopy];
CFMutableStringRef bufferRef = (__bridge CFMutableStringRef)buffer;
CFStringTransform(bufferRef, NULL, kCFStringTransformToLatin, false);
CFStringTransform(bufferRef, NULL, kCFStringTransformStripDiacritics, false);
NSArray *arr = [buffer componentsSeparatedByString:#" "];
NSLog(#"%#", arr);
and you can find some more info here:
http://nshipster.com/cfstringtransform/

how to show image on email body - using sksmtplibrary

I have a html content as my email body. I need show an image on my html body. I have tried attaching the image to email and used the filename in html image tag. But the image is not showing. I have also tried using dataUri, which doesnt work in certain email clients.
This is my code.
NSData * imageData = [[NSDataalloc] initWithContentsOfURL: [NSURLURLWithString: #"http://wf.vanillicon.com/f6f63a5a0d149275772ff1cf22595988_100.png"]];
NSString *strFileName = [NSStringWithFormat:#"MyPicture.png"];
NSString *strFormat = [NSStringWithFormat:#"image/png;\r\n\tx-unix-mode=0644;\r\n\tname=\"%#\"",strFileName];
NSString *strFormat2 = [NSStringWithFormat:#"attachment;\r\n\tfilename=\"%#\"",strFileName];
NSDictionary *vcfPart = [NSDictionarydictionaryWithObjectsAndKeys:strFormat,kSKPSMTPPartContentTypeKey,
strFormat2,kSKPSMTPPartContentDispositionKey,[imageData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArrayarrayWithObject:vcfPart];
NSDictionary *plainPart = [NSDictionarydictionaryWithObjectsAndKeys:#"text/html",kSKPSMTPPartContentTypeKey,
#"<img src=\"MyPicture.png\" width=\"100px\" height=\"100px\" /><h1>Tui</h1>",kSKPSMTPPartMessageKey,
#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
testMsg.parts = [NSArrayarrayWithObjects:plainPart,vcfPart,nil];
find out demo codes of email sending via SMPT from below links
https://code.google.com/p/skpsmtpmessage/source/browse/trunk/SMTPSender/Classes/SMTPSenderAppDelegate.m
or
https://github.com/kailoa/iphone-smtp
or
http://iphonesdksnippets.com/post/2009/04/15/Send-email-with-attachments-on-iPhone.aspx
you may be succeed
Sometimes, when you send an HTML email, and you have an image in a tag in that HTML, the email client on the receiving side won't display the images automatically. You may have to click "Show images" on the email.

Using Placeholders Within NSDictionary Strings On iOS

I am trying to make a dictionary for Facebook posting, and trying to figure out how to use placeholders in my string. I currently have:
NSDictionary *parameters = #{#"message" : #"I'm reading today.", #"caption": (#"I'm on %#", _entry.date), #"link": _entry.articleUrl};
_entry.date is a string that displays which day of reading the user is on, and _entry.articleUrl is a string for the page the user is reading. My issue is getting the correct format so that the string used for caption can have text and a placeholder for the string. Right now it tells me the expression result is unused.
try this string api to build your string:
NSDictionary *parameters = #{#"message" : #"I'm reading today.", #"caption": [NSString stringWithFormat:#"I'm on %#", _entry.date], #"link": _entry.articleUrl};

iOS : How to do proper URL encoding?

I'm unable to open a URL into UIWebView so I've seached & found that I need to encode URL, so I tried to encode it but, I've facing problem in URL encoding : My URL is http://somedomain.com/data/Témp%20Page%20-%20Open.html (It's not real URL).
I'm concerned with %20 that I tried to replace using stringByReplacingOccuranceOfString:#"" withString:#"" , it give me the URL I wanted like http://somedomain.com/data/Témp Page - Open.html However its not opening in UIWebView but amazingly it opens in Safari & FireFox perfect. Even I open unencoded URL its automatically converts and open the page I'm looking for.
I've google for URL encoding & it points me to different results I already checked but no results help me out!! I tried different functions answers in different URL encoding question but it just changed all special characters and make my URL like, http%3A%2F%2Fsomedomain.com%2Fdata%2FT... which can't open in UIWebView and even in any browser.
It gives the following Error Log in UIWebView delegate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error { }
Error Code : 101
& Description : Error Domain=WebKitErrorDomain Code=101 "The operation couldn’t be completed. (WebKitErrorDomain error 101.)" UserInfo=0x6e4cf60 {}
The answer #Dhaval Vaishnani provided is only partially correct. This method treats the ?, = and & characters as not to be encoded, since they're valid in an URL. Thus, to encode an arbitrary string to be safely used as a part of an URL, you can't use this method. Instead you have to fall back to using CoreFoundation and CFURLRef:
NSString *unsafeString = #"this &string= confuses ? the InTeRwEbZ";
CFStringRef safeString = CFURLCreateStringByAddingPercentEscapes (
NULL,
(CFStringRef)unsafeString,
NULL,
CFSTR("/%&=?$#+-~#<>|\\*,.()[]{}^!"),
kCFStringEncodingUTF8
);
Don't forget to dispose of the ownership of the resulting string using CFRelease(safeString);.
Also, it seems that despite the title, OP is looking for decoding and not encoding a string. CFURLRef has another, similar function call to be used for that:
NSString *escapedString = #"%32%65BCDEFGH";
CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding (
NULL,
(CFStringRef)escapedString,
CFSTR(""),
kCFStringEncodingUTF8
);
Again, don't forget proper memory management.
I did some tests and I think the problem is not really with the UIWebView but instead that NSURL won't accept the URL because of the é in "Témp" is not encoded properly. This will cause +[NSURLRequest requestWithURL:] and -[NSURL URLWithString:] to return nil as the string contains a malformed URL. I guess that you then end up using a nil request with -[UIViewWeb loadRequest:] which is no good.
Example:
NSLog(#"URL with é: %#", [NSURL URLWithString:#"http://host/Témp"]);
NSLog(#"URL with encoded é: %#", [NSURL URLWithString:#"http://host/T%C3%A9mp"]);
Output:
2012-10-02 12:02:56.366 test[73164:c07] URL with é: (null)
2012-10-02 12:02:56.368 test[73164:c07] URL with encoded é: http://host/T%C3%A9mp
If you really really want to borrow the graceful handling of malformed URLs that WebKit has and don't want to implement it yourself you can do something like this but it is very ugly:
UIWebView *webView = [[[UIWebView alloc]
initWithFrame:self.view.frame]
autorelease];
NSString *url = #"http://www.httpdump.com/texis/browserinfo/Témp.html";
[webView loadHTMLString:[NSString stringWithFormat:
#"<script>window.location=%#;</script>",
[[[NSString alloc]
initWithData:[NSJSONSerialization
dataWithJSONObject:url
options:NSJSONReadingAllowFragments
error:NULL]
encoding:NSUTF8StringEncoding]
autorelease]]
baseURL:nil];
The most straightforward way is to use:
NSString *encodedString = [rawString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
iDhaval was close, but he was doing it the other way around (decoding instead of encoding).
Anand's way would work, but you'll most likely have to replace more characters than spaces and new lines. See the reference here:
http://en.wikipedia.org/wiki/Percent-encoding#Percent-encoding_reserved_characters
Hope that helps.
It's very simple to encode the URL in iPhone. It is as following
NSString* strURL = #"http://somedomain.com/data/Témp Page - Open.html";
NSURL* url = [NSURL URLWithString:[strURL stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
It's a perfect way to encode the URL, I am using it and it's perfectly work with me.
Hope it will help you!!!
This may useful to someone who's reach to this question for URL encoding, as my question likely different which has been solved and accepted, this is the way I used to do encoding,
-(NSString *)encodeURL:(NSString *)urlString
{
CFStringRef newString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)urlString, NULL, CFSTR("!*'();:#&=+#,/?#[]"), kCFStringEncodingUTF8);
return (NSString *)CFBridgingRelease(newString);
}
You can try this
NSString *url = #"http://www.abc.com/param=Hi how are you";
NSString* encodedUrl = [url stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
I think this will work for you
[strUrl stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]
the Native method for URL Encoding.
Swift 4.x
let originalString = "https://www.somedomain.com/folder/some cool file.jpg"
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
print(escapedString!)
You probably need to break the URL down into it's constituent parts and then URL encode the host and path but not the scheme. Then put it back together again.
Create an NSURL with the string and then use the methods on it such as host, scheme, path, query, etc to pull it apart. Then use CFURLCreateStringByAddingPercentEscapes to encode the parts and then you can put them back together again into a new NSURL.
can you please Try this out.
//yourURL contains your Encoded URL
yourURL = [yourURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
yourURL = [yourURL stringByReplacingOccurrencesOfString:#"\n" withString:#""];
NSLog(#"Keyword:%# is this",yourURL);
I am not sure,but I have solved using this in my case.
Hope this will solve yours.

Resources