Skip to content

Instantly share code, notes, and snippets.

@shikelong
Created December 7, 2021 03:05
Show Gist options
  • Save shikelong/92f31f5f4237eb5c6ee0e75e83e61fc6 to your computer and use it in GitHub Desktop.
Save shikelong/92f31f5f4237eb5c6ee0e75e83e61fc6 to your computer and use it in GitHub Desktop.
Attach dimension style for img (get height/width value from height/width properties)
/**
* html-to-rtf-browser not recognize height/style property of img tag
* so, need add height/size to style property to avoid image lose rtf picture size.
*/
function attachDimensionStyleForImage(htmlString: string): string {
try {
const domParser = new DOMParser();
const doc = domParser.parseFromString(htmlString, "text/html");
const images = doc.getElementsByTagName("img");
for (let i = 0; i < images.length; i++) {
const image = images[i];
const width = image.getAttribute("width");
const height = image.getAttribute("height");
if (width === null || height === null) {
throw new Error("img width or height cannot be null");
}
const style = image.getAttribute("style");
if (style === null) {
image.setAttribute("style", `height:${height}px;width:${width}px;`);
} else {
image.setAttribute(
"style",
`${style};height:${height}px;width:${width}px;`
);
}
return doc.body.innerHTML;
}
} catch (error) {
console.error("attachDimensionStyleForImage error", error);
return htmlString;
}
return htmlString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment