Wstawianie obrazu do DocX za pomocą OpenXML i Ustawianie rozmiaru

Używam OpenXML do wstawiania obrazu do mojego dokumentu. Kod dostarczony przez Microsoft działa, ale sprawia, że obraz jest znacznie mniejszy:

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)));
        }

Muszę nadać obrazowi oryginalny rozmiar. Jak mogę to zrobić? (Wygooglowałem, jak to zrobić poza tym procesem, ale to nie jest to, czego szukam. Muszę założyć, że w podanym kodzie są jakieś właściwości wielkości).

Edit: Updated Code (still not working)

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)));
}
Author: MintGrowth, 2011-11-10

5 answers

Rozmiary, w EMUs (angielska Jednostka metryczna -- przeczytaj to dla dobrego wyjaśnienia ), są ustawione w zakresie (CX i Cy). Aby dostać zdjęcie do DocX zwykle robię to tak:

  1. uzyskaj wymiary i rozdzielczość obrazu
  2. Oblicz szerokość obrazu w EMUs: wEmu = imgWidthPixels / imgHorizontalDpi * emuPerInch
  3. Oblicz wysokość obrazu w EMUs: hEmu = imgHeightPixels / imgVerticalDpi * emuPerInch
  4. Oblicz stronę max szerokość w Emu (zauważyłem, że jeśli obrazek jest zbyt szeroki, to się nie pokaże)
  5. Jeśli szerokość obrazu w Emu jest większa niż maksymalna szerokość strony, skaluję szerokość i wysokość obrazu tak, aby szerokość obrazu była równa szerokości strony (Kiedy mówię strona, mam na myśli stronę "użyteczną", czyli minus marginesy):

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

  6. Następnie używam szerokości jako wartości Cx i wysokości jako wartości Cy, zarówno W DW.Extent i w A.Extents (z A.Transform2D z PIC.ShapeProperties).

Zauważ, że wartość emuPerInch to 914400.
Mam to uruchomione (w serwisie), ale nie mam kodu ze sobą w tej chwili.

UPDATE

Oto kod, którego używam:

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);
}

W moim przypadku miary mojej strony są w cm, stąd emusPerCm, który widzisz powyżej.

UPDATE 2 (do odpowiedzi @ andw)

Aby plik został zablokowany w minimalnym możliwym czasie, otwórz to z FileStream i przekazać otrzymany strumień do StreamSource własności BitmapImage:

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;
...
 47
Author: ssarabando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-15 14:26:55

Możesz nadać obrazowi jego oryginalny rozmiar w ten sposób:

Najpierw otrzymasz szerokość i wysokość pliku:

int iWidth = 0;
int iHeight = 0;
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap("yourFilePath"))
{
     iWidth = bmp.Width;
     iHeight = bmp.Height;
}

Następnie Konwertuj piksele na EMUs w ten sposób:

iWidth = (int)Math.Round((decimal)iWidth * 9525);
iHeight = (int)Math.Round((decimal)iHeight * 9525);

I na koniec podaj wartości podczas otwierania pliku, mam na myśli w tej linii kodu:

new DW.Extent() { Cx = 990000L, Cy = 792000L },

Zastąp Cx i Cy obliczonymi wartościami, aby wyglądało to tak:

new DW.Extent() { Cx = iWidth, Cy = iHeight },

Zauważ, że w Twoim kodzie są dwie linie, w których trzeba podać obliczone wartości.

Wtedy masz swój obraz w oryginalnym rozmiarze, mam nadzieję, że to komuś pomoże.

 12
Author: JCO9,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-30 08:39:07

Ten kod działa dla mnie.

Źródło: http://msdn.microsoft.com/en-us/library/office/bb497430(v=office.15). aspx

    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;
    }
 2
Author: safriend,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-22 07:45:40

To działa dla mnie w Net Core i zaimplementowane Tutaj .

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);
}
 1
Author: renemadsen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-01 07:41:39

Ponieważ jest to jeden z pierwszych hitów podczas wyszukiwania obrazów i OpenXml, a świat poszedł nieco dalej, chciałbym podzielić się rozwiązaniem @ ssarabando do obliczania emu zaadaptowanego dla. Net core, gdzie System.Drawing nie jest dostępny, używając ImageSharp (wciąż beta od listopada 2018):

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;
}
Mam nadzieję, że to oszczędzi komuś czasu.
 0
Author: Marc Wittke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-11-23 23:00:56