Java 实现 word(docx版本)转 pdf

docx文件转pdf,支持数据源(文字和图片)替换。   字体链接在最下方!!!

poi 3.15版本。

替换word文件内容后直接通过fr.opensagres.xdocreport转成pdf。 


   org.apache.poi
   ooxml-schemas
   1.3



    org.apache.poi
    poi-ooxml
    3.15



    fr.opensagres.xdocreport
    org.apache.poi.xwpf.converter.pdf
    1.0.6
    
	    
		    org.apache.poi
		    poi-ooxml
	    
	    
		    org.apache.poi
		    poi-ooxml-schemas
	    
	    
		    org.apache.poi
		    ooxml-schemas
	    
    
package com.dz.demo.utils;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * Created by dzwang on 2018/12/11.
 */
public class WordUtil {
    private static Pattern pattern = Pattern.compile("\\$\\{[a-zA-Z_0-9:.#]+\\}");

    /**
     * 根据指定的参数值、模板,生成 word 文档
     *
     * @param param    需要替换的变量
     * @param template 模板
     */
    public static XWPFDocument generateWord(Map param, String template) {
        XWPFDocument doc = null;
        try {
            OPCPackage pack = POIXMLDocument.openPackage(template);
            doc = new XWPFDocument(pack);
            if (param != null && param.size() > 0) {

                //处理段落
                List paragraphList = doc.getParagraphs();
                processParagraphs(paragraphList, param, doc);

                //处理表格
                Iterator it = doc.getTablesIterator();
                while (it.hasNext()) {
                    XWPFTable table = it.next();
                    List rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        List cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            List paragraphListTable = cell.getParagraphs();
                            processParagraphs(paragraphListTable, param, doc);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    /**
     * 处理段落
     *
     * @param paragraphList
     */
    private static void processParagraphs(List paragraphList, Map param, XWPFDocument doc) throws Exception {
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                List runs = paragraph.getRuns();
                for (XWPFRun run : runs) {
                    String text = run.getText(0);
                    if (text != null) {
                        text = text.trim();
                        if (pattern.matcher(text).matches() && param.get(text) != null) {
                            Object value = param.get(text);
                            if (value instanceof String) {//文本替换
                                text = text.replace(text, value.toString());
                            } else if (value instanceof Map) {//图片替换
                                text = text.replace(text, "");
                                Map pic = (Map) value;
                                int width = (int) pic.get("width");
                                int height = (int) pic.get("height");
                                int picType = getPictureType(pic.get("type").toString());
                                byte[] byteArray = (byte[]) pic.get("content");
                                ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                                try {
                                    String ind = doc.addPictureData(byteInputStream, picType);
                                    createPicture(ind, width, height, run);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                text = text.replace(text, value.toString());
                            }
                            run.setText(text, 0);
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据图片类型,取得对应的图片类型代码
     *
     * @param picType
     * @return int
     */
    private static int getPictureType(String picType) {
        int res = XWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = XWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = XWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = XWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = XWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = XWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    /**
     * 将输入流中的数据写入字节数组
     *
     * @param in
     * @return
     */
    public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (isClose) {
                try {
                    in.close();
                } catch (Exception e2) {
                    System.out.println("关闭流失败");
                }
            }
        }
        return byteArray;
    }

    private static void createPicture(String blipId, int width, int height, XWPFRun run) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        CTInline inline = run.getCTR().addNewDrawing().addNewInline();
        String picXml = ""
                + ""
                + "   "
                + "      "
                + "         " + "            "
                + "            "
                + "         "
                + "         "
                + "            "
                + "            "
                + "               "
                + "            "
                + "         "
                + "         "
                + "            "
                + "               "
                + "               "
                + "            "
                + "            "
                + "               "
                + "            "
                + "         "
                + "      "
                + "   " + "";

        inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try {
            xmlToken = XmlToken.Factory.parse(picXml);
        } catch (XmlException xe) {
            xe.printStackTrace();
        }
        inline.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);
    }
}
package com.dz.demo;

import com.dz.demo.utils.WordUtil;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import fr.opensagres.xdocreport.itext.extension.font.IFontProvider;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class Word2Pdf {
    private final static String DOC_X = "D:\\test.docx";
    private final static String PDF = "D:\\test.pdf";

    public static void main(String[] args) {
        try {
            Map param = new HashMap();
            param.put("${name}", "dz");
            param.put("${sex}", "male");

            Map image = new HashMap();
            image.put("width", 300);
            image.put("height", 300);
            image.put("type", "png");
            image.put("content", WordUtil.inputStream2ByteArray(new FileInputStream("D:\\3.png"), true));
            param.put("${image}", image);


            XWPFDocument doc = WordUtil.generateWord(param, DOC_X);
            // 在没有字体的服务器上发布要用到下面 options,同时在resource目录下加入字体文件, windows 服务器上可不加
            PdfOptions options = PdfOptions.create();
            options.fontProvider(new IFontProvider() {

                @Override
                public Font getFont(String familyName, String encoding, float size, int style, java.awt.Color color) {
                    try {
                        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
                        Font fontChinese = new Font(bfChinese, size, style, color);
                        if (familyName != null)
                            fontChinese.setFamily(familyName);
                        return fontChinese;
                    } catch (Exception e) {
                        e.printStackTrace();
                        return null;
                    }
                }
            });
            OutputStream out = new FileOutputStream(PDF);
            PdfConverter.getInstance().convert(doc, out, options);
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

字体文件下载地址:https://download.csdn.net/download/fyzzlz/10867139

字体文件放置如下图:

Java 实现 word(docx版本)转 pdf_第1张图片

你可能感兴趣的:(Java)