PHP in the pattern of generating images, similar to the long microblog image generator

Source: Internet
Author: User
PHP in the way the page generated images, similar to the long microblog image generator

Introduction: Due to media station microblogging communication needs, in the forward article to Sina Weibo can be the text of the article has been the image of the form of dissemination, to improve the content of the microblogging initiative, GU need in the original PHP project code to add the page to the picture function.

?

In the Java Web page to the picture has the open source conversion tool, is relatively simple, PHP in the Web page to the picture the open Source tool to be few, only then has only one semi-finished product (only through the command line invocation, cannot use the PHP code Generation) Html2image (HTTP/ www.guangmingsoft.net/htmlsnapshot/html2image.htm), no way, the habit of directly in the code to unify the use of pure language code implementation, so continue Google, and then found a solution: HTML "PDF" Image (Source: http://buffernow.com/), it has to be said that this scheme is very familiar with PHP to be able to get the situation.

?

Originally intended to use his open source program directly, but in the application process found that there is a problem: No Chinese fonts, add Chinese fonts after the whole paragraph of the Chinese page in the picture only one line, the other content can not be displayed.

?

This is to force me to study his open source code of the festival, but fortunately, the meaning of this open source project is to confirm the HTML "PDF" image scheme is feasible.

?

Take apart his code to see, found the problem in the HTML page generated PDF stage, because the author rewritten the Tcpdf scheme formed the html2pdf Open source package, but not well rewritten, the Chinese support is not enough, so abandoned the author's open source framework, Convert HTML to PDF and go to image directly using stable tcpdf and Imagick.

?

This process is slightly difficult ah (PHP has not been formally studied, usually pick up the project on the start, what to check what), from noon to 2 o'clock, a full 14 hours ah, my God, I think it is necessary to summarize, to avoid the next encounter the same scene and forget.

?

Let's start now:

?

1. The project adopts the mature open source scheme: tcpdf (http://www.tcpdf.org/index.php), Imagick (a library of PHP, similar to the GD library, need to install the library file at the operating system level, and need to join the dynamic link library in php.ini )。

?

2. First need to generate HTML PDF: here to pay attention to the processing of Chinese, Chinese garbled in countless places have appeared, need to ensure that all the data exchange are using the UTF8 character set, where the HTML using FCKeditor through post submitted, First is the need to set the Web server to receive characters UTF8, followed by new tcpdf when you need to set the encoding to Chinese,

$pdf = new TCPDF (pdf_page_orientation, Pdf_unit, Pdf_page_format, True, ' UTF-8 ', false);

?

?

3.tcpdf default does not contain Chinese font (Chinese to rise ah, have to do a bit big World general project, then do not put Japanese font, German font what, haha), can be used in a lot of Chinese font, the most use of the net is the Droid Sans fallback font , so I used the Droid Sans fallback font, either directly download the tcpdf version of the font (three files), or download TTF fonts, and then use the Tcpdf tool to generate three files , the way See 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 code is correct, ready to start, but the official only case, no document, and most of the case is a little bit of HTML code to write to the Tcpdf object, and I need to write a piece of HTML directly, and then generate a PDF document, so need to reference case to streamline the code

?

5.html When you create a PDF, you need to be aware that improper font settings can affect the process of creating images behind a PDF, which in this project has been plagued by 4 hours, Droid Sans is a font set, there are two ways to set up a PDF font, one is to only write the font description information to the PDF document, the PDF reading tool when parsing from the tool's own font library or system to introduce the corresponding font to display the document, Therefore, the PDF document will be small, the font is set to ' Stsongstdlight ', and the font file is also saved to the PDF document when the font is set, even if the PDF reading tool or the system does not have the font to parse and display the document, so the document will be larger, at this time the font is set to ' Droidsansfallback '; because you just started font settings ' stsongstdlight', resulting in the subsequent use of Imagick from the PDF generation of images can never be generated; then various control variable method, step by step to find the reason, the final positioning to the font location, font ' stsongstdlight' led to the inability to generate images, the completed Google guidelines found that the Droid sans fonts are set up in two ways, Try two more settings to set the font to find a PDF document generated when the font is set to ' Droidsansfallback ' to generate a picture "Here I feel is the missing Droid sans font library on the server, if the can the Droid Sans font library be installed on the server to generate pictures as well? Because the project was late, so did not go to research "

?

6. The HTML code written to the Tcpdf object must be a code that is error-free and conforms to the HTML specification, otherwise tcpdf will error, and the HTML code normally generated by FCKeditor will escape the double quotes, causing "to \", which cannot be tcpdf recognized. So you need to remove the escape character \

?

7. Image copyright: The generated image needs to add a product watermark, both in the PDF generation of the image link can be added in the HTML generation PDF phase, the individual think the PDF creation phase is more simple to add, in this project due to the time relationship, I simply added a Web site identifier at the end of the HTML (because the PDF was generated in HTML format, so you can modify the HTML format to make the resulting PDF more aesthetically pleasing and more relevant to the watermark).

?

OK, so this HTML generated PDF document is successful, the code is as follows:

$pdf = new TCPDF (pdf_page_orientation, Pdf_unit, Pdf_page_format, True, ' UTF-8 ', false); $pdf->setcreator (pdf_ CREATOR); $pdf->setmargins (Pdf_margin_left, Pdf_margin_top, pdf_margin_right); $pdf->setautopagebreak (TRUE, Pdf_margin_bottom), $pdf->setimagescale (pdf_image_scale_ratio), $pdf->addpage (); $pdf->setfont (' Droidsansfallback ', ', '), $testhtml =str_replace ("\ \", "", $html). '
NET: www.diggg.com.cn '; $pdf->writehtml ($testhtml, True, 0, True, true); $pdf->lastpage (); $pdf->output ($ config[' Webroot ']. ' /temp/temp '. $id. PDF ', ' f ');

? Next we'll start using Imagick to generate the PDF image

?

8. First prepare the Imagick system environment to install the Imagick system installation package (see Window http://www.gretheer.com/2013/09/ Installing-imagemagick-on-windows-and-using-with-php-imagick.html,linux directly with Yum installation), open the command line after successful installation enter convert to see if it performs properly Second, you have to install PHP dynamic link library, this is the most troublesome stage, the dynamic link library must and the operating system version, PHP version consistent, otherwise can not be used, the tragedy is the landlord with PHP is wampp3.2.1 PHP, version is 5.4.16, operating system is WINDOW7 64 bits, Google did not find a normal installation of the Imagick Dynamic library, after spending 2 hours, I gave up on the window7 on the local debugging work, directly on the CENTOS6 server installed Imagick, Results The Imagick Dynamic Library on CentOS was successfully integrated into PHP. Under this spit slot: This PHP dynamic library is really troublesome, the compatibility is too poor

?

The official tutorial address for 9.imagick (http://www.php.net/manual/zh/ book.imagick.php), in fact, the function of Imagick is very powerful, but related to the function of the document is too small, the time relationship can not be a method of a method of the attempt, only Google get what I need to start with the simplest code to implement functions such as

?

$img = new Imagick ($pdf _file), $img->setimageformat (' jpg '), $img->writeimage ($save _to);

The picture can be generated normally, but the picture contains only the contents of the last page of the PDF, and if the PDF is a single-page operation, but if the PDF is multi-page, this is not the case, because there is no related document, at first, since you can put the content of the last page of the PDF to generate pictures, Then you can make all the pages of the picture, and then use the picture library to put together the pictures

?

Code thought wrote

1. Get the number of pages in the PDF [$Image = new Imagick ($pdfpath. PDF '); $num _page = $Image->getnumberimages ();]
2. Create a picture of each page [$Image = new Imagick ($pdfpath. PDF "[i])]
3. Get the height of each page picture and add the height of the canvas to be used for subsequent flattened pictures
4. Create a new canvas
5. Write the picture to the canvas, note the starting coordinates of the picture in the canvas, the horizontal axis is 0, the vertical axis is the height of the front several pictures and
6. Close the canvas and export the picture file

? After writing the code, it is found that there is a direct multi-page PDF directly generated images of the method, tragedy Ah, took so long time, incredibly there is a simpler way, well, of course, the use of simple ideas

?

$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 ();

?

?

?

Well, to this HTML to generate the picture the whole process is complete

? The complete code:

The picture of the cached body include_once ($config [' Webroot ']. "                /tcpdf/tcpdf.php "); $pdf = new TCPDF (pdf_page_orientation, Pdf_unit, Pdf_page_format, True, ' UTF-8 ', false); $pdf->setcreator (pdf_ CREATOR); $pdf->setmargins (Pdf_margin_left, Pdf_margin_top, pdf_margin_right); $pdf->setautopagebreak (TRUE, Pdf_margin_bottom), $pdf->setimagescale (pdf_image_scale_ratio), $pdf->addpage (); $pdf->setfont (' Droidsansfallback ', ', '), $testhtml =str_replace ("\ \", "", $con). '
NET: www.diggg.com.cn '; $pdf->writehtml ($testhtml, True, 0, True, true); $pdf->lastpage (); $pdf->output ($ config[' Webroot ']. ' /temp/temp '. $id. PDF ', ' f '); $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 (); unlink ($pdfpath);// End of Cache

?

  • Related Article

    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.