How can I insert math equations in word from php? - math

I need to automatically generate word documents with mathematical expressions using php.
Better to use Microsoft equation, MathType or word's 07+ equation editor.
I tried to use phpword's function addObject() to insert MathType *.eps file as OLE but it filetype not support.
How I should do it?
$word = new \PhpOffice\PhpWord\PhpWord();
$section = $word->addSection();
$section->addObject('formulas/Eqn1.eps');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($word, 'Word2007');
$objWriter->save('docs/helloWorld.docx');
Error: PhpOffice\PhpWord\Exception\InvalidObjectException
If I tried add as math:
$section->addText('
<w:p w:rsidR="00D14CAF" w:rsidRDefault="00A07C15">
<m:oMathPara>
<m:oMath>
<m:r>
<w:rPr>
<w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/>
</w:rPr>
<m:t>XXXXXXXXXXXXXX</m:t>
</m:r>
</m:oMath>
</m:oMathPara>
<w:bookmarkStart w:id="0" w:name="_GoBack"/>
<w:bookmarkEnd w:id="0"/>
</w:p>
');
*.docx doesn't open (error)

The file does not open cause there's xml tag elements in the text.
I needed to insert equations into a document and the easiest way was to render the equation using mathjax then save an image with html2canvas and insert with phpWord addImage(). I hope this helps.

adding answer for new developers.
php-docx library can help here, here is an example
https://www.phpdocx.com/api-documentation/word-content/add-math-OMML-Word-document-with-PHP

Related

Changing page orientation in word using Quarto?

Is there a way of changing the page orientation for specific segments of a document when using Quarto and rendering to Word?
The ideal approach would be something similar to BLOCK_LANDSCAPE_START/BLOCK_LANDSCAPE_STOP from officedown.
But also interested in other approaches (for example using the reference-doc).
There's no unified solution for this yet, but you can get around by using a custom Lua filter. Store the filter given below to a file, say docx-landscape.lua, and then use it by listing it under filters in the document's YAML section. Use a fenced div with class landscape to mark content that should appear in landscape mode.
E.g.:
---
title: "Nullus"
filters:
- docx-landscape.lua
---
This is in portrait mode.
::: landscape
This should appear in landscape mode.
:::
Things should be back to normal here.
where the filter docx-landscape.lua contains
local ooxml = function (s)
return pandoc.RawBlock('openxml', s)
end
local end_portrait_section = ooxml
'<w:p><w:pPr><w:sectPr></w:sectPr></w:pPr></w:p>'
local end_landscape_section = ooxml [[
<w:p>
<w:pPr>
<w:sectPr>
<w:pgSz w:h="11906" w:w="16838" w:orient="landscape" />
</w:sectPr>
</w:pPr>
</w:p>
]]
function Div (div)
if div.classes:includes 'landscape' then
div.content:insert(1, end_portrait_section)
div.content:insert(end_landscape_section)
return div
end
end
The filter takes a few shortcuts, but should work ok in most cases. Please let me know about any issues with it.
Addendum: if you prefer officedown commands, then append the following to the filter to make those commands work:
function RawBlock (raw)
if raw.text:match 'BLOCK_LANDSCAPE_START' then
return end_portrait_section
elseif raw.text:match 'BLOCK_LANDSCAPE_STOP' then
return end_landscape_section
end
end

How to apply built-in footer style using Aspose Word?

Recenty I am using Aspose Word to generating some reports, and there is a small problem.
Currently I am using DocumentBuilder and a 2-column table to make up the footer, System name at first column align to left while page number at second column align to right.
Everything is fine, yet I do not want the footer looks so dull as plain text, so I would like to add some style to the footer.
I would like to apply some built-in template of footer, say Alphabet as shown below, is it possible to do so by using Aspose Word?
If you have MS Word 2013 installed on your machine, you'll most likely find a Word document 'Built-In Building Blocks.dotx' at the following location:
C:\Users\Awais\AppData\Roaming\Microsoft\Document Building Blocks\1033\15\Built-In Building Blocks.dotx
The predefined built-in building blocks entries that ship with Word are stored in above template document. Using Aspose.Words, you can extract any building block from it and paste inside another Word document.
GlossaryDocument class in Aspose.Words represents such Building Blocks. Please try using the following code:
Document docBuildingBlocks = new Document(MyDir + #"Building Blocks.dotx");
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
GlossaryDocument glossaryDocument = docBuildingBlocks.GlossaryDocument;
foreach (BuildingBlock buildingBlock in glossaryDocument.BuildingBlocks)
{
if (buildingBlock.Gallery.ToString().StartsWith("Footer") &&
buildingBlock.Name.Equals("ViewMaster (Vertical)"))
{
Section sec = (Section)buildingBlock.FirstChild;
foreach (Node node in sec.Body.ChildNodes)
{
HeaderFooter hf = doc.FirstSection.HeadersFooters[HeaderFooterType.FooterPrimary];
hf.AppendChild(doc.ImportNode(node, true));
}
}
}
doc.Save(MyDir + #"15.6.0.docx");
Hope, this helps.
I work with Aspose as Developer Evangelist.

Conditional Formatting lost on save

I'm trying to create a simple setup to load a template, insert some data and save as a new file. However I need some conditional formatting on some of the cells and when I get the newly created files the conditional formatting is missing. It's not being overridden by some other formatting, the rules are missing from the conditional formatting menu. I'm using PHP 5.2, PHPExcel 1.7.8 and Excel 2010.
<?php
class template {
static $objPHPExcel;
function __construct() {
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
require_once '../Classes/PHPExcel/IOFactory.php';
if (!file_exists("template.xlsx")) {
exit("template missing." . EOL);
}
echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(false);
self::$objPHPExcel = $objReader->load("template.xlsx");
}
function insertdata($dataArray){ /* unused */ }
function save($name){
define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');
require_once '../Classes/PHPExcel/IOFactory.php';
echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$objWriter = PHPExcel_IOFactory::createWriter(self::$objPHPExcel, 'Excel2007');
$objWriter->save($name);
echo date('H:i:s') , " File written to: ".$name , EOL;
}
$temp=new template();
$temp->save("savethis.xlsx");
I'm trying to preserve a Graded 2 color scale (Formatting based on cell values, Minimum is type Number=1, Maximum is type Number=10). The cell in question has a formula attached that references another sheet (all data has been saved correctly).
I have found that is is hopeless to read, modify and save an XLS/XLSX file getting the "auto filter", "Data Validation" and "Conditional Format" from the original file, the final solution I found is to make the template using the PHPExcel library.
Sadly, as it was stated on the other answer (https://stackoverflow.com/a/13172890/218418):
PHPExcel is not a library for "editing" workbook files: you're not using PHPExcel to change a file, you're changing a PHPExcel object that can be loaded from a file, and can subsequently be written to a file.
I'm amused that something like "editing" an Excel file using a template with just data validation, conditional formating and auto filter is not possible, but I understand.
This is an old thread, but I recently ran into the same issue. It seems like PHPSpreadsheet (the new incarnation of PHPExcel) supports creating spreadsheets with conditional formatting, but when I tried to read an existing spreadsheet and then write it out to a new file, the conditional formatting was broken.
I'm planning to use xlsx-populate instead - it's nodeJS rather than PHP, but it seems to be better at writing Excel files while maintaining features of the spreadsheet (like conditional formatting) that it doesn't understand.
In my case, I have a need to populate one sheet of a large, complex spreadsheet. Values from that sheet are used in calculations and conditional formatting on other sheets, which I don't need to modify directly.
With xlsx-populate, I was able to open the spreadsheet, populate it, and save it without breaking the formatting.

How to get alt text from images in a docx file using Open XML and C#

I am creating a web form that will do a 508 compliance check on word documents. I am looking through MSDN and other sites for getting the information I need from a file the user selects. The one thing I can't find is how to find images, and check to see if they have alternative text. Any help would be GREATLY appreciated!
Images inserted into 2007+ Word documents are Drawing objects. So you can traverse the XML for w:drawing members.
http://msdn.microsoft.com/en-us/library/documentformat.openxml.wordprocessing.drawing.aspx
The w:drawing member will have a child called w:inline which is a part of the Inline class.
http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.wordprocessing.inline.aspx
The w:inline member will have a member called wd:docPr.
http://msdn.microsoft.com/en-us/library/documentformat.openxml.drawing.wordprocessing.docproperties.aspx
The wd:docPr member may have a field called title which houses the alternative text title and a field called descr which houses all the alternative text.
Example XML:
<w:drawing xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<wp:inline distT="0" distB="0" distL="0" distR="0" wp14:anchorId="357A850A" wp14:editId="384E9053" xmlns:wp14="http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">
<wp:extent cx="5943600" cy="4457700" />
<wp:effectExtent l="0" t="0" r="0" b="0" />
<wp:docPr id="1" name="Picture 1" descr="ALL TEXT HERE" title="ALT TEXT TITLE HERE"/>
...
I highly recommend you use the OpenXML Productivity Tool that comes with the OpenXML SDK.
You can do the same thing slightly more easily with unzip and a copy of lxprintf (part of the LTXML2 toolkit), by unzipping the slides in a loop and running lxprintf on each one to locate the wp:docPr element and output the values of #descr and #title, eg
for f in `unzip -l demo.pptx | grep ppt/slides/slide.*\.xml | awk '{print $NF}'`; do
unzip -p demo.pptx $f |\
lxprintf -e 'w:drawing/wp:inline/wp:docPr' "%s, %s\n" #descr #title -
done

# symbol in Drupal modules

I'm trying to learn Drupal modules. Can someone tell me what the '#' symbol is? I dont remember coming across it in PHP. (Its tricky to search for it cos as far as I can tell, you cant google for symbols). Can I convert it into a normal PHP variable, modify it and finally put it back into an # thing within the PHP of the .module file?
UPDATE: e.g.:
$error['msg'] = t("We're sorry. We have now only #qty of the ....
in file...
http://drupal.org/project/uc_out_of_stock
While that is the case in general PHP, it is used differently in Drupal within the t() function.
You can properly use placeholders in your text (which should be wrapped in t() for translation purposes on i18n capabilities) by putting a # , ! or % in front.
! = insert as is
# = run text through check_plain
% = html escape text
More info on the API page
In PHP the # symbol suppresses error messages.
There's plenty about it in the manual. When in doubt that's the place to go.
http://us3.php.net/manual/en/language.operators.errorcontrol.php

Resources