Created
April 2, 2019 05:55
-
-
Save MadeBugs/f7df20525ceb9aca0107441cee19bed2 to your computer and use it in GitHub Desktop.
HTML网页导出PDF文件
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| - (void)htmlExpectToPDF{ | |
| UIViewPrintFormatter *viewPrintFormatter = [self.webView viewPrintFormatter]; | |
| viewPrintFormatter.startPage = 0; | |
| UIPrintPageRenderer *pageRender = [[UIPrintPageRenderer alloc] init]; | |
| [pageRender addPrintFormatter:viewPrintFormatter startingAtPageAtIndex:0]; | |
| CGRect page; | |
| page.origin.x=0; | |
| page.origin.y=0; | |
| page.size.width=600; | |
| page.size.height=768; | |
| CGRect printable=CGRectInset( page, 10, 10 ); | |
| [pageRender setValue:[NSValue valueWithCGRect:page] forKey:@"paperRect"]; | |
| [pageRender setValue:[NSValue valueWithCGRect:printable] forKey:@"printableRect"]; | |
| NSMutableData *pdfData = [NSMutableData data]; | |
| UIGraphicsBeginPDFContextToData(pdfData, CGRectZero, nil); | |
| for (int i = 0; i < pageRender.numberOfPages; i++) { | |
| UIGraphicsBeginPDFPage(); | |
| CGRect bounds =UIGraphicsGetPDFContextBounds(); | |
| [pageRender drawPageAtIndex:i inRect:bounds]; | |
| } | |
| UIGraphicsEndPDFContext(); | |
| NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; | |
| NSString *txtPath = [docPath stringByAppendingPathComponent:@"objc.pdf"]; // 此时仅存在路径,文件并没有真实存在 | |
| [pdfData writeToFile:txtPath atomically:YES]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment