1. 程式人生 > >poi處理docx轉pdf出現空指標異常

poi處理docx轉pdf出現空指標異常

轉換過程出現這個異常
Caused by: java.lang.NullPointerException
at org.apache.poi.xwpf.converter.core.styles.run.RunUnderlineValueProvider.getValue(RunUnderlineValueProvider.java:40)

檢視原始碼得知是程式碼寫的不嚴謹

return (rPr != null && rPr.isSetU()) ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue
()) : null;

rPr.getU().getVal().intValue()這裡容易出現空指標問題

解決辦法:

  • 在自己的專案中新建一個package名為org.apache.poi.xwpf.converter.core.styles.run
  • 新建一個RunUnderlineValueProvider類,程式碼如下:
package org.apache.poi.xwpf.converter.core.styles.run;

import org.apache.poi.xwpf.converter.core.styles.XWPFStylesDocument;
import
org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTUnderline; import org.openxmlformats.schemas.wordprocessingml.x2006.main.STUnderline.Enum; /** * 解決空指標異常,jar裡面的寫法不嚴謹 */ public class
RunUnderlineValueProvider extends AbstractRunValueProvider<UnderlinePatterns> {
public static final RunUnderlineValueProvider INSTANCE = new RunUnderlineValueProvider(); @Override public UnderlinePatterns getValue(CTRPr rPr, XWPFStylesDocument stylesDocument) { if(rPr == null) { return null; } if(rPr.isSetU()) { CTUnderline u = rPr.getU(); if(u != null) { Enum val = u.getVal(); if(val != null) { return UnderlinePatterns.valueOf(val.intValue()); } } } return null; // old code // return (rPr != null && rPr.isSetU()) // ? UnderlinePatterns.valueOf(rPr.getU().getVal().intValue()) : null; } }

這樣系統會優先呼叫.