C# 使用OpenXML将图像插入DocX并设置大小
我正在使用OpenXML将图像插入到文档中。Microsoft提供的代码可以正常工作,但会使图像变得更小:C# 使用OpenXML将图像插入DocX并设置大小,c#,image,openxml,docx,C#,Image,Openxml,Docx,我正在使用OpenXML将图像插入到文档中。Microsoft提供的代码可以正常工作,但会使图像变得更小: public static void InsertAPicture(string document, string fileName) { using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(document, true))
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)));
}
我需要使图像保持原来的大小。我该怎么做?(我已经在谷歌上搜索了如何在这个过程之外做到这一点,但这不是我想要的。我必须假设给定代码中有某种大小属性)
编辑:更新的代码(仍不工作)
以EMUs()为单位的大小在区段(Cx和Cy)中设置。
为了将一张照片放入DocX,我通常这样做:
var比率=hEmu/wEmu代码>
wEmu=maxPageWidthEmu代码>
hEmu=wEmu*比值代码>
DW.Extent
和A.extends
(在PIC.ShapeProperties的A.Transform2D
中)
我正在运行(在服务中),但我现在没有代码 更新 这是我使用的代码:
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);
}
在我的例子中,我的页面的度量单位是cm,因此您可以看到上面的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;
...
这个代码对我有用 资料来源:
publicstaticvoiddo()
{
字符串文件名=@“c:\temp\m.docx”;
字节[]reportData=GetWordReport();
//writealBytes(文件名、报表数据);
//Show(“文件”+文件名+“已创建”);
}
私有静态字节[]GetWordReport()
{
//使用(MemoryStream stream=new MemoryStream())
// {
//var template=GetTemplateData();
//stream.Write(template,0,template.Length);
使用(WordprocessingDocument docx=WordprocessingDocument.Open(@“c:\temp\m.docx”,true))
{
//docx的一些变化
docx.MainDocumentPart.Document=GenerateMainDocumentPart(6,4);
var imagePart=docx.MainDocumentPart.AddNewPart(“image/jpeg”、“rIdImagePart1”);
生成图像部件(图像部件);
}
//stream.Seek(0,SeekOrigin.Begin);
//返回流ToArray();
// }
返回null;
}
私有静态字节[]GetTemplateData()
{
使用(MemoryStream targetStream=new MemoryStream())
使用(BinaryReader sourceReader=new BinaryReader(File.Open(@“c:\temp\m_2.docx”,FileMode.Open)))
{
字节[]缓冲区=新字节[4096];
int num=0;
做
{
num=sourceReader.Read(缓冲区,04096);
如果(数值>0)
写入(缓冲区,0,num);
}
而(num>0);
Seek(0,SeekOrigin.Begin);
返回targetStream.ToArray();
}
}
私有静态void GenerateImagePart(OpenXmlPart)
{
使用(Stream-imageStream=File.Open(@“c:\temp\image002.jpg”,FileMode.Open))
{
部分。FeedData(imageStream);
}
}
私有静态文档生成器IndocumentPart(int cx,int cy)
{
长LCX=cx*261257L;
长LCY=cy*261257L;
变量元素=
新文件(
新机构(
新段落(
新运行(
新运行属性(
新NoProof()),
新图纸(
新wp.Inline(
新的wp.Extent(){Cx=LCX,Cy=LCY},
新的wp.EffectExtent(){LeftEdge=0L,TopEdge=19050L,RightEdge=0L,BottomEdge=0L},
新的wp.DocProperties(){Id=(UInt32Value)1U,Name=“Picture 0”,Description=“Forest Flowers.jpg”},
新wp.NonVisualGraphic FrameDrawingProperties(
新的a.GraphicFrameLocks(){NoChangeAspect=true}),
新a.图形(
新a.GraphicData(
新图片(
新图片。非可视图片属性(
新pic.NonVisualDrawingProperties(){Id=(UInt32Value)0U,Name=“Forest Flowers.jpg”},
新图片:NonVisualPictureDrawingProperties()),
新图片。布利普菲尔(
新的a.Blip(){Embed=“rIdImagePart1”,CompressionState=a.BlipCompressionValues.Print},
新的a.伸展运动(
新的a.FillRectangle()),
新pic.ShapeProperties(
氖
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;
...
public static void Do()
{
string filename = @"c:\temp\m.docx";
byte[] reportData = GetWordReport();
// File.WriteAllBytes(filename, reportData);
//MessageBox.Show("File " + filename + " created");
}
private static byte[] GetWordReport()
{
// using (MemoryStream stream = new MemoryStream())
// {
//var template = GetTemplateData();
//stream.Write(template, 0, template.Length);
using (WordprocessingDocument docx = WordprocessingDocument.Open(@"c:\temp\m.docx", true))
{
// Some changes on docx
docx.MainDocumentPart.Document = GenerateMainDocumentPart(6,4);
var imagePart = docx.MainDocumentPart.AddNewPart<ImagePart>("image/jpeg", "rIdImagePart1");
GenerateImagePart(imagePart);
}
// stream.Seek(0, SeekOrigin.Begin);
// return stream.ToArray();
// }
return null;
}
private static byte[] GetTemplateData()
{
using (MemoryStream targetStream = new MemoryStream())
using (BinaryReader sourceReader = new BinaryReader(File.Open(@"c:\temp\m_2.docx", FileMode.Open)))
{
byte[] buffer = new byte[4096];
int num = 0;
do
{
num = sourceReader.Read(buffer, 0, 4096);
if (num > 0)
targetStream.Write(buffer, 0, num);
}
while (num > 0);
targetStream.Seek(0, SeekOrigin.Begin);
return targetStream.ToArray();
}
}
private static void GenerateImagePart(OpenXmlPart part)
{
using (Stream imageStream = File.Open(@"c:\temp\image002.jpg", FileMode.Open))
{
part.FeedData(imageStream);
}
}
private static Document GenerateMainDocumentPart(int cx,int cy)
{
long LCX = cx*261257L;
long LCY = cy*261257L;
var element =
new Document(
new Body(
new Paragraph(
new Run(
new RunProperties(
new NoProof()),
new Drawing(
new wp.Inline(
new wp.Extent() { Cx = LCX, Cy = LCY },
new wp.EffectExtent() { LeftEdge = 0L, TopEdge = 19050L, RightEdge = 0L, BottomEdge = 0L },
new wp.DocProperties() { Id = (UInt32Value)1U, Name = "Picture 0", Description = "Forest Flowers.jpg" },
new wp.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 = "Forest Flowers.jpg" },
new pic.NonVisualPictureDrawingProperties()),
new pic.BlipFill(
new a.Blip() { Embed = "rIdImagePart1", 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 = LCX, Cy = LCY }),
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 }))
) { RsidParagraphAddition = "00A2180E", RsidRunAdditionDefault = "00EC4DA7" },
new SectionProperties(
new PageSize() { Width = (UInt32Value)11906U, Height = (UInt32Value)16838U },
new PageMargin() { Top = 1440, Right = (UInt32Value)1800U, Bottom = 1440, Left = (UInt32Value)1800U, Header = (UInt32Value)851U, Footer = (UInt32Value)992U, Gutter = (UInt32Value)0U },
new Columns() { Space = ((UInt32Value)425U).ToString() },
new DocGrid() { Type = DocGridValues.Lines, LinePitch = 312 }
) { RsidR = "00A2180E", RsidSect = "00A2180E" }));
return element;
}
int iWidth = 0;
int iHeight = 0;
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourFilePath"))
{
iWidth = bmp.Width;
iHeight = bmp.Height;
}
iWidth = (int)Math.Round((decimal)iWidth * 9525);
iHeight = (int)Math.Round((decimal)iHeight * 9525);
new DW.Extent() { Cx = 990000L, Cy = 792000L },
new DW.Extent() { Cx = iWidth, Cy = iHeight },
const int emusPerInch = 914400;
const int emusPerCm = 360000;
long widthEmus;
long heightEmus;
Image<Rgba32> img = Image.Load(sourceStream, new PngDecoder());
switch (img.MetaData.ResolutionUnits)
{
case PixelResolutionUnit.PixelsPerCentimeter :
widthEmus = (long)(img.Width / img.MetaData.HorizontalResolution * emusPerCm);
heightEmus = (long)(img.Height / img.MetaData.VerticalResolution * emusPerCm);
break;
case PixelResolutionUnit.PixelsPerInch:
widthEmus = (long)(img.Width / img.MetaData.HorizontalResolution * emusPerInch);
heightEmus = (long)(img.Height / img.MetaData.VerticalResolution * emusPerInch);
break;
case PixelResolutionUnit.PixelsPerMeter:
widthEmus = (long)(img.Width / img.MetaData.HorizontalResolution * emusPerCm * 100);
heightEmus = (long)(img.Height / img.MetaData.VerticalResolution * emusPerCm * 100);
break;
default:
widthEmus = 2000000;
heightEmus = 2000000;
break;
}
long iWidth = 0;
long iHeight = 0;
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(fullPathToImageFile))
{
iWidth = bmp.Width;
iHeight = bmp.Height;
}
iWidth = (long)Math.Round((decimal)iWidth * 9525);
iHeight = (long)Math.Round((decimal)iHeight * 9525);
double maxWidthCm = 17.4; // Our current margins gives us 17.4cm of space
const int emusPerCm = 360000;
long maxWidthEmus = (long)(maxWidthCm * emusPerCm);
if (iWidth > maxWidthEmus) {
var ratio = (iHeight * 1.0m) / iWidth;
iWidth = maxWidthEmus;
iHeight = (long)(iWidth * ratio);
}