Add image to Word docx file with NPOI

2019-08-10 11:34发布

问题:

I'm getting started with NPOI for creating Word documents, and I'm trying to add a simple image to a document, but it's just not showing up. (I can get text to show fine though).

This is my code:

    var wDoc = new XWPFDocument();
    var bytes = File.ReadAllBytes(Settings.Configuration.WebsiteRootPath + "images/logo-large.png");
    wDoc.AddPictureData(bytes, (int)PictureType.JPEG);

I also tried this:

    var wDoc = new XWPFDocument();
    using (Stream s = File.OpenRead(Settings.Configuration.WebsiteRootPath + "images/logo-large.png"))
    {
        wDoc.CreateParagraph().CreateRun().AddPicture(s, (int)PictureType.JPEG, "logo-large.png", 200, 200);
    }

No luck - blank documents in both cases.

What am I doing wrong?

回答1:

Finally I have a workaround for .netCore. The problem is in generated document.xml. Following code:

  var p0 = doc.Paragraphs[0];
  var r0 = p0.CreateRun();
  r0.AddPicture(image, 6,"logo.png",Units.ToEMU(width),Units.ToEMU(height));

generates xml node:

   <wp:docPr name="Drawing 0" descr="logo.png"/>

Attribute id is missing. When you change this node to:

<wp:docPr name="Drawing 0" id="0" descr="logo.png"/>

everything should work. This happens even if you already have images in your doc and only for first record. I couldn’t find the reason and way to fix it (probably something in export part), but if you change this id to other value it will work:

var p0 = doc.Paragraphs[0];
var r0 = p0.CreateRun();
r0.AddPicture(image, 6, "logo.png", Units.ToEMU(width), Units.ToEMU(height));
var docPr = ((NPOI.OpenXmlFormats.Dml.WordProcessing.CT_Drawing)r0.GetCTR().Items[0]).inline[0].docPr;
docPr.id = 1000;

This is required only for first image in file. If you have more images following code should work too:

var p0 = doc.Paragraphs[0];
var r0 = p0.CreateRun();
r0.AddPicture(image, 6, "logo.png", Units.ToEMU(width), Units.ToEMU(height)); 
var docPr = ((NPOI.OpenXmlFormats.Dml.WordProcessing.CT_Drawing)r0.GetCTR().Items[0]) .inline[0].docPr;
docPr.id = 1000;
var p1 = doc.Paragraphs[1];
var r1 = p1.CreateRun();
r1.AddPicture(image2, 6, "cat.png", Units.ToEMU(width2), Units.ToEMU(height2));


回答2:

Make sure you have the up to date dll's (at least version 2.1.1 - released June 2014) as there were known issues/limited support for inserting Pictures into a Word docx. Version 2.1.1 officially supported inserting Pictures into a Word docx. See new features in the release notes https://npoi.codeplex.com/releases/view/115353