2011-11-10 9 views
25

की स्थापना मैं OpenXML उपयोग कर रहा हूँ मेरे दस्तावेज़ में चित्र सम्मिलित करने के लिए docx में छवि सम्मिलित करना। माइक्रोसॉफ्ट द्वारा प्रदान किया गया कोड काम करता है, लेकिन छवि को बहुत छोटा बनाता है:OpenXML का उपयोग कर और आकार

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

मुझे छवि को अपना मूल आकार बनाने की आवश्यकता है। मैं यह कैसे कर सकता हूँ? (मैं googled है कि कैसे इस प्रक्रिया के इस बाहर करना है, लेकिन यह है कि मैं क्या देख रहा हूँ नहीं है। मुझे लगता है के लिए दिया कोड के अंदर आकार गुण किसी प्रकार देखते हैं कि है)।

संपादित करें: कोड अपडेट किया गया (अभी भी काम नहीं)

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

उत्तर

37

आकार, ईएमयू (English Metric Unit -- read this for a good explanation) में, विस्तार (Cx और Cy) में स्थापित कर रहे हैं। आदेश में एक docx में एक तस्वीर प्राप्त करने के लिए मैं आमतौर पर इतना है कि यह कार्य करें: wEmu = imgWidthPixels/imgHorizontalDpi * emuPerInch

  • कंप्यूट:

    1. छवि के आयाम और संकल्प
    2. कंप्यूट ईएमयू में छवि की चौड़ाई जाओ हेमू = imgHeightPixels/imgVerticalDpi * emuPerInch
    3. कंप्यूट ईएमयू में अधिकतम पेज चौड़ाई (मैं पाया है कि अगर चित्र बहुत व्यापक है, यह प्रदर्शित नहीं होगा)
    4. यदि छवि की चौड़ाई: ईएमयू में छवि की ऊंचाई ईएमयू में से अधिक है अधिकतम पेज चौड़ाई के, मैं छवि के चौड़ाई और ऊंचाई पैमाने ताकि छवि की चौड़ाई पेज के बराबर है (जब मैं पेज कहता हूँ, मैं "प्रयोग करने योग्य" पृष्ठ की चर्चा करते हुए हूँ, वह यह है कि शून्य से मार्जिन):

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

    5. मैं तो Cy के मूल्य के रूप में Cx के मूल्य और ऊंचाई के रूप में चौड़ाई का उपयोग, DW.Extent में दोनों और A.Extents में (के PIC.ShapeProperties की A.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; 
    ... 
    
  • +0

    क्या छवि चौड़ाई और ऊंचाई दोनों के लिए डीपीआई स्थिर है? मैं इसकी गणना कैसे करूं? –

    +0

    मैं उन्हें निरंतर नहीं मानता लेकिन मुझे अभी तक एक ऐसा नहीं मिला है जहां वे नहीं हैं। यदि आप [बिटमैप इमेज] (http://msdn.microsoft.com/en-us/library/ms619218.aspx) वर्ग (System.Windows.Media.Imaging नामस्थान) के साथ छवि खोलते हैं, तो इसमें निम्न गुण हैं जो आप कर सकते हैं उपयोग करें: 'पिक्सेल विड्थ', 'पिक्सेलहेइट', 'डीपीआईएक्स',' डीपीआईवाई '। – ssarabando

    +0

    मैंने अपने उत्तर में एक कोड नमूना जोड़ा है। – ssarabando

    2

    इस कोड मेरे लिए काम करता है।

    स्रोत: 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; 
        } 
    
    +1

    उस स्रोत को जोड़ने की देखभाल करें जहां आपको यह पता चलता है? क्योंकि यह आपकी खुद की "खोज" नहीं है। – Styxxy

    +0

    http://msdn.microsoft.com/en-us/library/office/bb497430(v=office.15).aspx –

    2

    आप छवि अपने मूल आकार करने के लिए इस तरह से दे सकते हैं: फिर

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

    Cx और Cy की जगह तो अपने गणना मूल्यों के साथ यह इस तरह दिखता है:

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

    सूचना वहाँ यो में दो लाइनें है यूआर कोड जहां आपको गणना मूल्यों को देना है।

    तब आपकी छवि आपकी मूल आकार में है, उम्मीद है कि इससे किसी की मदद मिलती है।

    संबंधित मुद्दे