Magento 2 invoice/shipment PDF中文亂碼及內容過長未自動換行問題

PDF中文亂碼

一、添加支持的中文字體(SourceHanSans-Normal.ttf
    將字體放到 lib/internal/GnuFreeFont/ 目錄下便可php

二、重寫\Magento\Sales\Model\Order\Pdf\InvoiceMagento\Sales\Model\Order\Pdf\Shipment
(注:抽象類 Magento\Sales\Model\Order\Pdf\AbstractPdf 不支持重寫,因此須要重寫繼承了它的子類)
    1)di.xmlgit

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <!--Pdf support chinese fonts-->
    <preference for="Magento\Sales\Model\Order\Pdf\Invoice" type="Vendor_name\Module_name\Model\Order\Pdf\Invoice" />
    <preference for="Magento\Sales\Model\Order\Pdf\Shipment" type="Vendor_name\Module_name\Model\Order\Pdf\Shipment" />
</config>

    2)Vendor_name\Module_name\Model\Order\Pdf\Invoice.phpgithub

<?php
namespace Vendor_name\Module_name\Model\Order\Pdf;

class Invoice extends \Magento\Sales\Model\Order\Pdf\Invoice
{
    /**
     * Set font as regular
     *
     * @param  \Zend_Pdf_Page $object
     * @param  int $size
     * @return \Zend_Pdf_Resource_Font
     */
    protected function _setFontRegular($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }

    /**
     * Set font as bold
     *
     * @param  \Zend_Pdf_Page $object
     * @param  int $size
     * @return \Zend_Pdf_Resource_Font
     */
    protected function _setFontBold($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }

    /**
     * Set font as italic
     *
     * @param  \Zend_Pdf_Page $object
     * @param  int $size
     * @return \Zend_Pdf_Resource_Font
     */
    protected function _setFontItalic($object, $size = 7)
    {
        $font = \Zend_Pdf_Font::fontWithPath(
            $this->_rootDirectory->getAbsolutePath('lib/internal/GnuFreeFont/SourceHanSans-Normal.ttf')
        );
        $object->setFont($font, $size);
        return $font;
    }
}

Vendor_name\Module_name\Model\Order\Pdf\Shipment.php 同上;字體


PDF內容(products, address)過長未自動換行

一、products 過長需重寫 Magento\Sales\Model\Order\Pdf\Items\Invoice\DefaultInvoicedraw() 方法;
二、address 過長需重寫 Magento\Sales\Model\Order\Pdf\AbstractPdf _formatAddress() 方法;
注:以上2個function中 split() 的第二個參數即用於設置換行長度,將其修改成本身須要的長度便可this

相關文章
相關標籤/搜索