英文:
Sizing Image inside Word Document using Openxml SDK .Net c#
问题
如何获得Word文档的宽度?以及实现此任务的最佳方法是什么?
英文:
I added an image to my generated word document using openxml sdk, but iam not able to size that image to word document full width respecting the image ratio.
How can i get the word document width? And what is the best aproach to achieve this task!?
答案1
得分: 1
我现在以这种方式解决了这个问题,并且它运行正常:
// 缩小图像
SectionProperties? sectionProperties = null;
PageSize? pageSize = null;
long pageWidth = 0;
if (main.Document.Body is { })
sectionProperties = main.Document.Body.GetFirstChild
if (sectionProperties is { })
pageSize = sectionProperties.GetFirstChild
if (pageSize is { Width: { } } && pageSize is { Height: { } })
pageWidth = pageSize.Width;
if (pageWidth > width) {
var sizeFactor = pageWidth / width;
width = (int)pageWidth;
height = (int)(sizeFactor * height);
}
double englishMetricUnitsPerInch = 914400;
double pixelsPerInch = 96;
double factor = englishMetricUnitsPerInch / pixelsPerInch;
/*
- MS-Docs(OpenXml SDK,PageSize 类)
- 此输出说明此部分中的所有页面必须为11907点的二十分之一宽度(11907点的二十分之一 = 8.269“)和16839点的二十分之一高度(16939点的二十分之一 = 11.694“)。示例结束]
*/
double emuWidth = (width * factor) / 20;
double emuHeight = (height * factor) / 20;
在绘图元素内部:
Extent = new() {
Cx = (Int64Value)emuWidth,
Cy = (Int64Value)emuHeight
},
英文:
I solved it that way now and it works fine:
// Scaling down the Image
SectionProperties? sectionProperties = null;
PageSize? pageSize = null;
long pageWidth = 0;
if (main.Document.Body is { })
sectionProperties = main.Document.Body.GetFirstChild<SectionProperties>();
if (sectionProperties is { })
pageSize = sectionProperties.GetFirstChild<PageSize>();
if (pageSize is { Width: { } } && pageSize is { Height: { } })
pageWidth = pageSize.Width;
if (pageWidth > width) {
var sizeFactor = pageWidth / width;
width = (int)pageWidth;
height = (int)(sizeFactor * height);
}
double englishMetricUnitsPerInch = 914400;
double pixelsPerInch = 96;
double factor = englishMetricUnitsPerInch / pixelsPerInch;
/*
* MS-Docs (OpenXml SDK, PageSize Class)
* This output states that all pages in this section must be 11907 twentieths of
* a point wide (11907 twentieths of a point = 8.269") and 16839 twentieths of a
* point high (16939 twentieths of a point = 11.694"). end example]
*/
double emuWidth = (width * factor) / 20;
double emuHeight = (height * factor) / 20;
The inside the drawing element:
Extent = new() {
Cx = (Int64Value)emuWidth,
Cy = (Int64Value)emuHeight
},
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论