Skip to content

Feat: SVG Image Type Support + CI #2790

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/changes/1.x/1.5.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

## Enhancements

- Word2007 Writer: Support for embedding SVG images by [@prog-klk1](https://github.com/prog-klk1) in [#2790](https://github.com/PHPOffice/PHPWord/pull/2790)

### Bug fixes

- Set writeAttribute return type by [@radarhere](https://github.com/radarhere) fixing [#2204](https://github.com/PHPOffice/PHPWord/issues/2204) in [#2776](https://github.com/PHPOffice/PHPWord/pull/2776)
Expand Down
41 changes: 41 additions & 0 deletions samples/Sample_47_SVG.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

use PhpOffice\PhpWord\Element\Section;
use PhpOffice\PhpWord\PhpWord;

include_once 'Sample_Header.php';

// New Word document
echo date('H:i:s'), ' Create new PhpWord object', EOL;
$phpWord = new PhpWord();

$section = $phpWord->addSection();
$section->addText('SVG image without any styles:');
$svg = $section->addImage(__DIR__ . '/resources/sample.svg');

printSeparator($section);

$section->addText('SVG image with styles:');
$svg = $section->addImage(
__DIR__ . '/resources/sample.svg',
[
'width' => 200,
'height' => 200,
'align' => 'center',
'wrappingStyle' => PhpOffice\PhpWord\Style\Image::WRAPPING_STYLE_BEHIND,
]
);

function printSeparator(Section $section): void
{
$section->addTextBreak();
$lineStyle = ['weight' => 0.2, 'width' => 150, 'height' => 0, 'align' => 'center'];
$section->addLine($lineStyle);
$section->addTextBreak(2);
}

// Save file
echo write($phpWord, basename(__FILE__, '.php'), $writers);
if (!CLI) {
include_once 'Sample_Footer.php';
}
96 changes: 96 additions & 0 deletions samples/resources/sample.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
49 changes: 49 additions & 0 deletions src/PhpWord/Element/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

namespace PhpOffice\PhpWord\Element;

use DOMDocument;
use PhpOffice\PhpWord\Exception\CreateTemporaryFileException;
use PhpOffice\PhpWord\Exception\InvalidImageException;
use PhpOffice\PhpWord\Exception\UnsupportedImageTypeException;
Expand Down Expand Up @@ -432,6 +433,20 @@ private function checkImage(): void
{
$this->setSourceType();

$ext = strtolower(pathinfo($this->source, PATHINFO_EXTENSION));
if ($ext === 'svg') {
[$actualWidth, $actualHeight] = $this->getSvgDimensions($this->source);
$this->imageType = 'image/svg+xml';
$this->imageExtension = 'svg';
$this->imageFunc = null;
$this->imageQuality = null;
$this->memoryImage = false;
$this->sourceType = self::SOURCE_LOCAL;
$this->setProportionalSize($actualWidth, $actualHeight);

return;
}

// Check image data
if ($this->sourceType == self::SOURCE_ARCHIVE) {
$imageData = $this->getArchiveImageSize($this->source);
Expand Down Expand Up @@ -598,4 +613,38 @@ private function setProportionalSize($actualWidth, $actualHeight): void
}
}
}

public function getSvgDimensions(string $file): array
{
$xml = @file_get_contents($file);
if ($xml === false) {
throw new InvalidImageException("Impossible de lire le fichier SVG: $file");
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
if (!$dom->loadXML($xml)) {
throw new InvalidImageException('SVG invalide ou mal formé');
}
$svg = $dom->documentElement;

$wAttr = round((float) $svg->getAttribute('width'));
$hAttr = round((float) $svg->getAttribute('height'));

$w = (int) filter_var($wAttr, FILTER_SANITIZE_NUMBER_INT);
$h = (int) filter_var($hAttr, FILTER_SANITIZE_NUMBER_INT);

if ($w <= 0 || $h <= 0) {
$vb = $svg->getAttribute('viewBox');
if (preg_match('/^\s*[\d.+-]+[\s,]+[\d.+-]+[\s,]+([\d.+-]+)[\s,]+([\d.+-]+)\s*$/', $vb, $m)) {
$w = (int) round((float) $m[1]);
$h = (int) round((float) $m[2]);
}
}

if ($w <= 0 || $h <= 0) {
throw new InvalidImageException('Impossible de déterminer width/height ou viewBox valides pour le SVG');
}

return [$w, $h];
}
}
138 changes: 138 additions & 0 deletions src/PhpWord/Writer/Word2007/Element/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ public function write(): void
if (!$element instanceof ImageElement) {
return;
}
$ext = strtolower(pathinfo($element->getSource(), PATHINFO_EXTENSION));
if ($ext === 'svg') {
$this->writeSvgDrawing($xmlWriter, $element);

return;
}

if ($element->isWatermark()) {
$this->writeWatermark($xmlWriter, $element);
Expand Down Expand Up @@ -127,4 +133,136 @@ private function writeWatermark(XMLWriter $xmlWriter, ImageElement $element): vo
$xmlWriter->endElement(); // w:p
}
}

private function writeSvgDrawing(XMLWriter $xmlWriter, ImageElement $element): void
{
$rId = $element->getRelationId() + ($element->isInSection() ? 6 : 0);

$style = $element->getStyle();
// dimensions px, fallback sur getSvgDimensions()
$pxW = $style->getWidth() ?: 0;
$pxH = $style->getHeight() ?: 0;
if ($pxW <= 0 || $pxH <= 0) {
[$pxW, $pxH] = $element->getSvgDimensions($element->getSource());
}
$cx = \PhpOffice\PhpWord\Shared\Drawing::pixelsToEmu($pxW);
$cy = \PhpOffice\PhpWord\Shared\Drawing::pixelsToEmu($pxH);

// <w:p> + align
if (!$this->withoutP) {
$xmlWriter->startElement('w:p');
(new ImageStyleWriter($xmlWriter, $style))->writeAlignment();
}
// <w:r>
$xmlWriter->startElement('w:r');
// <w:drawing>
$xmlWriter->startElement('w:drawing');

// <wp:inline> avec déclarations xmlns comme python-docx-oss
$xmlWriter->startElement('wp:inline');
$xmlWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');
$xmlWriter->writeAttribute('xmlns:pic', 'http://schemas.openxmlformats.org/drawingml/2006/picture');
$xmlWriter->writeAttribute('xmlns:asvg', 'http://schemas.microsoft.com/office/drawing/2016/SVG/main');

// <wp:extent>
$xmlWriter->startElement('wp:extent');
$xmlWriter->writeAttribute('cx', (string) $cx);
$xmlWriter->writeAttribute('cy', (string) $cy);
$xmlWriter->endElement();

// <wp:docPr>
$xmlWriter->startElement('wp:docPr');
$xmlWriter->writeAttribute('id', '1');
$xmlWriter->writeAttribute('name', 'Picture 1');
$xmlWriter->endElement();

// <wp:cNvGraphicFramePr>
$xmlWriter->startElement('wp:cNvGraphicFramePr');
$xmlWriter->startElement('a:graphicFrameLocks');
$xmlWriter->writeAttribute('noChangeAspect', '1');
$xmlWriter->endElement();
$xmlWriter->endElement();

// <a:graphic>
$xmlWriter->startElement('a:graphic');
// <a:graphicData uri=".../picture">
$xmlWriter->startElement('a:graphicData');
$xmlWriter->writeAttribute(
'uri',
'http://schemas.openxmlformats.org/drawingml/2006/picture'
);

// <pic:pic>
$xmlWriter->startElement('pic:pic');

// <pic:nvPicPr>
$xmlWriter->startElement('pic:nvPicPr');
$xmlWriter->startElement('pic:cNvPr');
$xmlWriter->writeAttribute('id', '0');
$xmlWriter->writeAttribute('name', basename($element->getSource()));
$xmlWriter->endElement();
$xmlWriter->startElement('pic:cNvPicPr');
$xmlWriter->endElement();
$xmlWriter->endElement();

// <pic:blipFill>
$xmlWriter->startElement('pic:blipFill');
$xmlWriter->startElement('a:blip');
// uniquement extLst avec svgBlip
$xmlWriter->startElement('a:extLst');
$xmlWriter->startElement('a:ext');
$xmlWriter->writeAttribute(
'uri',
'{96DAC541-7B7A-43D3-8B79-37D633B846F1}'
);
$xmlWriter->startElement('asvg:svgBlip');
$xmlWriter->writeAttribute(
'r:embed',
'rId' . $rId
);
$xmlWriter->endElement(); // asvg:svgBlip
$xmlWriter->endElement(); // a:ext
$xmlWriter->endElement(); // a:extLst
$xmlWriter->endElement(); // a:blip

// <a:stretch><a:fillRect/>
$xmlWriter->startElement('a:stretch');
$xmlWriter->startElement('a:fillRect');
$xmlWriter->endElement();
$xmlWriter->endElement();

$xmlWriter->endElement(); // pic:blipFill

// <pic:spPr>
$xmlWriter->startElement('pic:spPr');
$xmlWriter->startElement('a:xfrm');
$xmlWriter->startElement('a:off');
$xmlWriter->writeAttribute('x', '0');
$xmlWriter->writeAttribute('y', '0');
$xmlWriter->endElement();
$xmlWriter->startElement('a:ext');
$xmlWriter->writeAttribute('cx', (string) $cx);
$xmlWriter->writeAttribute('cy', (string) $cy);
$xmlWriter->endElement();
$xmlWriter->endElement();
$xmlWriter->startElement('a:prstGeom');
$xmlWriter->writeAttribute('prst', 'rect');
$xmlWriter->endElement();
$xmlWriter->endElement(); // pic:spPr

$xmlWriter->endElement(); // pic:pic

$xmlWriter->endElement(); // a:graphicData
$xmlWriter->endElement(); // a:graphic

$xmlWriter->endElement(); // wp:inline

$xmlWriter->endElement(); // w:drawing
$xmlWriter->endElement(); // w:r

// </w:p>
if (!$this->withoutP) {
$xmlWriter->endElement();
}
}
}
Loading