Convert HTML to PDF using uiprintpagerenderer

Source: Internet
Author: User

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

  1. @ Implementation kyprintpagerenderer
  2. -(Cgrect) paperrect
  3. {
  4. If (! _ Generatingpdf)
  5. Return [Super paperrect];
  6. Return uigraphicsgetpdfcontextbounds ();
  7. }
  8. -(Cgrect) printablerect
  9. {
  10. If (! _ Generatingpdf)
  11. Return [Super printablerect];
  12. Return cgrectinset (self. paperrect, 20, 20 );
  13. }
  14. -(Nsdata *) printtopdf
  15. {
  16. _ Generatingpdf = yes;
  17. Nsmutabledata * response data = [nsmutabledata data];
  18. Uigraphicsbegin1_contexttodata (partition data, cgrectmake (0, 0,792,612), nil); // letter-size, landscape
  19. [Self preparefordrawingpages: nsmakerange (0, 1)];
  20. Cgrect bounds = uigraphicsget?contextbounds ();
  21. For (INT I = 0; I <self. numberofpages; I ++)
  22. {
  23. Uigraphicsbeginpdfpage ();
  24. [Self drawpageatindex: I inrect: bounds];
  25. }
  26. Uigraphicsendencryption context ();
  27. _ Generatingpdf = no;
  28. Return response data;
  29. }

We still use webview to load HTML, but this time we use kyprintpagerenderer (pprenderer is its instance) to generate PDF:
Copy code

    1. Uiviewprintformatter * viewformatter = [htmlwebview viewprintformatter];
    2. [Pprenderer addprintformatter: viewformatter startingatpageatindex: 0];
    3. Nsdata * upload data = [pprenderer printtopdf];
    4. Nsstring * pdfpath = [nshomedirectory () stringbyappendingpathcomponent: @ "Documents/testpackages"];
    5. [Export data writetofile: pdfpath atomically: Yes];

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.