Add image to Word docx file with NPOI

陌路散爱 提交于 2019-12-13 19:23:57

问题


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



来源:https://stackoverflow.com/questions/29230853/add-image-to-word-docx-file-with-npoi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!