Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 讨论在PHP中如何把带有HTML内容的文字生成图片

讨论在PHP中如何把带有HTML内容的文字生成图片

Jun 20, 2016 pm 12:42 PM

比如:

 <div>        <font color="red">文字信息</font><br>        <font>换行</font> </div>
Copy after login


这样一段HTML代码,如何保持他的格式,生成一张图片


回复讨论(解决方案)

可能的现成途径:
1、使用 java 的 html2image
2、使用 TCPDF 生成 pdf 然后...
3、使用 php 的截屏函数 imagegrabscreen、imagegrabwindow

我补充一个
https://zh.wikipedia.org/wiki/Webkit
https://en.wikipedia.org/wiki/Webkit

楼上的连接无法访问

还可以用 dompdf
先 define('DOMPDF_PDF_BACKEND', 'gd'); 就可生成图片

"无法访问"请允许我做一个233的表情..........

额,表示如何?

示例

define('DOMPDF_PDF_BACKEND', 'gd');require_once("dompdf_config.inc.php");$html =<<< HTML<meta http-equiv="Content-Type" content="text/html; charset=gbk"><div>        <font color="red">文字信息</font><br>        <font>换行</font> </div>HTML;$dompdf = new DOMPDF();$dompdf->load_html($html);$dompdf->render();$dompdf->stream('');
Copy after login
Copy after login

dompdf 的下载地址
http://code.google.com/p/dompdf/downloads/list

示例

define('DOMPDF_PDF_BACKEND', 'gd');require_once("dompdf_config.inc.php");$html =<<< HTML<meta http-equiv="Content-Type" content="text/html; charset=gbk"><div>        <font color="red">文字信息</font><br>        <font>换行</font> </div>HTML;$dompdf = new DOMPDF();$dompdf->load_html($html);$dompdf->render();$dompdf->stream('');
Copy after login
Copy after login


版主我在问一下哈, 我在本地试了试,为什么没有看到生成的图片呢,也没有提示错误

不同版本的 dompdf 会有不同的表现(我这是 dompdf.php,v 1.24 2009-04-29 的)
它使用 DOMDocument 解析 html
print_r($dompdf->_xml);
可以看到解析是否正常

不同版本的 dompdf 会有不同的表现(我这是 dompdf.php,v 1.24 2009-04-29 的)
它使用 DOMDocument 解析 html
print_r($dompdf->_xml);
可以看到解析是否正常



看到提示错误了
Fatal error: Cannot access protected property DOMPDF::$_xml in G:\AppServ\www\6\1.php on line 16

你的php版本是多少?

_xml 属性的确是保护模式的
dompdf.cls.php 中有
class DOMPDF {
protected $_xml;

但我在 php5.4.12 中依然可以看到
DOMPDF Object
(
[_xml:protected] => DOMDocument Object
(
[doctype] => (object value omitted)
....

你可以将他改为 public 模式的

谢谢版主热心回答
我的php版本是 PHP Version 5.2.6
我下载的dompdf是 @version $Id: dompdf.cls.php 468 2012-02-05 10:51:40Z fabien.menager 应该是最新的

你的php版本是多少?

_xml 属性的确是保护模式的
dompdf.cls.php 中有
class DOMPDF {
protected $_xml;

但我在 php5.4.12 中依然可以看到
DOMPDF Object
(
[_xml:protected] => DOMDocument Object
(
[doctype] => (object value omitted)
....

你可以将他改为 public 模式的

我把xml改成public 里 现在提示错误

DOMDocument Object ( )
Warning: Cannot modify header information - headers already sent by (output started at G:\AppServ\www\6\1.php:16) in G:\AppServ\www\6\include\gd_adapter.cls.php on line 736

Warning: Cannot modify header information - headers already sent by (output started at G:\AppServ\www\6\1.php:16) in G:\AppServ\www\6\include\gd_adapter.cls.php on line 751

看样子是对ssl 也下手了,去掉http后的s应该能访问,webkit也不是什么关键词
http://zh.wikipedia.org/wiki/Webkit
http://en.wikipedia.org/wiki/Webkit

不过 PHP 好像也没webkit

http://www.phpclasses.org/package/7460-PHP-Convert-HTML-to-PDF-using-the-Webkit-engine.html
看看这个有没帮助

你下载的 dompdf 本身应该是没有问题的(这一点你可以通过生成 pdf 加以验证)
由于 dompdf 提供了生成图片的功能,所以也只是在正确生成 pdf 的基础上,通过定义 DOMPDF_PDF_BACKEND 常量将其图片生成的功能调出来而已
至于在测试时修改它的部分代码,这也是出于测试、分析的需要。也当然是自己对修改产生的后果负责


我把xml改成public 里 现在提示错误

DOMDocument Object ( )
Warning: Cannot modify header information - headers already sent by (output started at G:\AppServ\www\6\1.php:16) in G:\AppServ\www\6\include\gd_adapter.cls.php on line 736

Warning: Cannot modify header information - headers already sent by (output started at G:\AppServ\www\6\1.php:16) in G:\AppServ\www\6\include\gd_adapter.cls.php on line 751

谢谢版主的热心回复

不同版本的 dompdf 会有不同的表现(我这是 dompdf.php,v 1.24 2009-04-29 的)
它使用 DOMDocument 解析 html
print_r($dompdf->_xml);
可以看到解析是否正常


可否把你的版本发出来测试一下,用的0.5.2这个版本的测试了,没效果,图片没显示,也没发现有xml支持的

不报错似乎不应该
gd写文字总是需要字体文件的
dompdf的默认字体是 Times-Roman
为此作为测试,你可以将任意一款ttf中文字体复制到 lib/fonts 目录中,并更名为 Times-Roman.ttf

版本声明

<?php/** * DOMPDF - PHP5 HTML to PDF renderer * * File: $RCSfile: dompdf.php,v $ * Created on: 2004-06-22 * * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library in the file LICENSE.LGPL; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * Alternatively, you may distribute this software under the terms of the * PHP License, version 3.0 or later.  A copy of this license should have * been distributed with this file in the file LICENSE.PHP .  If this is not * the case, you can obtain a copy at http://www.php.net/license/3_0.txt. * * The latest version of DOMPDF might be available at: * http://www.digitaljunkies.ca/dompdf * * dompdf.php is a simple script to drive DOMPDF.  It can be executed from * a browser or from the command line. * * @link http://www.digitaljunkies.ca/dompdf * @copyright 2004 Benj Carson * @author Benj Carson <benjcarson@digitaljunkies.ca> * @package dompdf * @version 0.5.1 *//* $Id: dompdf.php,v 1.24 2009-04-29 04:11:35 benjcarson Exp $ */
Copy after login
Copy after login

不报错似乎不应该
gd写文字总是需要字体文件的
dompdf的默认字体是 Times-Roman
为此作为测试,你可以将任意一款ttf中文字体复制到 lib/fonts 目录中,并更名为 Times-Roman.ttf

版本声明

<?php/** * DOMPDF - PHP5 HTML to PDF renderer * * File: $RCSfile: dompdf.php,v $ * Created on: 2004-06-22 * * Copyright (c) 2004 - Benj Carson <benjcarson@digitaljunkies.ca> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library in the file LICENSE.LGPL; if not, write to the * Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * Alternatively, you may distribute this software under the terms of the * PHP License, version 3.0 or later.  A copy of this license should have * been distributed with this file in the file LICENSE.PHP .  If this is not * the case, you can obtain a copy at http://www.php.net/license/3_0.txt. * * The latest version of DOMPDF might be available at: * http://www.digitaljunkies.ca/dompdf * * dompdf.php is a simple script to drive DOMPDF.  It can be executed from * a browser or from the command line. * * @link http://www.digitaljunkies.ca/dompdf * @copyright 2004 Benj Carson * @author Benj Carson <benjcarson@digitaljunkies.ca> * @package dompdf * @version 0.5.1 *//* $Id: dompdf.php,v 1.24 2009-04-29 04:11:35 benjcarson Exp $ */
Copy after login
Copy after login


php版本我更改为php5.4.18了,xml可以正常了
可还是无法显示图片,还是打叉的,我也下的是你上面这个版本* @version 0.5.1了

不过时间是有点区别

* @version 0.5.1
*/

/* $Id: dompdf.php,v 1.17 2006/07/07 21:31:02 benjcarson Exp $ */

是1.17的,不是1.24的,你能把你这个1.24的打包发出来测试下不?

已上传 http://download.csdn.net/detail/xuzuning/5958493

已上传 http://download.csdn.net/detail/xuzuning/5958493


我用了0.6那个版本+php5.2.0可以显示图片了,不过没有显示全部,中文部分没显示定义的数字也没显示

由于 dompdf 使用 DOMDocument 解析 HTML
所以被解析的 HTML 文档中一定要有语言声明

否则将按欧洲语言解析,汉字就不能显示了

使用 php 的截屏函数 imagegrabscreen、imagegrabwindow

这2个函数有谁使用过的没?

由于 dompdf 使用 DOMDocument 解析 HTML
所以被解析的 HTML 文档中一定要有语言声明

否则将按欧洲语言解析,汉字就不能显示了


好像不能随便换字体,你这个貌似跟直接在google下载的有点不一样,要改字体,好像还得改程序

你用我给你的试试

截屏函数只用于 window 系统

刚才下了最新的 0.6
@version $Id: dompdf.php 448 2011-11-13 13:00:03Z fabien.menager $

补上字体文件 Times-Roman.ttf
#6 的代码即可正常运行

刚才下了最新的 0.6
@version $Id: dompdf.php 448 2011-11-13 13:00:03Z fabien.menager $

补上字体文件 Times-Roman.ttf
#6 的代码即可正常运行


是的,用0.6的,不用补字体也正常

不管哪个导出的图片会却像素色

是的,dompdf 的渲染效果很差不过0.6也改进了不少
但比起 tcpdf 来就差的太远了,只是 tcpdf 尚不支持输出图片。改起来也太费劲了

是的,dompdf 的渲染效果很差不过0.6也改进了不少
但比起 tcpdf 来就差的太远了,只是 tcpdf 尚不支持输出图片。改起来也太费劲了


使用过截屏的方法么?

截屏

$im = imagegrabscreen();imagepng($im, "myscreenshot.png");imagedestroy($im);
Copy after login

不过很慢,1440 x 900 大约 十七八秒

由于 php5.4 不再支持 com 了,imagegrabwindow 未作测试

真不如 [Prtsc Sys Rq] 和 [Alt]+[Prtsc Sys Rq] 在粘贴到“画图”中来的快

看了不少资料,感觉php做这个目前确实很薄弱

如果你是在 linux 下,那么你应该可以找到借助浏览器内核做分析的 php 项目

啥意思?html2img?我用c#做过 就是访问一个网址 生成图片

这和验证码生成不是一个原理?

这和验证码生成不是一个原理?


不是

那就可以用webscreencapture.exe之类的PHP截屏软件。


不同版本的 dompdf 会有不同的表现(我这是 dompdf.php,v 1.24 2009-04-29 的)
它使用 DOMDocument 解析 html
print_r($dompdf->_xml);
可以看到解析是否正常


可否把你的版本发出来测试一下,用的0.5.2这个版本的测试了,没效果,图片没显示,也没发现有xml支持的

gd_adapter.cls.php 的751行屏蔽header("Content-type: image/png");這句就報錯了

我測試了一下0.6版,就算排除了所有的錯誤之後對於html的解析還是非常不理想

我測試了一下0.6版,就算排除了所有的錯誤之後對於html的解析還是非常不理想


是的,是很不理想,php这个是个软肋啊

不满意可以改,不想改就自己写
只要对 css 很熟悉的话,做起来并不复杂
用 DOMDocument::loadHTML 载入 html
析出各个元素的属性
计算每个盒子的尺寸和位置 这个比较复杂,需对 css 很熟悉
逐一绘制

不满意可以改,不想改就自己写
只要对 css 很熟悉的话,做起来并不复杂
用 DOMDocument::loadHTML 载入 html
析出各个元素的属性
计算每个盒子的尺寸和位置 这个比较复杂,需对 css 很熟悉
逐一绘制


这个是什么意思?

CSS,我自认还行,你说的用那个可以做到?还是什么?
反正那个我测试了不行

不满意可以改,不想改就自己写
只要对 css 很熟悉的话,做起来并不复杂
用 DOMDocument::loadHTML 载入 html
析出各个元素的属性
计算每个盒子的尺寸和位置 这个比较复杂,需对 css 很熟悉
逐一绘制


主要是生成图片以后就没有了那么多样式了

自己繪製只能繪製一個大概而已,並不能做到完美,看來只能另闢蹊徑藉助瀏覽器的內核了.

不满意可以改,不想改就自己写
只要对 css 很熟悉的话,做起来并不复杂
用 DOMDocument::loadHTML 载入 html
析出各个元素的属性
计算每个盒子的尺寸和位置 这个比较复杂,需对 css 很熟悉
逐一绘制



http://www.tqcp.net/kong_bct.php
你看他这个是如何做到的,他这个就是动态生成图片的哦,格式还很漂亮,究竟PHP怎么做到的?

那是固定格式,用gd很容易做到

那是固定格式,用gd很容易做到



这个怎么实现呢?
我测试过多次都不行的,都是有瑕疵的

给你个示例代码

<?php$im = imagecreatefromstring(get());$ind = vertical($im);//取得垂直分布,用人工分析比较简单$w = imagesx($im);//抽取头部$top_h = 59;$top = imagecreate($w, $top_h);imagecopy($top, $im, 0, 0, 0, 0, $w, $top_h); for($y=6; $y<29; $y++) imagecopy($top, $top, 0, $y, 0, 5, $w, 1);//imagegif($top); exit; //抽取中段(空白的)$middle_h = 29;$middle = imagecreate($w, $middle_h);imagecopy($middle, $im, 0, 0, 0, 59, $w, $middle_h);for($y=2; $y<$middle_h-1; $y++) imagecopy($middle, $middle, 0, $y, 0, 1, $w, 1);//imagegif($middle); exit;//抽取中段(红色分隔线空白的)$middlered_h = 29;$middlered = imagecreate($w, $middlered_h);imagecopy($middlered, $im, 0, 0, 0, 175, $w, $middle_h);for($y=2; $y<$middle_h-1; $y++) imagecopy($middlered, $middlered, 0, $y, 0, 1, $w, 1);//imagegif($middlered); exit;//抽取底部$bottom_h = 41;$bottom = imagecreate($w, $bottom_h);imagecopy($bottom, $im, 0, 0, 0, 318, $w, $bottom_h); //imagegif($bottom); /*至此,我们已经准备好了组装空白彩票的部件。对于你自己的图片,当然是要自己动手画一些了他的组装规则是: 头部 + ((行数 - 1) % 4) * 中段 + ceil((行数 - 1) / 4) * (红线中段 + 3 * 中段)+ 中段 + 底部(底部上压一线)现在就按次规则组装*/$row = 11;$h = $top_h + (($row - 1) % 4) * $middle_h + ceil($row / 4) * 4 * $middle_h + $middle_h - 1 + $bottom_h;$new = imagecreate($w, $h);$y = 0;$k = 0;imagecopy($new, $top, 0, $y, 0, 0, $w, $top_h);$y += $top_h;for($i=0; $i<($row - 1) % 4; $i++, $y+=$middle_h) {  imagecopy($new, $middle, 0, $y, 0, 0, $w, $middle_h);  $k++;}for($i=0; $i<ceil($row / 4) * 4; $i++, $y+=$middle_h) {  if($k++ && $i % 4 == 0) imagecopy($new, $middlered, 0, $y, 0, 0, $w, $middle_h);  else imagecopy($new, $middle, 0, $y, 0, 0, $w, $middle_h);}imagecopy($new, $middle, 0, $y, 0, 0, $w, $middle_h);$y += $middle_h;imagecopy($new, $bottom, 0, $y-1, 0, 0, $w, $bottom_h);imagegif($new);function vertical($im) {  $num = 0;  for($y=0; $y<imagesy($im); $y++) {    $p = imagecolorat($im, 6, $y);    if($y == 0) $last = $p;    if($p != $last && $num) {      $res[$y-$num] = array($last, $num);      $last = $p;      $num = 0;    }    $num++;  }  $res[$y-$num] = array($last, $num);  //print_r($res);//$ind 保存了像素的垂直分布  return $res;}function get($n=5) {  $url = 'http://www.tqcp.net/ct_end.php';  $param = array('nqis' => $n, 'cmdOk' => '确定');  $ch = curl_init();  curl_setopt($ch, CURLOPT_URL,$url);  curl_setopt($ch, CURLOPT_POST, 1);  curl_setopt($ch, CURLOPT_POSTFIELDS, $param);  curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);  $r = curl_exec($ch);  curl_close($ch);  return $r;}
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles