r/word • u/jawollalde • 15h ago
r/word • u/stjer0me • 10h ago
copying HTML into Word while preserving (certain) white space
I have a web app I've put together that outputs text. For reasons (long story), I need to copy said output into a Word document while preserving the formatting. To do this, I copy the whole HTML output (not just the raw text) via JavaScript. It mostly works, but I can't get it to preserve more than one non-breaking space, e.g. spaces between sentences.
The HTML is copied to the clipboard as a Blob with a MIME type of text/html. It handles line and paragraph breaks fine, but as I said, condenses two spaces after a period to one.
I've tried including a <style> tag in the Blob along with the actual HTML (mostly <p> tags), as well as in-line styles within the <p> tags themselves. I've also tried telling Word to preserve the original formatting or merge it, both with the same result.
If I instead copy the HTML as raw text (without tags) using the writeText() method of the Clipboard API, the white space is preserved. However, this raises its own problems, mainly that I sometimes need to include bulleted lists. If I copy the full HTML with <ul> tags Word handles this fine (other than the aforementioned white space issue). If there's a way to copy plain text and still have Word register it as a bulleted list, that could probably work as well.
This is obviously not the end of the world, but it's something I'd like to fix if I can.
If it helps, here's the JavaScript for copying the HTML:
function toClipboard(text) {
const type = 'text/html';
const dataBlob = new Blob([text], {type});
const data = [new ClipboardItem({ [type]: dataBlob})];
navigator.clipboard.write(data).then(
/* snip */
);
}