如何使用 PHPWord 在现有 Word 文档上添加水印?

问题描述 投票:0回答:2

我想在现有的 Word 文档上添加水印,但无法添加。有很多创建新文档然后根据需要编辑它们的示例。但是我找不到任何教程来编辑预先存在的 Word 文档。

下面是我的代码:

<?php
require_once '../PHPWord.php';

// New Word Document
$PHPWord = new PHPWord();

// New portrait section
$section = $PHPWord->createSection();

// Create header
$header = $section->createHeader();

// Add a watermark to the header
$header->addWatermark('_earth.jpg', array('marginTop'=>200, 'marginLeft'=>55));

$section->addText("Hello World");

// Save File
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('Watermark.docx');
?>
php doc phpword
2个回答
1
投票

你可以在这里找到一个例子: https://github.com/PHPOffice/PHPWord/blob/develop/samples/Sample_11_ReadWord2007.php

特别是你的问题,要打开文档,你需要更换线

$PHPWord = new PHPWord();

$PHPWord = PhpWord\IOFactory::load('<file path of your MSWord document>'); // or \PhpOffice\PhpWord\IOFactory depending on your environment

0
投票

您可以使用 PHPOffice 电子表格库

示例工作代码如下

<?php 

require_once("vendor/autoload.php"); 

// Your word file as input / existing file
$name = basename(__FILE__, '.php');
$name="sample";
$source = __DIR__ . "/{$name}.docx";

$phpWord = \PhpOffice\PhpWord\IOFactory::load($source);


// Get the initial Section of header and add watermark image to it
$section = $phpWord->getSection(0);
$header = $section->createHeader();
$header->addWatermark('watermark_sample.png', array('marginTop' => 0, 'marginLeft' => 0));


// write the output file
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');
© www.soinside.com 2019 - 2024. All rights reserved.