在Word文档中使用OpenXML SDK .Net C#调整图像大小。

huangapple go评论50阅读模式
英文:

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
},

huangapple
  • 本文由 发表于 2023年2月10日 16:42:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408697.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定