1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| name: Word不改变表格单元格大小的情况下插入图片 (1) description: Create a new snippet from a blank template. host: WORD api_set: {} script: content: | $("#insertImage").click(() => tryCatch(insertImage));
async function insertImage() { let fileInput: HTMLInputElement = document.createElement("input"); fileInput.type = "file"; fileInput.style.display = "none"; fileInput.accept = "image/*"; fileInput.onchange = async () => { var reader: FileReader = new FileReader(); reader.onload = () => { Word.run(async (context) => { let base64 = reader.result.toString(); let img = new Image(); let imgWidth = 0; let imgHeight = 0; img.src = base64; img.onload = function() { imgWidth = img.width; imgHeight = img.height; }; base64 = base64.split(",")[1]; console.log(base64); const body = context.document.getSelection(); let cell = body.parentTableCell; cell.load("width,parentRow/preferredHeight"); await context.sync(); let width = cell.width; let height = cell.parentRow.preferredHeight; let inlinePic = body.insertInlinePictureFromBase64(base64, Word.InsertLocation.replace); await context.sync(); if (imgWidth > width || imgHeight > height) { inlinePic.width = width; inlinePic.height = height; } }).catch((error) => { console.log(error); }); }; // read in the image file as a data URL. reader.readAsDataURL(fileInput.files[0]); }; fileInput.click(); }
/** Default helper for invoking an action and handling errors. */ async function tryCatch(callback) { try { await callback(); } catch (error) { // Note: In a production add-in, you'd want to notify the user through your add-in's UI. console.error(error); } } language: typescript template: content: "<div>\n\t<button id=\"insertImage\">插入图片至Word表格内,不改变单元格大小</>\n</div>" language: html style: content: |- section.samples { margin-top: 20px; }
section.samples .ms-Button, section.setup .ms-Button { display: block; margin-bottom: 5px; margin-left: 20px; min-width: 80px; }
table, th, td { border: 1px solid black; border-collapse: collapse; } language: css libraries: | https://appsforoffice.microsoft.com/lib/1/hosted/office.js @types/office-js
office-ui-fabric-js@1.4.0/dist/css/fabric.min.css office-ui-fabric-js@1.4.0/dist/css/fabric.components.min.css
core-js@2.4.1/client/core.min.js @types/core-js
jquery@3.1.1 @types/jquery@3.3.1
|