我一直在尝试使用以下代码将 PDF 文件打印到 Google 云打印。它不是实际打印文档,而是仅打印一个显示文件位置和文件名的字符串。我想让它打印实际的文档。
我们可以假设传递给此方法的数据是有效的,因为它似乎从调用云打印/搜索中找到了正确的打印机
更新:代码从其原始格式更新为包含一些多部分表单数据
NSString *currentPDFFileName = [[NSBundle mainBundle] pathForResource:@"TestPDF" ofType:@"pdf"];
NSData *pdfData = [NSData dataWithContentsOfFile:currentPDFFileName];
NSData *validPDF = [[NSString stringWithString:@"%PDF"] dataUsingEncoding: NSASCIIStringEncoding];
if (!(pdfData && [[pdfData subdataWithRange:NSMakeRange(0, 4)] isEqualToData:validPDF]))
{
NSLog (@"Not valid");
}
NSLog (@"%@", currentPDFFileName);
NSLog (@"%@", [currentPDFFileName lastPathComponent]);
//create the body
NSMutableData *body = [NSMutableData data];
//create the POST vars
NSString *thePrinter = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"printerid\"\r\n\r\n%@", printerID];
NSString *pdf = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"content\"; filename=\"%@\"\r\n", [currentPDFFileName lastPathComponent]];
NSString *theContent = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"contentType\"\r\n\r\n%@", contentType];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[thePrinter dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[pdf dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[theContent dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/pdf\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:pdfData];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", @"----foo"] dataUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest *pdfRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/cloudprint/submit"]];
[pdfRequest setValue:@"multipart/form-data; boundary=----foo" forHTTPHeaderField:@"Content-type"];
[pdfRequest setHTTPMethod:@"POST"];
[pdfRequest setHTTPBody:body];
[self.authenticate authorizeRequest:pdfRequest completionHandler:^(NSError *error) {
NSString *output = nil;
if(error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:pdfRequest
returningResponse:&response
error:&error];
if(data) {
output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
} else {
output = [error description];
}
}
NSLog(@"%@", output);
}];