当前位置: 首页 > news >正文

dompdf导出pdf中文乱码显示问号?

环境:PHP 8.0   框架:ThinkPHP 8   软件包:phpoffice/phpword 、dompdf/dompdf

看了很多教程(包括GitHub的issue、stackoverflow)都没有解决、最终找到解决问题的根本!

背景:用Word模板做转PDF的时候,中文乱码,做法是先用模板替换好变量以后,转成HTML,再转成PDF。

解决方案:

1、先将load_font.php放在项目根目录,跟vendor同级

  A、GITHUB下载地址: load_font.php

  B、新建文件load_font.php复制下面代码

<?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 <<<EODUsage: {$_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.ttfEOD;
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字体文件放到项目根目录,跟load_font、vendor同级,这里我改名改成了SimSun.ttf

执行PHP命令:

php load_font.php "SimSun" SimSun.ttf

显示如下:

php load_font.php "SimSun" SimSun.ttf
Unable to find bold face file.
Unable to find italic face file.
Unable to find bold_italic face file.
Copying SimSun.ttf to D:\phpstudy_pro\WWW\newcrm.com\vendor\dompdf\dompdf/lib/fonts/SimSun.ttf...
Generating Adobe Font Metrics for D:\phpstudy_pro\WWW\newcrm.com\vendor\dompdf\dompdf/lib/fonts/SimSun...

如果php命令有问题,检查一下是不是没有配置环境变量,没有配置的话另行寻找配置教程

3、PHP代码如下:

    public function test(){$path = '/storage/contract/' . date('Ymd');$directoryPath = public_path() . $path;if (!file_exists($directoryPath)) {mkdir($directoryPath, 0755, true);}$options = new Options();$options->set('isRemoteEnabled', true);// 重点设置字体$options->setDefaultFont('SimSun');$dompdf = new Dompdf($options);$htmlFile = $directoryPath . '/index.html';$htmlContent = file_get_contents($htmlFile);$dompdf->loadHtml($htmlContent,'UTF-8');$dompdf->setPaper('A4');$dompdf->render();$pdfName = 'index.pdf';$pathToSavePdf = $directoryPath . '/' . $pdfName;$output = $dompdf->output();file_put_contents($pathToSavePdf, $output);}

<!DOCTYPE html>
<html lang="en">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><title></title>
</head>
<body>
<div>世界和平
</div>
</body>
</html>

生成PDF后

下面配一个WORD模板(动态变量)->转HTML->生成PDF文件

    public function generateContract($param): array{$contract = $this->contractModel->with(['customer','contacts'])->where('id', $param['id'])->find();if (!$contract) {throw new BusinessException(Code::NOT_FOUND, '合同订单不存在');}$contract = $contract->toArray();$file = public_path() . '/static/template/contract/2024.docx';$templateProcessor = new TemplateProcessor($file);$templateProcessor->setValue('customer', $contract['customer_name']);$templateProcessor->setValue('address', $contract['customer_city'] . $contract['customer_address']);$path = '/storage/contract/' . date('Ymd');$directoryPath = public_path() . $path;if (!file_exists($directoryPath)) {mkdir($directoryPath, 0755, true);}$name = $contract['code'] . mt_rand(1000, 9999);$wordName = $name . '.docx';$pathToSave = $directoryPath . '/' . $wordName;$templateProcessor->saveAs($pathToSave);// 转换 Word 文件为 HTML$phpWord = IOFactory::load($pathToSave);$htmlWriter = IOFactory::createWriter($phpWord, 'HTML');$htmlFile = $directoryPath . '/' . $name . '.html';$htmlWriter->save($htmlFile);// 使用 Dompdf 将 HTML 转换为 PDF$options = new Options();$options->set('isRemoteEnabled', true);$options->setDefaultFont('SimSun');$dompdf = new Dompdf($options);$htmlFile = $directoryPath . '/' . $name . '.html';$htmlContent = file_get_contents($htmlFile);$dompdf->loadHtml($htmlContent,'UTF-8');$dompdf->setPaper('A4');$dompdf->render();$pdfName = $name . '.pdf';$pathToSavePdf = $directoryPath . '/' . $pdfName;$output = $dompdf->output();file_put_contents($pathToSavePdf, $output);// 删除临时 HTML 文件unlink($htmlFile);return ['url' => $path . '/' . $pdfName];}

注:doc文件不兼容,用docx模板文件

相关文章:

dompdf导出pdf中文乱码显示问号?

环境&#xff1a;PHP 8.0 框架&#xff1a;ThinkPHP 8 软件包&#xff1a;phpoffice/phpword 、dompdf/dompdf 看了很多教程&#xff08;包括GitHub的issue、stackoverflow&#xff09;都没有解决、最终找到解决问题的根本&#xff01; 背景&#xff1a;用Word模板做转PDF…...

韩顺平Java-第二十四章:MYSQL基础篇

一 数据库 1 数据库简单原理图 2 使用命令行窗口连接MYSQL数据库 &#xff08;1&#xff09;mysql -h 主机名 -P 端口 -u 用户名 -p密码&#xff1b; &#xff08;2&#xff09;登录前&#xff0c;保证服务启动。 3 MySQL三层结构 &#xff08;1&#xff09;所谓安装MySQL数…...

【动态规划算法题记录】最长/最大 问题汇总 (leetcode)

目录 32. 最长有效括号思路代码 300. 最长递增子序列思路代码 674. 最长连续递增序列思路1&#xff1a;双指针代码1&#xff1a;双指针思路2&#xff1a;dp代码2&#xff1a;dp 718. 最长重复子数组思路1&#xff1a;dp代码1&#xff1a;dp思路2&#xff1a;dp优化代码2&#x…...

2020 位示图

2020年网络规划设计师上午真题解析36-40_哔哩哔哩_bilibili 假设某计算机的字长为32位&#xff0c;该计算机文件管理系统磁盘空间管理采用位示图&#xff08;bitmap&#xff09;&#xff0c;记录磁盘的使用情况。若磁盘的容量为300GB&#xff0c;物理块的大小为4MB&#xff0c;…...

富格林:防止陷入黑幕欺诈平台

富格林指出&#xff0c;不少投资者因未做好投资准备而不慎误入黑幕欺诈平台&#xff0c;造成了不必要的亏损。投资者在投资前&#xff0c;需要时刻保持警惕&#xff0c;根据市场行情&#xff0c;作出有依据的投资决定&#xff0c;而不是依赖黑幕欺诈平台的噱头进行投资。建议投…...

Cookie、Session 、token

Cookie 优点: 简单易用: 浏览器自动管理 Cookie 的发送和接收。持久性: 可以设置过期时间&#xff0c;使其可以在浏览器关闭后依旧存在。广泛支持: 所有现代浏览器都支持 Cookie。 缺点: 安全性问题: 存储在客户端&#xff0c;容易被查看和篡改。敏感信息不应直接存储在 Co…...

Json-类型映射使用TypeFactory或者TypeReference

当你需要将JSON数据转换为Java中的复杂类型时,可以使用Jackson库中的TypeFactory或 者TypeReference。这两种方式可以帮助你处理复杂的泛型类型,例如 List<Map<String, Object>> 或者 Map<String, List<Object>>。 示例 1: 使用 TypeFactory 和 T…...

Linux shell编程学习笔记73:sed命令——沧海横流任我行(上)

0 前言 在大数据时代&#xff0c;我们要面对大量数据&#xff0c;有时需要对数据进行替换、删除、新增、选取等特定工作。 在Linux中提供很多数据处理命令&#xff0c;如果我们要以行为单位进行数据处理&#xff0c;可以使用sed。 1 sed 的帮助信息&#xff0c;功能&#xff…...

内网渗透之icmp隧道传输

原理 # 为什么要建立隧道 在实际的网络中&#xff0c;通常会通过各种边界设备软/硬件防火墙、入侵检测系统来检查对外连接的情况&#xff0c;如果发现异常&#xff0c;会对通信进行阻断。 ​ # 什么是隧道 就是一种绕过端口屏蔽的方式&#xff0c;防火墙两端的数据包通过防火墙…...

【C++ 第十五章】map 和 set 的封装(封装红黑树)

1. map 和 set 的介绍 ⭐map 与 set 分别是STL中的两种序列式容器; 它们是一种树形数据结构的容器&#xff0c;且其的底层构造为一棵红黑树; 而在上一篇文章中提到,其实红黑树本身就是一棵二叉搜索树,是基于二叉搜索树的性质对其增加了平衡的属性来提高其综合性能 ⭐当然也…...

LIN通讯

目录 1 PLinApi.h 2 TLINFrameEntry 结构体 3 自定义函数getTLINFrameEntry 4 TLINScheduleSlot 结构体 5 自定义函数 getTLINScheduleSlot 6 自定义LIN_SetScheduleInit函数 7 自定义 LIN_StartSchedule 8 发送函数 9 线程接收函数 1 PLinApi.h 这是官方头文件 ///…...

zabbix常见架构及组件

Zabbix作为一个开源的、功能全面的监控解决方案&#xff0c;广泛应用于各类组织中&#xff0c;以实现对网络、服务器、云服务及应用程序性能的全方位监控。部署架构灵活性高&#xff0c;可支持从小型单一服务器环境到大型分布式系统的多种场景。基本架构通常包括监控端&#xf…...

plsql表格怎么显示中文 plsql如何导入表格数据

在Oracle数据库开发中&#xff0c;PL/SQL Developer是一款广泛使用的集成开发环境&#xff08;IDE&#xff09;&#xff0c;它提供了丰富的功能来帮助开发人员高效地进行数据库开发和管理。在使用PL/SQL Developer时&#xff0c;许多用户会遇到表格显示中文的问题&#xff0c;以…...

chromedriver下载地址大全(包括124.*后)以及替换exe后仍显示版本不匹配的问题

Chrome for Testing availability CNPM Binaries Mirror 若已经更新了系统环境变量里的chromdriver路径下的exe&#xff0c;仍显示版本不匹配&#xff1a; 则在cmd界面输入 chromedriver 会跳出version verison与刚刚下载好的exe不匹配&#xff0c;则再输入&#xff1a; w…...

拦截器实现 Mybatis Plus 打印含参数的 SQL 语句

1.实现拦截器 package com.sample.common.interceptor;import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.BoundSql; import or…...

Oracle Subprogram即Oracle子程序

Oracle Subprogram&#xff0c;即Oracle子程序&#xff0c;是Oracle数据库中存储的过程&#xff08;Procedures&#xff09;和函数&#xff08;Functions&#xff09;的统称。这些子程序是存储在数据库中的PL/SQL代码块&#xff0c;用于执行特定的任务或操作。下面详细介绍Orac…...

自然语言处理实战项目30-基于RoBERTa模型的高精度的评论文本分类实战,详细代码复现可直接运行

大家好,我是微学AI,今天给大家介绍一下自然语言处理实战项目30-基于RoBERTa模型的高精度的评论文本分类实战,详细代码复现可直接运行。RoBERTa模型是由 Facebook AI Research 和 FAIR 的研究人员提出的一种改进版的 BERT 模型。RoBERTa 通过采用更大的训练数据集、动态掩码机…...

RK3588J正式发布Ubuntu桌面系统,丝滑又便捷!

本文主要介绍瑞芯微RK3588J的Ubuntu系统桌面演示&#xff0c;开发环境如下&#xff1a; U-Boot&#xff1a;U-Boot-2017.09 Kernel&#xff1a;Linux-5.10.160 Ubuntu&#xff1a;Ubuntu20.04.6 LinuxSDK&#xff1a; rk3588-linux5.10-sdk-[版本号] &#xff08;基于rk3…...

基于GPT-SoVITS的API实现批量克隆声音

目标是将每一段声音通过GPT-SoVITS的API的API进行克隆,因为拼在一起的整个片段处理会造成内存或者缓存溢出。 将目录下的音频文件生成到指定目录下,然后再进行拼接。 通过AI工具箱生成的数据文件是这样的结构,temp目录下是没个片段生成的部分,connect_是正常拼接的音频文件…...

详解华为项目管理,附华为高级项目管理内训材料

&#xff08;一&#xff09;华为在项目管理中通过有效的沟通、灵活的组织结构、坚持不懈的努力、细致的管理和科学的考核体系&#xff0c;实现了持续的创新和发展。通过引进先进的管理模式&#xff0c;强调以客户需求为导向&#xff0c;华为不仅优化了技术管理和项目研发流程&a…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

基于服务器使用 apt 安装、配置 Nginx

&#x1f9fe; 一、查看可安装的 Nginx 版本 首先&#xff0c;你可以运行以下命令查看可用版本&#xff1a; apt-cache madison nginx-core输出示例&#xff1a; nginx-core | 1.18.0-6ubuntu14.6 | http://archive.ubuntu.com/ubuntu focal-updates/main amd64 Packages ng…...

高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数

高效线程安全的单例模式:Python 中的懒加载与自定义初始化参数 在软件开发中,单例模式(Singleton Pattern)是一种常见的设计模式,确保一个类仅有一个实例,并提供一个全局访问点。在多线程环境下,实现单例模式时需要注意线程安全问题,以防止多个线程同时创建实例,导致…...

关于uniapp展示PDF的解决方案

在 UniApp 的 H5 环境中使用 pdf-vue3 组件可以实现完整的 PDF 预览功能。以下是详细实现步骤和注意事项&#xff1a; 一、安装依赖 安装 pdf-vue3 和 PDF.js 核心库&#xff1a; npm install pdf-vue3 pdfjs-dist二、基本使用示例 <template><view class"con…...

淘宝扭蛋机小程序系统开发:打造互动性强的购物平台

淘宝扭蛋机小程序系统的开发&#xff0c;旨在打造一个互动性强的购物平台&#xff0c;让用户在购物的同时&#xff0c;能够享受到更多的乐趣和惊喜。 淘宝扭蛋机小程序系统拥有丰富的互动功能。用户可以通过虚拟摇杆操作扭蛋机&#xff0c;实现旋转、抽拉等动作&#xff0c;增…...

WPF八大法则:告别模态窗口卡顿

⚙️ 核心问题&#xff1a;阻塞式模态窗口的缺陷 原始代码中ShowDialog()会阻塞UI线程&#xff0c;导致后续逻辑无法执行&#xff1a; var result modalWindow.ShowDialog(); // 线程阻塞 ProcessResult(result); // 必须等待窗口关闭根本问题&#xff1a…...

uniapp 实现腾讯云IM群文件上传下载功能

UniApp 集成腾讯云IM实现群文件上传下载功能全攻略 一、功能背景与技术选型 在团队协作场景中&#xff0c;群文件共享是核心需求之一。本文将介绍如何基于腾讯云IMCOS&#xff0c;在uniapp中实现&#xff1a; 群内文件上传/下载文件元数据管理下载进度追踪跨平台文件预览 二…...

数据结构:递归的种类(Types of Recursion)

目录 尾递归&#xff08;Tail Recursion&#xff09; 什么是 Loop&#xff08;循环&#xff09;&#xff1f; 复杂度分析 头递归&#xff08;Head Recursion&#xff09; 树形递归&#xff08;Tree Recursion&#xff09; 线性递归&#xff08;Linear Recursion&#xff09;…...

密码学基础——SM4算法

博客主页&#xff1a;christine-rr-CSDN博客 ​​​​专栏主页&#xff1a;密码学 &#x1f4cc; 【今日更新】&#x1f4cc; 对称密码算法——SM4 目录 一、国密SM系列算法概述 二、SM4算法 2.1算法背景 2.2算法特点 2.3 基本部件 2.3.1 S盒 2.3.2 非线性变换 ​编辑…...

pgsql:还原数据库后出现重复序列导致“more than one owned sequence found“报错问题的解决

问题&#xff1a; pgsql数据库通过备份数据库文件进行还原时&#xff0c;如果表中有自增序列&#xff0c;还原后可能会出现重复的序列&#xff0c;此时若向表中插入新行时会出现“more than one owned sequence found”的报错提示。 点击菜单“其它”-》“序列”&#xff0c;…...