gpt4 book ai didi

c# - 使用 OpenXML 将图像插入 DocX 并设置大小

转载 作者:IT王子 更新时间:2023-10-29 04:14:15 26 4
gpt4 key购买 nike

我正在使用 OpenXML 将图像插入到我的文档中。 Microsoft 提供的代码可以工作,但会使图像变小:

public static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}

AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart));
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId)
{
// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});

// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}

我需要将图像设为原始大小。我怎样才能做到这一点? (我用谷歌搜索了如何在此过程之外执行此操作,但这不是我要找的。我必须假设给定代码中有某种大小属性)。

编辑:更新代码(仍然不工作)

public static void InsertAPicture(string document, string fileName)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
{
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);

using (FileStream stream = new FileStream(fileName, FileMode.Open))
{
imagePart.FeedData(stream);
}

AddImageToBody(wordprocessingDocument, mainPart.GetIdOfPart(imagePart), fileName);
}
}
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, string fileName)
{

var img = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
var widthPx = img.PixelWidth;
var heightPx = img.PixelHeight;
var horzRezDpi = img.DpiX;
var vertRezDpi = img.DpiY;
const int emusPerInch = 914400;
const int emusPerCm = 360000;
var maxWidthCm = 16.51;
var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch);
var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch);
var maxWidthEmus = (long)(maxWidthCm * emusPerCm);
if (widthEmus > maxWidthEmus)
{
var ratio = (heightEmus * 1.0m) / widthEmus;
widthEmus = maxWidthEmus;
heightEmus = (long)(widthEmus * ratio);
}

// Define the reference of the image.
var element =
new Drawing(
new DW.Inline(
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DW.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DW.NonVisualGraphicFrameDrawingProperties(
new A.GraphicFrameLocks() { NoChangeAspect = true }),
new A.Graphic(
new A.GraphicData(
new PIC.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new PIC.NonVisualPictureDrawingProperties()),
new PIC.BlipFill(
new A.Blip(
new A.BlipExtensionList(
new A.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState = A.BlipCompressionValues.Print
},
new A.Stretch(
new A.FillRectangle())),
new PIC.ShapeProperties(
new A.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = widthEmus, Cy = heightEmus }),
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});

// Append the reference to body, the element should be in a Run.
wordDoc.MainDocumentPart.Document.Body.AppendChild(new Paragraph(new Run(element)));
}

最佳答案

EMU 中的大小 (English Metric Unit -- read this for a good explanation) 在范围(Cx 和 Cy)中设置。为了将图片放入 DocX,我通常这样做:

  1. 获取图片的尺寸和分辨率
  2. 计算 EMU 中的图像宽度:wEmu = imgWidthPixels/imgHorizo​​ntalDpi * emuPerInch
  3. 计算 EMU 中的图像高度:hEmu = imgHeightPixels/imgVerticalDpi * emuPerInch
  4. 计算 EMU 中的最大页面宽度(我发现如果图像太宽,则不会显示)
  5. 如果 EMU 中的图像宽度大于最大页面宽度,我会缩放图像的宽度和高度,使图像的宽度等于页面的宽度(当我说页面时,我指的是到“可用”页面,即减去边距):

    var ratio = hEmu/wEmu;
    wEmu = maxPageWidthEmu;
    hEmu = wEmu * 比率;

  6. 然后我将宽度用作 Cx 的值,将高度用作 Cy 的值,两者DW.Extent 中A.Extents(PIC.ShapePropertiesA.Transform2D)。

请注意,emuPerInch 值为 914400。
我有这个运行(在服务中),但我现在没有代码。

更新

这是我使用的代码:

var img = new BitmapImage(new Uri(fileName, UriKind.RelativeOrAbsolute));
var widthPx = img.PixelWidth;
var heightPx = img.PixelHeight;
var horzRezDpi = img.DpiX;
var vertRezDpi = img.DpiY;
const int emusPerInch = 914400;
const int emusPerCm = 360000;
var widthEmus = (long)(widthPx / horzRezDpi * emusPerInch);
var heightEmus = (long)(heightPx / vertRezDpi * emusPerInch);
var maxWidthEmus = (long)(maxWidthCm * emusPerCm);
if (widthEmus > maxWidthEmus) {
var ratio = (heightEmus * 1.0m) / widthEmus;
widthEmus = maxWidthEmus;
heightEmus = (long)(widthEmus * ratio);
}

在我的例子中,我的页面尺寸以厘米为单位,因此您在上面看到的是 emusPerCm。

更新 2(回答@andw)

要在尽可能短的时间内锁定文件,请使用 FileStream 打开它,并将生成的流传递给 BitmapImage StreamSource 属性:

var img = new BitmapImage();
using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) {
img.BeginInit();
img.StreamSource = fs;
img.EndInit();
}
// The file is now unlocked
var widthPx = img.PixelWidth;
...

关于c# - 使用 OpenXML 将图像插入 DocX 并设置大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8082980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com