Java Word 转 Pdf
前言:
平常项目中遇到需要将word转换为pdf,我们一般利用的是jacob.jar组件,这个组件利用的是微软office组件,但有时项目需要部署到liunx下,liunx中没有office,我们可以利用apache poi实现这一功能。
代码:
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.collections.MapUtils; import org.apache.poi.xwpf.converter.pdf.PdfConverter; import org.apache.poi.xwpf.converter.pdf.PdfOptions; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableCell; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import fr.opensagres.xdocreport.utils.StringUtils; public class WordPdfUtils { protected static final Logger logger = LoggerFactory.getLogger(WordPdfUtils. class ); public static void main(String[] args) throws Exception{ String filepath = "E:/Spring_Security_安全权限管理手册.docx" ; String outpath = "E:/test.pdf" ; InputStream source = new FileInputStream(filepath); OutputStream target = new FileOutputStream(outpath); Map<String, String> params = new HashMap<String, String>(); PdfOptions options = PdfOptions.create(); wordConverterToPdf(source, target, options, params); } public static void wordConverterToPdf(InputStream source, OutputStream target, Map<String, String> params) throws Exception { wordConverterToPdf(source, target, null , params); } public static void wordConverterToPdf(InputStream source, OutputStream target, PdfOptions options, Map<String, String> params) throws Exception { XWPFDocument doc = new XWPFDocument(source); paragraphReplace(doc.getParagraphs(), params); for (XWPFTable table : doc.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { paragraphReplace(cell.getParagraphs(), params); } } } PdfConverter.getInstance().convert(doc, target, options); } private static void paragraphReplace(List<XWPFParagraph> paragraphs, Map<String, String> params) { if (MapUtils.isNotEmpty(params)) { for (XWPFParagraph p : paragraphs){ for (XWPFRun r : p.getRuns()){ String content = r.getText(r.getTextPosition()); logger.info(content); if (StringUtils.isNotEmpty(content) && params.containsKey(content)) { r.setText(params.get(content), 0 ); } } } } } }
原博文地址:
http://my.oschina.net/mingpeng/blog/337198。
备注:
1.word的后缀必须为docx格式。
2.我在使用中发现有些jar包需要特定版本,代码才能正常运行。
所使用jar包:
apache poi 3.8;com.lowagie.text-2.1.7.jar;commons-collections-3.2.1.jar;fr.opensagres.xdocreport.itext.extension-1.0.4.jar;ooxml-schemas-1.1.jar;org.apache.poi.xwpf.converter.core-1.0.4.jar;org.apache.poi.xwpf.converter.pdf-1.0.4.jar