Skip to content

NPOI版本2.3.0生成的带图片的docx,Word打开时报错,但2.1.3版本则可正常打开 #24

@tomtdev

Description

@tomtdev

使用NPOI版本2.3.0生成的带图片的docx,Word打开时报错。但切换回旧版本2.1.3版本则可以正常打开,测试代码:

        XWPFDocument docx = new XWPFDocument();
        using (FileStream picFile = new FileStream("1.png", FileMode.Open, FileAccess.Read))
        {
            docx.CreateParagraph().CreateRun().AddPicture(picFile, (int)PictureType.PNG, "1", (int)(400.0 * 9525), (int)(300.0 * 9525));
        }

        using (FileStream file = File.Create("Image.docx"))
        {
            docx.Write(file);
        }

经过检查,发现用2.3.0版本生成的docx文件中,word/document.xml有问题:

<wp:docPr name="Drawing 0" descr="1"></wp:docPr>

对比2.1.3版本,2.1.3版本则多了id属性:

<wp:docPr id="1" name="Drawing 1" descr="1"></wp:docPr>

将id="1"添加到2.3.0版本的 word/document.xml ,打包生成docx,用Word打开正确。

这可能是序列化时产生的bug。临时解决方案:

XWPFDocument docx = new XWPFDocument();
XWPFParagraph para = docx.CreateParagraph();
XWPFRun run = para.CreateRun();
run.AddPicture(imageStream, (int)PictureType.PNG, "1.png", width, height);
CT_Inline inline = run.GetCTR().GetDrawingList()[0].inline[0];
inline.docPr.id = 1; //id必须从1开始

也就是强制赋予一个Id值以后,问题即可解决。

这样看,是否可在NPOI的代码里修复?

谢谢!

Activity

wlclass

wlclass commented on Jun 25, 2018

@wlclass

谢谢,我也碰到过。

tomtdev

tomtdev commented on Jun 26, 2018

@tomtdev
Author

@wlclass 主项目中已经合并了补丁:https://github.com/tonyqus/npoi

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @wlclass@tomtdev

        Issue actions

          NPOI版本2.3.0生成的带图片的docx,Word打开时报错,但2.1.3版本则可正常打开 · Issue #24 · svn2github/npoi