iT邦幫忙

0

無法使用NPOI讓Word插入頁首圖片

我目前使用的NPOI版本為2.5.4
想要在頁首增加圖片
但目前卡在一個奇怪的狀況

XWPFDocument document = new XWPFDocument();
document.Document.body.sectPr = new CT_SectPr();
CT_SectPr ctSectPr = document.Document.body.sectPr;
CT_Hdr hdr = new CT_Hdr();

XWPFRelation relation = XWPFRelation.HEADER;
var header = document.CreateRelationship(relation, XWPFFactory.GetInstance(), document.HeaderList.Count + 1) as XWPFHeader;
header.SetHeaderFooter(hdr);

using (var headerStream = new FileStream(headerImagePath, FileMode.Open, FileAccess.Read)){
    using (var reader = new BinaryReader(headerStream)){
    header.AddPictureData(reader.ReadBytes((int)reader.BaseStream.Length), (int)PictureType.JPEG);
    
    }
}
CT_HdrFtrRef hdrFtrRef = ctSectPr.AddNewHeaderReference();
hdrFtrRef.type = ST_HdrFtr.@default;
hdrFtrRef.id = header.GetPackageRelationship().Id;

其中

header.AddPictureData(reader.ReadBytes((int)reader.BaseStream.Length), (int)PictureType.JPEG);

出現System.NullReferenceException : 並未將物件參考設定為物件的執行個體。的例外狀況,但是有確定輸入都沒有Null的值出現

去看NPOI提供的範例也沒提到怎麼增加頁首圖片
網路查到的也都是舊版的寫法
/images/emoticon/emoticon02.gif


更新

後來依照海綿寶寶提供的2019年連結照著修改
順利把圖片加上頁首了
/images/emoticon/emoticon41.gif

下面是修改後的程式碼,稍微紀錄一下

XWPFDocument document = new XWPFDocument();

//XWPFParagraph paragraph = document.CreateParagraph();
//XWPFRun run = paragraph.CreateRun();

XWPFHeader header = document.CreateHeaderFooterPolicy().CreateHeader(ST_HdrFtr.@default);
            var paragraph = header.GetParagraphArray(0);
            paragraph.Alignment = ParagraphAlignment.CENTER;
            var run = paragraph.CreateRun();
            
using (var headerStream = new FileStream(headerImagePath, FileMode.Open, FileAccess.Read)){
                run.AddPicture(headerStream, (int)PictureType.JPEG, fileName, Units.ToEMU(headerW * cmCoefficient), Units.ToEMU(headerH * cmCoefficient));
}

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
海綿寶寶
iT邦大神 1 級 ‧ 2021-08-05 10:53:54
最佳解答

XWPFHeaderFooter.cs的原始碼得知
addPictureData 真的只有 addPictureData 然後回傳一個 string (id)

這篇的答案是 2019 年的
可以試試看
雖然是 java 版本
我想 C# 有相對應的 class

0
japhenchen
iT邦超人 1 級 ‧ 2021-08-05 11:24:38

我來喇滴賽....用python讀寫word docx
https://python-docx.readthedocs.io/en/latest/user/quickstart.html

(話說我現在也在用openpyxl在讀寫XLSX,比以前用C#+Epplus還高效)

WRITE LESS , DO MORE
只要底下這幾行,免安裝officeea

import docx

doc= docx.Document()
doc.add_paragraph("這是一張圖片")
doc.add_picture("C:/Users/JaphenChen/Downloads/Snipaste_2021-07-26_15-21-23.jpg")
doc.save("test.docx")

細部操作(字型大小、段落、圖片位置跟大小)可參考上述網站裡的教學

至於NPOI,我放棄

我要發表回答

立即登入回答