laravel生成pdf(barryvdh/laravel-dompdf)

7 篇文章 0 订阅
文章介绍了在Laravel6中集成barryvdh/laravel-dompdf库生成PDF时遇到中文乱码的问题,以及如何通过安装字体和配置解决这个问题。主要步骤包括添加服务提供者和别名,发布配置,创建控制器和视图,以及在命令行中执行脚本来安装自定义字体。
摘要由CSDN通过智能技术生成

安装:

composer require barryvdh/laravel-dompdf

配置:config/app.php中

providers:Barryvdh\DomPDF\ServiceProvider::class,

aliases:'PDF' => Barryvdh\DomPDF\Facade::class,

laravel6之后需要在bootstrap/app.php中,return $app;前增加

$app->singleton(\Barryvdh\DomPDF\ServiceProvider::class);

在config文件夹下生成配置文件

php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider"

routes/web.php中注册路由

Route::get('/pdf_download', 'PdfController@pdf_download');

在app/Http/Controllers下创建PdfController.php

<?php
namespace App\Http\Controllers;
use PDF;
class PdfController{
    public function pdf_download () {
        $data = ["one"=>1, "two"=>2];
        $pdf = PDF::loadView("pdf.pdf_download", ["data"=>$data]);
        return $pdf->download("pdf下载".date("YmdHis").".pdf");
    }
}

在resources/views下创建pdf文件夹,该文件夹下创建pdf_download.blade.php文件

<style>
    body{
        font-family:"wryh";//这里是之后防止中文乱码引入的字体
    }
</style>
<h3>pdf下载</h3>
<table>
    <tr>
        <td>{{$data['one']}}</td>
        <td>{{$data['two']}}</td>
        <td>yingwen</td>
        <td>中文</td>
    </tr>
</table>

浏览器里执行路由‘/pdf_download’生成并打开对应的pdf文件,会发现中文是乱码的

解决中文乱码:

在根目录下(非public目录下)创建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 <<<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-italic
                  face 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 readable
  if ( !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 readable
    if ( !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) ));
}

下载微软雅黑字体,重命名为wryh.ttf,并保存在根目录下(非public下)

在该项目下执行命令行php font.php wryh wryh.ttf

修改config/dompdf.php中的配置:

"font_dir" => realpath(base_path())."/vendor/dompdf/dompdf/lib/fonts",
"font_cache" => realpath(base_path())."/vendor/dompdf/dompdf/lib/fonts",

然后在模版文件中使用wryh字体,

<style>
body{
  font-family:"wryh"
}
</style>

参考:

laravel6.*实现html转PDF导出下载(barryvdh/laravel-dompdf)-阿里云开发者社区

Laravel 6 - How to generate HTML to PDF with laravel domPDF

https://www.cnblogs.com/cocoqi/p/17022163.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值