php数据导出pdf文件

一.导出pdf文件,首先要安装相关的类库文件,我用的是dompdf类库。

 1.安装类库文件:

composer require dompdf/dompdf

2.引入类库文件到你的控制器中,创建方法:

    public function generatePdf(){//你需要打印的查询内容$data = ['name' => '烦烦烦','content' => '哈哈哈计划经济','img' => 'https:://www.tupian.com/upload/name.png'];// 实例化 Dompdf 对象$options = new Options();// 重点设置字体$options->setDefaultFont('SimSun');$dompdf = new Dompdf($options);// 设置 HTML 内容$html = $this->getPdfContent($list); // 自定义获取数据并生成 HTML 的方法// 加载 HTML 到 Dompdf$dompdf->loadHtml($html);$dompdf->setPaper('A4', 'portrait');// 渲染 PDF$dompdf->render();// 输出 PDF 文件到浏览器$dompdf->stream("/report.pdf", array("Attachment" => true)); // 可以设置为 true 来强制下载return $this->success('ok');}//pdf的html文件private function getPdfContent($data){// 获取数据并生成 HTML 字符串
//        $data = YourModel::all(); // 替换为你的数据获取逻辑$html = '<meta charset="UTF-8">';$html = '<html><head><style>table { width: 100%; border-collapse: collapse; } td, th { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>';$html .= '<h1>记录</h1>';$html .= '<table>';//        foreach ($data as $row) {$html .= '<tr><td><b></b></td><td></td></tr>';$html .= "<tr><td>名称</td><td>{$data->name}</td></tr>"; // 根据你的数据结构调整单元格内容$html .= "<tr><td>使用内容</td><td>{$data->content}</td></tr>"; $html .= "<tr><td>图片</td><td><img src='{$data->img}' width='100' height='100'></img></td></tr>";//        }$html .= '</table></body></html>';return $html;}

二. 这时候你去访问生成pdf文件,若输出数据为中文,则会显示乱码。需要引用字体库文件。
 1) 新建load_font.php放到项目跟目录,跟verdor同级:

<?php
// 1. [Required] Point to the composer or dompdf autoloader
require_once "vendor/autoload.php";// 2. [Optional] Set the path to your font directory
//    By default dompdf loads fonts to dompdf/lib/fonts
//    If you have modified your font directory set this
//    variable appropriately.
//$fontDir = "lib/fonts";// *** DO NOT MODIFY BELOW THIS POINT ***use Dompdf\Dompdf;
use Dompdf\CanvasFactory;
use Dompdf\Exception;
use Dompdf\FontMetrics;
use Dompdf\Options;use FontLib\Font;/*** Display command line usage*/
function usage() {echo <<<EOD
Usage: {$_SERVER["argv"][0]} font_family [n_file [b_file] [i_file] [bi_file]]
font_family:      the name of the font, e.g. Verdana, 'Times New Roman',monospace, sans-serif. If it equals to "system_fonts", all the system fonts will be installed.
n_file:           the .ttf or .otf file for the normal, non-bold, non-italicface of the font.
{b|i|bi}_file:    the files for each of the respective (bold, italic,bold-italic) faces.
If the optional b|i|bi files are not specified, load_font.php will search
the directory containing normal font file (n_file) for additional files that
it thinks might be the correct ones (e.g. that end in _Bold or b or B).  If
it finds the files they will also be processed.  All files will be
automatically copied to the DOMPDF font directory, and afm files will be
generated using php-font-lib (https://github.com/PhenX/php-font-lib).
Examples:
./load_font.php silkscreen /usr/share/fonts/truetype/slkscr.ttf
./load_font.php 'Times New Roman' /mnt/c_drive/WINDOWS/Fonts/times.ttf
EOD;
exit;
}if ( $_SERVER["argc"] < 3 && @$_SERVER["argv"][1] != "system_fonts" ) {usage();
}$dompdf = new Dompdf();
if (isset($fontDir) && realpath($fontDir) !== false) {$dompdf->getOptions()->set('fontDir', $fontDir);
}/*** Installs a new font family* This function maps a font-family name to a font.  It tries to locate the* bold, italic, and bold italic versions of the font as well.  Once the* files are located, ttf versions of the font are copied to the fonts* directory.  Changes to the font lookup table are saved to the cache.** @param Dompdf $dompdf      dompdf main object * @param string $fontname    the font-family name* @param string $normal      the filename of the normal face font subtype* @param string $bold        the filename of the bold face font subtype* @param string $italic      the filename of the italic face font subtype* @param string $bold_italic the filename of the bold italic face font subtype** @throws Exception*/
function install_font_family($dompdf, $fontname, $normal, $bold = null, $italic = null, $bold_italic = null) {$fontMetrics = $dompdf->getFontMetrics();// Check if the base filename is readableif ( !is_readable($normal) )throw new Exception("Unable to read '$normal'.");$dir = dirname($normal);$basename = basename($normal);$last_dot = strrpos($basename, '.');if ($last_dot !== false) {$file = substr($basename, 0, $last_dot);$ext = strtolower(substr($basename, $last_dot));} else {$file = $basename;$ext = '';}if ( !in_array($ext, array(".ttf", ".otf")) ) {throw new Exception("Unable to process fonts of type '$ext'.");}// Try $file_Bold.$ext etc.$path = "$dir/$file";$patterns = array("bold"        => array("_Bold", "b", "B", "bd", "BD"),"italic"      => array("_Italic", "i", "I"),"bold_italic" => array("_Bold_Italic", "bi", "BI", "ib", "IB"),);foreach ($patterns as $type => $_patterns) {if ( !isset($$type) || !is_readable($$type) ) {foreach($_patterns as $_pattern) {if ( is_readable("$path$_pattern$ext") ) {$$type = "$path$_pattern$ext";break;}}if ( is_null($$type) )echo ("Unable to find $type face file.\n");}}$fonts = compact("normal", "bold", "italic", "bold_italic");$entry = array();// Copy the files to the font directory.foreach ($fonts as $var => $src) {if ( is_null($src) ) {$entry[$var] = $dompdf->getOptions()->get('fontDir') . '/' . mb_substr(basename($normal), 0, -4);continue;}// Verify that the fonts exist and are readableif ( !is_readable($src) )throw new Exception("Requested font '$src' is not readable");$dest = $dompdf->getOptions()->get('fontDir') . '/' . basename($src);if ( !is_writeable(dirname($dest)) )throw new Exception("Unable to write to destination '$dest'.");echo "Copying $src to $dest...\n";if ( !copy($src, $dest) )throw new Exception("Unable to copy '$src' to '$dest'");$entry_name = mb_substr($dest, 0, -4);echo "Generating Adobe Font Metrics for $entry_name...\n";$font_obj = Font::load($dest);$font_obj->saveAdobeFontMetrics("$entry_name.ufm");$font_obj->close();$entry[$var] = $entry_name;}// Store the fonts in the lookup table$fontMetrics->setFontFamily($fontname, $entry);// Save the changes$fontMetrics->saveFontFamilies();
}// If installing system fonts (may take a long time)
if ( $_SERVER["argv"][1] === "system_fonts" ) {$fontMetrics = $dompdf->getFontMetrics();$files = glob("/usr/share/fonts/truetype/*.ttf") +glob("/usr/share/fonts/truetype/*/*.ttf") +glob("/usr/share/fonts/truetype/*/*/*.ttf") +glob("C:\\Windows\\fonts\\*.ttf") +glob("C:\\WinNT\\fonts\\*.ttf") +glob("/mnt/c_drive/WINDOWS/Fonts/");$fonts = array();foreach ($files as $file) {$font = Font::load($file);$records = $font->getData("name", "records");$type = $fontMetrics->getType($records[2]);$fonts[mb_strtolower($records[1])][$type] = $file;$font->close();}foreach ( $fonts as $family => $files ) {echo " >> Installing '$family'... \n";if ( !isset($files["normal"]) ) {echo "No 'normal' style font file\n";}else {install_font_family($dompdf, $family, @$files["normal"], @$files["bold"], @$files["italic"], @$files["bold_italic"]);echo "Done !\n";}echo "\n";}
}
else {call_user_func_array("install_font_family", array_merge( array($dompdf), array_slice($_SERVER["argv"], 1) ));
}

2)下载simsun.ttf文件放到根目录下:
3)执行命令:

//必须执行,很重要
php load_fount.php "SimSun" SimSun.ttf

4)添加设置字体的引用,如图一:

        // 重点设置字体$options->setDefaultFont('SimSun');

参考文档:php|thinkphp pdf 导出中文乱码 解决办法 #php导出 pdf中文乱码_我自横刀向天笑的技术博客_51CTO博客三.这时候,你想要导出的数据还有图片怎么办

1)将图片转换为base64的格式输出

$image = 'data:image/jpeg;base64,' . base64_encode(file_get_contents($data['img']));

参考文档:php生成pdf图片不显示怎么办-PHP问题-PHP中文网

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/web/87075.shtml
繁体地址,请注明出处:http://hk.pswp.cn/web/87075.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Beam2.61.0版本消费kafka重复问题排查

1.问题出现过程 在测试环境测试flink的job的任务消费kafka的情况&#xff0c;通过往job任务发送一条消息&#xff0c;然后flink web ui上消费出现了两条。然后通过重启JobManager和TaskManager后&#xff0c;任务从checkpoint恢复后就会出现重复消费。当任务不从checkpoint恢复…

关于 java:9. Java 网络编程

一、Socket 编程 Socket&#xff08;套接字&#xff09;是网络通信的端点&#xff0c;是对 TCP/IP 协议的编程抽象&#xff0c;用于实现两台主机间的数据交换。 通俗来说&#xff1a; 可以把 Socket 理解为“电话插口”&#xff0c;插上后客户端和服务端才能“通话”。 Sock…

主流零信任安全产品深度介绍

腾讯 iOA 零信任安全管理系统 功能&#xff1a;提供零信任接入、终端安全、数据防泄密等十余种功能模块。可实现基于身份的动态访问控制、终端安全一体化防护、数据防泄密体系等。核心优势&#xff1a;基于腾讯内部千万级终端实践打磨&#xff0c;沉淀丰富场景方案&#xff0c…

LabVIEW装配车体挠度无线测量

针对轨道交通车辆装配过程中车体挠度测量需求&#xff0c;基于LabVIEW开发无线快速测量系统&#xff0c;采用品牌硬件构建高精度数据采集与传输架构。系统通过 ZigBee 无线传输技术、高精度模数转换模块及激光位移传感器&#xff0c;实现装配车体挠度的实时、自动、非接触测量&…

java微服务-linux单机CPU接近100%优化

你这个场景&#xff1a; 4核16G 机器 同时运行了 8个 Spring Boot 微服务&#xff0c;每个 JAR 文件 100多 MB 导致 CPU 接近100% 确实是一个常见但资源紧绷的部署情境。下面是分层的优化建议&#xff0c;包括 JVM、系统、服务架构等多个方面&#xff0c;帮助你 降 CPU、稳…

MySQL表的约束和基本查询

一.表的约束 1.1空属性 当我们填写问卷的时候,经常会有不允许为空的问题,比如电话号,姓名等等.而mysql上我们可以在创建表的时候,如果想要某一列不允许为空,可以加上not null来加以限制: mysql> create table myclass( -> class_name varchar(20) not null, -> cla…

VBA代码解决方案第二十六讲:如何新建EXCEL工作簿文件

《VBA代码解决方案》(版权10028096)这套教程是我最早推出的教程&#xff0c;目前已经是第三版修订了。这套教程定位于入门后的提高&#xff0c;在学习这套教程过程中&#xff0c;侧重点是要理解及掌握我的“积木编程”思想。要灵活运用教程中的实例像搭积木一样把自己喜欢的代码…

【unity游戏开发——网络】套接字Socket的重要API

注意&#xff1a;考虑到热更新的内容比较多&#xff0c;我将热更新的内容分开&#xff0c;并全部整合放在【unity游戏开发——网络】专栏里&#xff0c;感兴趣的小伙伴可以前往逐一查看学习。 文章目录 1、Socket套接字的作用2、Socket类型与创建3、核心属性速查表4、关键方法指…

计算机网络(二)应用层HTTP协议

目录 1、HTTP概念 ​编辑2、工作流程​​ 3、HTTP vs HTTPS​​ 4、HTTP请求特征总结​ 5、持久性和非持久性连接 非持久连接&#xff08;HTTP/1.0&#xff09;​​ ​​持久连接&#xff08;HTTP/1.1&#xff09;​​ 1、HTTP概念 HTTP&#xff08;HyperText Transfer …

c# IO密集型与CPU密集型任务详解,以及在异步编程中的使用示例

文章目录 IO密集型与CPU密集型任务详解&#xff08;C#示例&#xff09;一、基本概念1. IO密集型任务2. CPU密集型任务 二、C#示例1. IO密集型示例1.1 文件操作异步示例1.2 网络请求异步示例1.3 数据库操作异步示例 2. CPU密集型示例2.1 基本CPU密集型异步处理2.2 并行处理CPU密…

用lines_gauss的width属性提取缺陷

自己做了一个图&#xff0c;这个图放在资源里了 结果图是这样&#xff08;这里只结算了窄区&#xff09; 代码和备注如下 read_image (Image11, C:/Users/Administrator/Desktop/分享/15/11.png) rgb1_to_gray (Image11, GrayImage) invert_image (GrayImage, ImageInvert) thr…

从0到100:房产中介小程序开发笔记(中)

背景调研 为中介带来诸多优势&#xff0c;能借助它打造专属小程序&#xff0c;方便及时更新核实租赁信息&#xff0c;确保信息准确无误&#xff0c;像房屋的大致地址、租金数额、租赁条件、房源优缺点等关键信息都能清晰呈现。还可上传房屋拍摄照片&#xff0c;这样用户能提前…

【AI 时代的网络爬虫新形态与防护思路研究】

网络爬虫原理与攻击防护的深度研究报告 网络爬虫技术已进入AI驱动的4.0时代&#xff0c;全球自动化请求流量占比突破51%&#xff0c;传统防御手段在面对高度仿真的AI爬虫时已显疲态。基于2025年最新数据&#xff0c;深入剖析网络爬虫的基本原理、工作流程、分类与攻击方式&…

低代码平台架构设计与关键组件

低代码平台的架构设计是其核心能力的关键支撑&#xff0c;需要平衡可视化开发的便捷性、生成应用的健壮性与性能、可扩展性以及企业级需求&#xff08;如安全、多租户、集成&#xff09;。以下是一个典型的企业级低代码平台架构概览及其关键组件&#xff1a; https://example.…

电商 ERP 系统集成接口指南

电商 ERP 系统的高效运行依赖于与多个业务系统的无缝对接&#xff0c;需要集成的核心接口包括&#xff1a;商品管理、订单处理、库存同步、物流配送、客户管理、财务结算等。这些接口是实现数据互通、业务协同的关键桥梁。 一、电商 ERP 系统集成所需接口类型 &#xff08;一…

Python实现对WPS协作群进行群消息自动推送

前言 本文是该专栏的第59篇,后面会持续分享python的各种干货知识,值得关注。 相信有些同学在工作或者项目中,都会使用到“WPS协作”作为办公聊天软件。如果说,有些项目的监控预警正好需要你同步到WPS协作群,这个时候需要怎么去做呢? 而本文,笔者将基于WPS协作,通过Py…

js严格模式和非严格模式

好的&#xff0c;这是一个非常基础且重要的概念。我们来详细解析一下 JavaScript 中的严格模式&#xff08;Strict Mode&#xff09;和非严格模式&#xff08;Sloppy Mode&#xff09;。 可以把它想象成参加一场考试&#xff1a; 非严格模式&#xff1a;就像是开卷、不计时的…

板凳-------Mysql cookbook学习 (十一--------1)

第11章&#xff1a;生成和使用序列 11.0 引言 11.1 创建一个序列列并生成序列值 CREATE TABLE insect ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id)&#xff0c;name VARCHAR(30) NOT NULL,date DATE NOT NULL,origin VARCHAR(30) NOT NULL); 字段说明 ‌id…

Vue3 中 Excel 导出的性能优化与实战指南

文章目录 Vue3 中 Excel 导出的性能优化与实战指南引言&#xff1a;为什么你的导出功能会卡死浏览器&#xff1f;一、前端导出方案深度剖析1.1 xlsx (SheetJS) - 轻量级冠军1.2 exceljs - 功能强大的重量级选手 二、后端导出方案&#xff1a;大数据处理的救星2.1 为什么大数据需…

安卓RecyclerView实现3D滑动轮播效果全流程实战

安卓RecyclerView实现3D滑动轮播效果全流程实战 1. 前言 作为一名学习安卓的人,在接触之前和之后两种完全不同的想法: 好看和怎么实现 当初接触到RecyclerView就觉得这个控件就可以把关于列表的所有UI实现,即便不能,也是功能十分强大 放在现在依然是应用最广的滑动列表控…