Php web page generation Image mode, similar to long Weibo Image generator

Source: Internet
Author: User
In php, images are generated on webpages, similar to long Weibo Image Generators. Reading Guide: due to the Media Station's Weibo communication needs, the article body must be transmitted in the form of images when it is forwarded to Sina Weibo, to improve the enthusiasm of Weibo content forwarding, you need to add the webpage conversion function to the original php project code .? In java, there are open-source conversion tools for webpage conversion to images, which are relatively simple. in php, there are few open-source tools for webpage conversion to images, and there is only one half-product (which can only be called through command lines, you cannot use the p php web page to generate images, similar to the long Weibo Image generator.

Reading: due to the needs of media station Weibo, when forwarding an article to Sina Weibo, the text of the article must be transmitted in the form of images to improve the enthusiasm of Weibo content forwarding, you need to add the webpage conversion function to the original php project code.

?

In java, there are open-source conversion tools for webpage conversion to images, which are relatively simple. in php, there are few open-source tools for webpage conversion to images, and there is only one half-product (which can only be called through command lines, unable to use php code generation) html2image (http://www.guangmingsoft.net/htmlsnapshot/html2image.htm), no way, used to unified use of pure language code in the code implementation, so continue google, and then found a solution: html pdf image (source: http://buffernow.com/), have to say this solution is very familiar with php in order to get.

?

I originally intended to directly use his open-source solution, but I found a problem in the application process: no Chinese font. after adding a Chinese font, only one line of Chinese text in the entire section of the webpage is displayed in the image, other content cannot be displayed.

?

This is to force me to study his open-source code, but fortunately, the significance of this open-source project is to prove that the html pdf image solution is feasible.

?

Looking at the code, we found that the problem lies in the html web page pdf generation phase. The author adapted the tcpdf solution to form the html2pdf open-source package, but it was not well adapted and not enough support for Chinese, as a result, the author's open-source framework is abandoned, and the stable tcpdf and imagick are directly used to convert html to pdf and then to image.

?

This process is a little difficult (php has never been formally studied, and it usually starts work when it picks up the project and uses what to check). It lasted for 14 hours from noon till pm, my God, I think it is necessary to sum up to avoid forgetting the same scenario next time.

?

Start now:

?

1. mature open-source solutions used by the project: tcpdf (http://www.tcpdf.org/index.php), imagick (a php library, similar to the gd Library, need to install the library file at the operating system level, at the same time in php. ini ).

?

2. first, you must generate html pdf files. here, you must note that Chinese characters are processed. Chinese characters are garbled in numerous places. make sure that all data exchanges use the utf8 character set, here, html is submitted using fckeditor through post. First, you need to set utf8 as the web server receiving character, and then set Chinese as the encoding when new tcpdf is used,

$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

?

?

3. tcpdf does not contain Chinese fonts by default (the Chinese are about to rise, so we have to make a world-wide project, so we will not release Japanese or German fonts, haha ), there are many Chinese character libraries available for use, and the most used for online data transfer isDroid SansFallback font, so I can useDroid SansFallback font, both can directly download the tcpdf version of the font (three files), you can also download the ttf font, and then use tcpdf tool to generate three files, see the http://www.5eyi.com/php-to-generate-pdf-the-perfect-support-for-the-chinese-to-address-the-garbage-tcpdf/

?

4. the font is ready, the encoding is correct, and the preparation is started. However, there are only official cases and no documents. in this case, most of them are multipart html code that is written to the tcpdf object a little bit, what I need is to write a piece of html directly and then generate a pdf document. Therefore, we need to refer to the case to streamline the code.

?

When generating a pdf file in 5.html, you must note that improper font setting will affect the process of generating the image in the following pdf file. in this transformation project, it has been plagued by four hours,Droid SansIt is a font set. There are two ways to set the pdf Font. one is to write the font description information only to the pdf document, when parsing the pdf reading tool, the corresponding font will be introduced from the tool's own library or system to display the document. Therefore, the pdf document will be relatively small, and the font will be set to 'stsonststmdlight '; another method is to save the font file to the pdf file at the same time when setting the font. even if the font is not found in the pdf reading tool or system, the document can still be parsed and displayed, so the document will be relatively large, in this case, set the font to 'droidsansfallback'. because the font is set to 'stsonstdlight' at the beginning, the image cannot be generated when imagick is used to generate an image from a pdf file. then, various control variables are used, find the cause step by step, and finally locate the font location. the font 'stsonststmdlight' causes the image to fail to be generated. following the instructions on google, we found that the Droid Sans font can be set in two ways, try setting the font in two ways to find the font generated when it is set to 'droidsansfallback '. Pdf files can generate images. [I feel that the Droid Sans Library is missing on the server. can I generate images if I install the Droid Sans library on the server? The project is very late, so no research is conducted]

?

6. the html code written to the tcpdf object must be correct and conform to the html specification. otherwise, tcpdf reports an error. Generally, the html code generated by fckeditor will escape double quotation marks, this will cause "to become \". This escape cannot be recognized by tcpdf, so you need to remove the escape character \

?

7. image copyright: The product watermark must be added to the generated image. you can add the product watermark either in the pdf generation Image process or in the html generation pdf phase, I personally think it is easier to add a pdf file at the creation stage. due to the time relationship, I simply added a website ID at the end of the html file (because the pdf file is generated in html format, therefore, you can modify the html format to make the generated pdf more beautiful and watermark more appropriate ).

?

Now, the html file is successfully generated. the code is as follows:

$ Pdf = new TCPDF (pai_page_orientation, pai_unit, pai_page_format, true, 'utf-8', false); $ pdf-> SetCreator (pai_creator); $ pdf-> SetMargins (pai_margin_left, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $ pdf-> SetAutoPageBreak (TRUE, PDF_MARGIN_BOTTOM); $ pdf-> setImageScale (pai_image_scale_ratio); $ pdf-> AddPage (); $ pdf-> SetFont ('droidsansfallback', '', 16); $ testhtml = str_replace (" \ "," ", $ html ).'

Dige.com: www.diggg.com.cn

'; $ Pdf-> writeHTML ($ testhtml, true, 0, true, true); $ pdf-> lastPage (); $ pdf-> Output ($ config ['webroot']. '/temp/temp'.mongoid.'hangzhou', 'F ');

? Next we will start to use imagick to generate an image in pdf.

?

8. first, you have to prepare the imagick system environment, install the imagick system installation package (for Windows, see the composer), and open the command line and enter convert to check whether the installation is normal. second, you have to install the php dynamic link library, this is the most troublesome stage. the dynamic link library must be consistent with the operating system version and php version. Otherwise, it cannot be used. The tragedy is that the php used by the landlord is the php included in wampp3.2.1, the version is 5.4.16, the operating system is window7 64-bit, and google cannot find the imagick dynamic library that can be installed normally. After two hours, I gave up local debugging on window7, imagick is directly installed on the centos6 server. as a result, the imagick dynamic library on centos is successfully integrated. To php. In this example, this php dynamic library is really troublesome and has poor compatibility.

?

9. imagick official tutorial address (http://www.php.net/manual/zh/book.imagick.php), in fact, imagick function is very powerful, but the relevant function Introduction Documentation is too little information, time relationship can not be a method of a try, only google can get what I need. the simplest code implementation function is as follows:

?

$img = new imagick($pdf_file);$img->setImageFormat('jpg');$img->writeImage($save_to);

? The image can be generated normally, but the image only contains the content of the last page of the pdf. if the pdf is a single page, you can do this, but if the pdf is multi-page, this method is not applicable, because there is no relevant document, since we can generate an image for the last page of the pdf at the beginning, we can certainly generate an image for all pages and then splice the image with the image library.

?

Code thought writing

1. obtain the number of pdf pages [$ Image = new imagick($pdfpath.'hangzhou'); $ num_page = $ Image-> getnumberimages ();]
2. generate an Image for each page [$ Image = new imagick($pdfpath.'shanghai' [I])]
3. get the height of each page of the image and add it together to get the height of the canvas to be used for image combination.
4. create a canvas
5. write the image into the canvas in sequence. Note the starting coordinates of the image in the canvas. the horizontal coordinates are 0, and the vertical coordinates are the sum of the heights of the images on the front.
6. close the canvas and output the image file.

? After writing the code, I found that there was a way to directly generate images from multiple pages of pdf files. it took a long time to create a simpler method. well, of course we should adopt a simple approach.

?

$pdfpath=$config['webroot'].'/temp/temp'.$id.'.pdf';$im = new Imagick();$im->readImage($pdfpath);$im -> resetIterator();$imgs = $im->appendImages(true);$imgs->setImageFormat( "jpg" );$img_name = $id.'.jpg';$imgs->writeImage( $config['webroot']."/temp/".$img_name);$imgs->clear();$imgs->destroy();$im->clear();$im->destroy();

?

?

?

Now, the entire process of generating html images is complete.

? Complete code:

// Cache the image include_once ($ config ['webroot']. "/tcpdf. php "); $ pdf = new TCPDF (pai_page_orientation, pai_unit, pai_page_format, true, 'utf-8', false); $ pdf-> SetCreator (pai_creator ); $ pdf-> SetMargins (pai_margin_left, pai_margin_top, pai_margin_right); $ pdf-> SetAutoPageBreak (TRUE, PDF_MARGIN_BOTTOM); $ pdf-> setImageScale (latency ); $ pdf-> AddPage (); $ pdf-> SetFont ('droidsansfallback', '', 16); $ testhtml = str_replace ("\\","", $ con ).'

Dige.com: www.diggg.com.cn

'; $ Pdf-> writeHTML ($ testhtml, true, 0, true, true); $ pdf-> lastPage (); $ pdf-> Output ($ config ['webroot']. '/temp/temp'.mongoid.'hangzhou', 'F'); $ pdfpath = $ config ['webroot']. '/temp/temp'.$id.'hangzhou'; $ im = new Imagick (); $ im-> readImage ($ pdfpath); $ im-> resetIterator (); $ imgs = $ im-> appendImages (true); $ imgs-> setImageFormat ("jpg"); $ img_name = $id.'.jpg '; $ imgs-> writeImage ($ config ['webroot']. "/temp /". $ img_name); $ imgs-> clear (); $ imgs-> destroy (); $ im-> clear (); $ im-> destroy (); unlink ($ pdfpath); // The cache ends.

?

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.