How to extract Header and Footer section from openXML file? - ms-word

I have Open Xml file which has Header, Body and Footer content. When I am trying to insert that open Xml it always picking only Body related part and not able to extract Header & Footer section data out of it.
I tried below snippet, but it always printing Body part data instead of Header data which resides in Header1.xml
ps: WORD_OPEN_XML is holding whole content
async function insertHeader() {
Word.run(async (context) => {
const mySections = context.document.sections;
context.load(mySections);
await context.sync();
for (let i = 0; i < mySections.items.length; i++) {
mySections.items[i].getHeader('Primary').insertOoxml(WORD_OPEN_XML, 'Replace');
}
await context.sync();
});
}
Please help me to insert Header and Footer part from that open Xml
WORD_OPEN_XML

Related

Attaching paragraph to the top of nested list highlights level change

I'm working on a simple office-js Word app, built with the Yeoman Generator. I have a very basic document with the following structure:
1. This is heading one
1.1 This is subheading 1
1.2 This is subheading 2
Some random text here...
Paragraph I want to attach to the list from the beginning of my doc
When I try to attach this last paragraph to my list though, I'm getting the following output:
Word document's screenshot:
It looks as though it's first trying to insert it to the level=1 of that list (thus the initial 3) and then actually inserts it to the root list's position (thus the secondary 2).
The code I'm running looks as follows:
const insertHeading = async (event: Office.AddinCommands.Event) => {
try {
await Word.run(async (context) => {
const selection = context.document.getSelection();
selection.load("paragraphs");
await context.sync();
const lists = context.document.body.lists;
const list = lists.getFirst();
const paragraph = selection.paragraphs.getFirst();
list.load("id");
await context.sync();
paragraph.attachToList(list.id, 0);
await context.sync();
})
} catch (error) {
console.info("Error occurred", error.debugInfo);
} finally {
event.completed();
}
}
I'd expect this paragraph to be added as 2nd item of the root level (with 2.) and without this turquoise strike, shown in the image above.
Any help would be much appreciated!

Open existing Word document in office js

I'm new in office js and I want to know if is possible to open an existing document in Word add-in. I've already tried get my file as base64 but didn't work ->
function dataURLtoFile() {
Word.run(async (context) => {
var body = context.document.body;
body.insertFileFromBase64(getBase64(), Word.InsertLocation.start);
await context.sync();
console.log('Added base64 encoded text to the beginning of the document body.');
});
}

Express [413 too large] with QuillJS image

I am trying to use QuillJS to let the user write a rich text, and then store it as JSON to display later on. There are 2 of these rich text areas in a single form, and may include images. QuillJS encodes images as base64 strings, and my POST request results in 413 by Express.
I have tried to change the limits by adding express json parameters, even trying extreme numbers.
// app.js
//----------------------------------------------------
// Middlewares
//----------------------------------------------------
app.use(express.json({limit: '2000mb'}));
app.use(express.urlencoded({extended: true, limit:'2000mb'}));
Even this did not help and I think it is not logical to let these parameters with such values.
I tried with json and urlencoded enctypes. When I tried to post with multipart/form, req.body was empty.
// My html page (pugJS)
form(enctype='application/x-www-form-urlencoded', action='/editor/page',
method='POST', onsubmit='return addContent()')
.form-control
label Content-1
div#toolbar
div#editor
input#content(name='content', type='text', hidden)
addContent() function that runs before form submit simply changes input#content's value with JSON.stringify(#editor.getContents())
I want to be able to store two quill content in a single database row, to display later.
A better approach to this would be to overwrite the image upload function and then save the image in Amazon S3 or some cloud server. Then you paste it inside the editor as <img src="http://uploaded-image-url"> This would solve your problem of maximum memory issue.
I fixed my problem few hours before #argo mentioned and I did it that way. So I wanted to post little bit of detail to the solution. I have been also guided by a github issue but can't seem to find the link again, in case I find it I will edit the post and add it.
// Quill - EN content
var quillEn = new Quill('#editor-en', {
modules: {
toolbar: toolbarOptions
},
theme: 'snow'
});
// set custom image handler
quillEn.getModule('toolbar').addHandler('image', () => {
selectLocalImage(quillEn);
});
// create fake input to upload image to quill
function selectLocalImage(editor) {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/png, image/jpeg')
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
saveImageToServer(editor, file);
};
}
// upload image to server
function saveImageToServer(editor, file) {
const fd = new FormData();
fd.append('image', file);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/page/upload_image', true);
xhr.onload = () => {
if (xhr.status === 200) {
// this is callback data: url
const url = JSON.parse(xhr.responseText).data;
insertToEditor(editor, url);
}
};
xhr.send(fd);
}
// manipulate quill to replace b64 image with uploaded image
function insertToEditor(editor, url) {
// push image url to rich editor.
const range = editor.getSelection();
editor.insertEmbed(range.index, 'image', url.toString());
}
In the backend where you POST image, you must return json as { data: FullUrlToImg } with 200 response, if you want to change your status to 201 or something else, don't forget to update it in saveImageToServer function.
So to summarize, you set custom image handler for your quill editor, you post the image to server as soon as user chooses to insert, then you replace the URL with your uploaded image in the editor.
Thanks.

OfficeJS deleting headers on load

I have a simple piece of code that loads headers and then changes some text in them. Recently an issue was reported where the headers are deleted. I've tracked it down to happening on loading the headers for these documents, and it appears they have 'Link to Previous' selected in the header options. I'm not sure why this would cause it to be deleted as the code up to that point makes no changes. Even this simple snippet causes the same issue.
Word.run(function (context) {
var sections = context.document.sections;
context.load(sections);
return context.sync().then(function() {
if (sections !== null) {
var headers = [];
for (var i = 0; i < sections.items.length; i++) {
var header = sections.items[i].getHeader('primary');
context.load(header);
headers.push(header);
}
context.sync().then(function() {
// when you get here all headers are deleted.
});
}
}).then(context.sync);
});
After some testing, what's really happening is that the LinkToPrevious setting is being removed. When that happens the content of the original header is removed from that header, which leaves nothing.
I could determine this by alternating the setting from section to section (on/off).
LinkToPrevious is not supported in the Office JS API that I can find, which may explain why the setting isn't being respected. I consider this a bug.
The only possibility to work around this that occurs to me would be to work over the Word Open XML for the headers.

How to change the header and footer in the Section Breaks Next Page using OpenXML?

I have a word document file in which I added a Section Break of Next Page, now I want to change the header and footer of that page.
Scenario of example, I have a doc file which has four pages with headers and footers and added fifth page in the section break next page, I want to change the header and footer of the fifth page only. This is achievable manually by deselecting the Link to Previous button in the Word Application but I don't know how to change it using XML?
My code that adds the new page in the section breaks is:
class Program
{
static void Main(string[] args)
{
string path = #"C:\sample.docx";
string strtxt = "Hello This is done by programmatically";
OpenAndAddTextToWordDocument(path,strtxt);
}
public static void OpenAndAddTextToWordDocument(string filepath, string txt)
{
using (DocX document = DocX.Load(#"C:\Riyaz\sample.docx"))
{
document.InsertSectionPageBreak();
Paragraph p1 = document.InsertParagraph();
p1.Append("This is new section");
document.Save();
}
}
}
Please help.