在PHP中的Docx上添加行号

时间:2019-04-01 08:24:15

标签: php excel ms-word phpoffice

我正在处理用户上传的docx,我想在将其导出为PDF之前在docx上添加行号(例如:http://prntscr.com/n5rc1s)。

我试图用PhpOffice添加它,但没有成功。

我的代码可以转换为PDF,但没有行号。

感谢您的帮助:)

我的代码:

require_once('vendor/autoload.php');


define('PHPWORD_BASE_DIR', realpath(__DIR__));
$domPdfPath = realpath(PHPWORD_BASE_DIR . '/vendor/dompdf/dompdf');
\PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
\PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');

$phpWord = new \PhpOffice\PhpWord\PhpWord();

//Open template and save it as docx
$document = $phpWord->loadTemplate('test.docx');
$document->saveAs('temp.docx');

//Load temp file
$phpWord = \PhpOffice\PhpWord\IOFactory::load('temp.docx');
$sections = $phpWord->getSections();
foreach ($sections as $section) {
    $section->getStyle()->setLineNumbering(array());

}
//Save it
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord , 'PDF');
$xmlWriter->save('result.pdf');

1 个答案:

答案 0 :(得分:0)

您已经接近了,但您必须将值传递给

$section->getStyle()->setLineNumbering(array());

而不是空数组。在source

/**
 * Line numbering
 *
 * @var \PhpOffice\PhpWord\Style\LineNumbering
 * @see  http://www.schemacentral.com/sc/ooxml/e-w_lnNumType-1.html
 */
private $lineNumbering;

有对 the schema 的引用,因此您实际上必须传递 countBy 等的值。您可能希望文本和行号之间至少有一些间距,因此您可以执行以下操作

$section->getStyle()->setLineNumbering(['countBy' => 1, 'restart' => 'continuous', 'distance' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(.2)]);