aspose-words实战(三)

aspose-words实战word转pdf(三)

  1. 参考(一)文档准备依赖和获得授权

  2. word转pdf工具类

    package com.pcr.embed.util.aspose;
    
    import com.aspose.words.Document;
    import com.aspose.words.FontSettings;
    import com.aspose.words.Range;
    import com.pcr.embed.entity.pcr.PcrData;
    
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.text.SimpleDateFormat;
    import java.util.List;
    import java.util.UUID;
    import java.util.regex.Pattern;
    
    import static java.util.regex.Pattern.compile;
    
    /**
     * 文件转PDF
     * <p>
     * Aspose下载地址:https://repository.aspose.com/repo/com/aspose/
     */
    public class PdfUtils {
    
        /**
         * word 转为 pdf 输出
         *
         * @param inputStream  word文件
         * @param outPath pdf 输出文件目录
         */
        public static String word2pdf(InputStream inputStream,
                                      String outPath,
                                      ReplaceAndInsertTableImage replaceAndInsertTableImage,
                                      ReplaceAndInsertTable replaceAndInsertTable,
                                      PcrData pcrData) {
            // 验证License
    //        if (!isWordLicense()) {
    //            return null;
    //        }
            AsposeUtil.getLicense();
            FileOutputStream os = null;
            try {
                String path = outPath.substring(0, outPath.lastIndexOf(File.separator));
                File file = new File(path);
                // 创建文件夹
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 新建一个空白pdf文档
                file = new File(outPath);
                os = new FileOutputStream(file);
                // Address是将要被转化的word文档
                Document doc = new Document(inputStream);
                FontSettings.setFontsFolder("/home/fonts", false);
                Range range = doc.getRange();
              	 //替换图片
                range.replace(compile("\\d{6}"), replaceAndInsertTableImage, true);
              	//替换表格
                range.replace(compile("\\d{5}"), replaceAndInsertTable, true);
              	//替换字符串
                range.replace("kitno", pcrData.getKitNo(), true, true);
                String format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(pcrData.getStartTime());
                range.replace("startTime", format, true, true);
                range.replace("deviceno", pcrData.getDeviceNo(), true, true);
                // 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                doc.save(os, com.aspose.words.SaveFormat.PDF);
                os.close();
            } catch (Exception e) {
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                e.printStackTrace();
            }
            return outPath;
        }
    
        /**
         * 验证 Aspose.word 组件是否授权
         * 无授权的文件有水印和试用标记
         */
        public static boolean isWordLicense() {
            boolean result = false;
            try {
                // 避免文件遗漏
                String licensexml = "<License>\n" +
                        "<Data>\n" +
                        "<Products>\n" +
                        "<Product>Aspose.Total for Java</Product>\n" +
                        "<Product>Aspose.Words for Java</Product>\n" +
                        "</Products>\n" +
                        "<EditionType>Enterprise</EditionType>\n" +
                        "<SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
                        "<LicenseExpiry>20991231</LicenseExpiry>\n" +
                        "<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
                        "</Data>\n" +
                        "<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
                        "</License>";
                InputStream inputStream = new ByteArrayInputStream(licensexml.getBytes());
                com.aspose.words.License license = new com.aspose.words.License();
                license.setLicense(inputStream);
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * OutputStream 转 InputStream
         */
        public static ByteArrayInputStream parse(OutputStream out) {
            ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
            ByteArrayInputStream swapStream = new ByteArrayInputStream(baos.toByteArray());
            return swapStream;
        }
    
        /**
         * InputStream 转 File
         */
        public static File inputStreamToFile(InputStream ins, String name) throws Exception {
            File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
            if (file.exists()) {
                return file;
            }
            OutputStream os = new FileOutputStream(file);
            int bytesRead;
            int len = 8192;
            byte[] buffer = new byte[len];
            while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
            return file;
        }
    
        /**
         * 根据网络地址获取 File 对象
         */
        public static File getFile(String url) throws Exception {
            String suffix = url.substring(url.lastIndexOf("."));
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            return PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + suffix);
        }
    }
    
    
    package com.pcr.embed.util.aspose;
    
    import com.aspose.words.Shape;
    import com.aspose.words.*;
    import lombok.SneakyThrows;
    
    import java.awt.*;
    import java.io.File;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.regex.Pattern;
    
    import static java.util.regex.Pattern.compile;
    
    
    public class AsposeUtil {
    
        /**
         * 加载license 用于破解 不生成水印
         */
        public static void getLicense() {
            try (InputStream is = 			 AsposeUtil.class.getClassLoader().getResourceAsStream("License.xml")) {
                License license = new License();
                license.setLicense(is);
            }
        }
    
    }
    
  3. 将word文档放入resource文档下

  4. ReplaceAndInsertTableImage和ReplaceAndInsertTable类

    package com.pcr.embed.util.aspose;
    
    import com.aspose.words.*;
    
    import java.awt.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    
    public class ReplaceAndInsertTableImage implements IReplacingCallback {
        private String key;
        private String imageUrl;
    
        public ReplaceAndInsertTableImage(String key, String imageUrl) {
            this.key = key;
            this.imageUrl = imageUrl;
        }
    
        @Override
        public int replacing(ReplacingArgs e) throws Exception {
            //获取当前节点
            Node currentNode = e.getMatchNode();
            //节点拆分处理当前匹配字段
            splitRun(currentNode, e.getMatchOffset());
            //获取当前文档
            Document document = (Document) currentNode.getDocument();
            DocumentBuilder builder = new DocumentBuilder(document);
            //将光标移动到指定节点
            builder.moveTo(currentNode);
    
            builder.insertImage(imageUrl, 300, 150);
    
            return ReplaceAction.SKIP;
        }
    
        /**
         * 创建列
         * @param value
         * @param doc
         * @return
         */
        static Cell createCell(String value, Document doc, boolean isBold) throws Exception {
            Cell c1 = new Cell(doc);
            Paragraph p = new Paragraph(doc);
            Run r = new Run(doc,value);
            r.getFont().setName("微软雅黑");
            r.getFont().setBold(isBold);
            p.getParagraphFormat().setLineSpacing(12);
            p.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            p.appendChild(r);
            c1.appendChild(p);
            return c1;
        }
    
        /**
         * 创建行
         * @param columnCount
         * @param columnValues
         * @param doc
         * @return
         */
        static Row createRow(int columnCount,String[] columnValues,Document doc, boolean isBold) throws Exception {
            Row r2 = new Row(doc);
            r2.getRowFormat().setTopPadding(5d);
            r2.getRowFormat().setBottomPadding(5d);
            for (int i = 0; i < columnCount; i++) {
                if (columnValues.length > i) {
                    Cell cell = createCell(columnValues[i], doc, isBold);
                    r2.getCells().add(cell);
                } else {
                    Cell cell = createCell("", doc, isBold);
                    r2.getCells().add(cell);
                }
    
            }
            return r2;
        }
    
        /**
         * 替换参数位置
         * @param currentNode
         * @param position
         */
        private void splitRun(Node currentNode, int position) throws Exception {
            String text = currentNode.getText();
            Node newNode = currentNode.deepClone(true);
            if (text.length() >= position + this.key.length()) {
                ((Run) currentNode).setText(text.substring(position + this.key.length()));
            } else {
                int morlength = position + this.key.length() - text.length();
                ((Run) currentNode).setText("");
                Node tmpnode = currentNode;
                for (int i = 0; i < this.key.length(); i++) {
                    System.out.println(i);
                    tmpnode = tmpnode.getNextSibling();
                    String tmptext = tmpnode.getText();
                    System.out.println(tmptext);
                    System.out.println(morlength);
                    System.out.println("--------" + (tmptext.length() >= morlength));
    
                    if (tmptext.length() >= morlength) {
                        ((Run) tmpnode).setText(tmptext.substring(morlength));
                        break;
                    } else {
                        morlength = morlength - tmptext.length();
                        ((Run) tmpnode).setText("");
                    }
                }
            }
            if (position > 0) {
                ((Run) newNode).setText(text.substring(0, position));
                currentNode.getParentNode().insertBefore(newNode, currentNode);
            }
        }
    }
    
    package com.pcr.embed.util.aspose;
    
    import com.aspose.words.*;
    import com.pcr.embed.vo.TableVo;
    
    import java.awt.*;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    
    public class ReplaceAndInsertTable implements IReplacingCallback {
        private String key;
        private List<TableVo> tableVos;
    
        public ReplaceAndInsertTable(String key, List<TableVo> tableVos) {
            this.key = key;
            this.tableVos = tableVos;
        }
    
        @Override
        public int replacing(ReplacingArgs e) throws Exception {
            //获取当前节点
            Node currentNode = e.getMatchNode();
            //节点拆分处理当前匹配字段
            splitRun(currentNode, e.getMatchOffset());
            //获取当前文档
            Document document = (Document) currentNode.getDocument();
            DocumentBuilder builder = new DocumentBuilder(document);
            //将光标移动到指定节点
            builder.moveTo(currentNode);
    
            Table table = builder.startTable();
            builder.insertCell();
            builder.getCellFormat().setWidth(100);
            builder.getFont().setName("宋体");
            builder.getFont().setColor(Color.decode("#000000"));
            builder.getFont().setSize(10);
            builder.getCellFormat().getBorders().getLeft().setLineStyle(LineStyle.NONE);
            builder.getCellFormat().getBorders().getRight().setLineStyle(LineStyle.NONE);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            builder.getParagraphFormat().setLineSpacing(15);
            builder.write("序号");
            builder.insertCell();
            builder.getCellFormat().setWidth(300);
            builder.getCellFormat().getBorders().getLeft().setLineStyle(LineStyle.NONE);
            builder.getCellFormat().getBorders().getRight().setLineStyle(LineStyle.NONE);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            builder.write("检测指标");
            builder.insertCell();
            builder.getCellFormat().setWidth(100);
            builder.getCellFormat().getBorders().getLeft().setLineStyle(LineStyle.NONE);
            builder.getCellFormat().getBorders().getRight().setLineStyle(LineStyle.NONE);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            builder.write("检测结果");
            builder.insertCell();
            builder.getCellFormat().setWidth(100);
            builder.getCellFormat().getBorders().getLeft().setLineStyle(LineStyle.NONE);
            builder.getCellFormat().getBorders().getRight().setLineStyle(LineStyle.NONE);
            builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            builder.write("检测下限");
            builder.endRow();
            //实验数据
            for (TableVo tableVo : tableVos) {
                if (tableVo.getId().equals(tableVos.size())) {
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getCellFormat().getBorders().getBottom().setLineStyle(LineStyle.SINGLE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getId()+"");
                    builder.insertCell();
                    builder.getCellFormat().setWidth(330);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getCellFormat().getBorders().getBottom().setLineStyle(LineStyle.SINGLE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getTestIndex());
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getCellFormat().getBorders().getBottom().setLineStyle(LineStyle.SINGLE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getTestingResult());
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getCellFormat().getBorders().getBottom().setLineStyle(LineStyle.SINGLE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getDetectionLimit());
                } else {
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getId()+"");
                    builder.insertCell();
                    builder.getCellFormat().setWidth(330);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getTestIndex());
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getTestingResult());
                    builder.insertCell();
                    builder.getCellFormat().setWidth(80);
                    builder.getCellFormat().getBorders().setLineStyle(LineStyle.NONE);
                    builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
                    builder.write(tableVo.getDetectionLimit());
                }
                builder.endRow();
            }
            builder.endTable();
            return ReplaceAction.SKIP;
        }
    
        /**
         * 创建列
         * @param value
         * @param doc
         * @return
         */
        static Cell createCell(String value, Document doc, boolean isBold) throws Exception {
            Cell c1 = new Cell(doc);
            Paragraph p = new Paragraph(doc);
            Run r = new Run(doc,value);
            r.getFont().setName("微软雅黑");
            r.getFont().setBold(isBold);
            p.getParagraphFormat().setLineSpacing(12);
            p.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
            p.appendChild(r);
            c1.appendChild(p);
            return c1;
        }
    
        /**
         * 创建行
         * @param columnCount
         * @param columnValues
         * @param doc
         * @return
         */
        static Row createRow(int columnCount,String[] columnValues,Document doc, boolean isBold) throws Exception {
            Row r2 = new Row(doc);
            r2.getRowFormat().setTopPadding(5d);
            r2.getRowFormat().setBottomPadding(5d);
            for (int i = 0; i < columnCount; i++) {
                if (columnValues.length > i) {
                    Cell cell = createCell(columnValues[i], doc, isBold);
                    r2.getCells().add(cell);
                } else {
                    Cell cell = createCell("", doc, isBold);
                    r2.getCells().add(cell);
                }
    
            }
            return r2;
        }
    
        /**
         * 替换参数位置
         * @param currentNode
         * @param position
         */
        private void splitRun(Node currentNode, int position) throws Exception {
            String text = currentNode.getText();
            Node newNode = currentNode.deepClone(true);
            if (text.length() >= position + this.key.length()) {
                ((Run) currentNode).setText(text.substring(position + this.key.length()));
            } else {
                int morlength = position + this.key.length() - text.length();
                ((Run) currentNode).setText("");
                Node tmpnode = currentNode;
                for (int i = 0; i < this.key.length(); i++) {
                    System.out.println(i);
                    tmpnode = tmpnode.getNextSibling();
                    String tmptext = tmpnode.getText();
                    System.out.println(tmptext);
                    System.out.println(morlength);
                    System.out.println("--------" + (tmptext.length() >= morlength));
    
                    if (tmptext.length() >= morlength) {
                        ((Run) tmpnode).setText(tmptext.substring(morlength));
                        break;
                    } else {
                        morlength = morlength - tmptext.length();
                        ((Run) tmpnode).setText("");
                    }
                }
            }
            if (position > 0) {
                ((Run) newNode).setText(text.substring(0, position));
                currentNode.getParentNode().insertBefore(newNode, currentNode);
            }
        }
    }
    
  5. controller方法

    @GetMapping("/getPcrDataPdf")
        public void getPcrDataPdf(@RequestParam("id") Integer id, HttpServletResponse response) {
            ObjectRestResponse response1 = null;
            try {
                //todo 获取数据 url tableVos
                //替换数据
                ReplaceAndInsertTableImage image = new ReplaceAndInsertTableImage("123456", url);
                ReplaceAndInsertTable table = new ReplaceAndInsertTable("12345", tableVos);
                //生成pdf
                ClassPathResource classPathResource = new ClassPathResource("1.docx");
                InputStream inputStream = classPathResource.getInputStream();
                File file = new File(PdfUtils.word2pdf(inputStream, "/Users/zyn/Desktop/watch/pdf/" + UUID.randomUUID().toString() + ".pdf", image, table, pcrData));
                response.setContentType("application/pdf");
                response.setCharacterEncoding("UTF-8");
                FileInputStream stream = new FileInputStream(file);
                ServletOutputStream outputStream = response.getOutputStream();
                byte[] bytes = new byte[1024];
                int length = 0;
                while ((length = stream.read(bytes)) > 0) {
                    outputStream.write(bytes, 0, length);
                }
                stream.close();
                outputStream.close();
                outputStream.flush();
    
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
上一篇:EBS: Report Builder 的公式程序中不支持over()分组


下一篇:Android那些冷门(邪门)的小知识