Boss asked me to investigate how to convert HTML to PDF. Google has many methods, such as webview loading, screenshot taking, and conversion.
Report to the boss, and he said that the PDF converted to this form is pure image, and the text cannot be operated on to achieve the desired effect.
But Google continues. As a result, once again understand the strength of stackoverflow, finally found a solution: http://stackoverflow.com/q/9528658/966127
Implementation process: subclass uiprintpagerenderer
Copy code
-
- @ Implementation kyprintpagerenderer
-
-
- -(Cgrect) paperrect
-
- {
-
- If (! _ Generatingpdf)
-
- Return [Super paperrect];
-
-
- Return uigraphicsgetpdfcontextbounds ();
-
- }
-
-
-
- -(Cgrect) printablerect
-
- {
-
- If (! _ Generatingpdf)
-
- Return [Super printablerect];
-
- Return cgrectinset (self. paperrect, 20, 20 );
-
- }
-
-
-
- -(Nsdata *) printtopdf
-
- {
-
- _ Generatingpdf = yes;
-
-
- Nsmutabledata * response data = [nsmutabledata data];
-
-
- Uigraphicsbegin1_contexttodata (partition data, cgrectmake (0, 0,792,612), nil); // letter-size, landscape
-
-
- [Self preparefordrawingpages: nsmakerange (0, 1)];
-
-
- Cgrect bounds = uigraphicsget?contextbounds ();
-
-
- For (INT I = 0; I <self. numberofpages; I ++)
-
- {
-
- Uigraphicsbeginpdfpage ();
-
- [Self drawpageatindex: I inrect: bounds];
-
- }
-
-
- Uigraphicsendencryption context ();
-
-
- _ Generatingpdf = no;
-
-
- Return response data;
-
- }
|
We still use webview to load HTML, but this time we use kyprintpagerenderer (pprenderer is its instance) to generate PDF:
Copy code
- Uiviewprintformatter * viewformatter = [htmlwebview viewprintformatter];
- [Pprenderer addprintformatter: viewformatter startingatpageatindex: 0];
- Nsdata * upload data = [pprenderer printtopdf];
- Nsstring * pdfpath = [nshomedirectory () stringbyappendingpathcomponent: @ "Documents/testpackages"];
- [Export data writetofile: pdfpath atomically: Yes];