JAVA用WORD模板导出PDF文件

								JAVA用WORD模板导出PDF文件

//第一步、创建WORD文档模板

在这里插入图片描述

第二步、直接上源码

try {
            String fileName = inPramDTO.getInpatNum()  + "-" + new String((new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                    .getBytes(), StandardCharsets.UTF_8);
            response.reset();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition","attachment;filename=" + fileName + ".pdf");
            response.setContentType("application/force-download");
            ClassPathResource classPathResource = new ClassPathResource("/XXX.docx");
            String pathName = pafPath + fileName;
            MyXWPFDocument document = new MyXWPFDocument(classPathResource.getStream());
            HashMap<String, Object> contentMap = new HashMap<>();
            //填充WORD模板文档内容
            contentMap.put("XXX",XXX);
            WordExportUtil.exportWord07(document, contentMap);
            FileOutputStream wordOutputStream = new FileOutputStream( pathName+ ".docx");
            document.write(wordOutputStream);
            document.close();
            wordOutputStream.close();
            //WORD转PDF
            InputStream licenseInput = getClass().getClassLoader().getResourceAsStream("license.xml");
            License license = new License();
            license.setLicense(licenseInput);
            licenseInput.close();
            FileInputStream wordInputStream = new FileInputStream(pathName + ".docx");
            FileOutputStream pdfOutputStream = new FileOutputStream(pathName + ".pdf");
            Document wordDoc = new Document(pathName + ".docx");
            wordDoc.save(pdfOutputStream, SaveFormat.PDF);
            wordInputStream.close();
            pdfOutputStream.close();
              //添加自定义水印
            PdfUtil.addWaterMark(pathName + ".pdf", pathName + "final.pdf", "水印文字");
            //返回前端BASE64
            String pdfBase64 = Base64.encode(new File(pathName + "final.pdf"));
        }catch (Exception e){
        log.error("导出PDF失败:",e);
        }finally {
        //最后删除文件,以免浪费资源
            String fileName = inPramDTO.getInpatNum()  + "-" + new String((new SimpleDateFormat("yyyy-MM-dd").format(new Date()))
                    .getBytes(), StandardCharsets.UTF_8);
            String pathName = pafPath + fileName;
            boolean workFlag = new File(pathName + ".docx").delete();
            boolean pdfFlag = new File(pathName + ".pdf").delete();
            boolean finalPdfFlag = new File(pathName + "final.pdf").delete();
        }

第三步、PDF添加水印工具类:
    /**
     * pdf添加水印
     *
     * @param inputFile     需要添加水印的文件
     * @param outputFile    添加完水印的文件存放路径
     * @param waterMarkName 需要添加的水印文字
     * @return
     */
    public static boolean addWaterMark(String inputFile, String outputFile, String waterMarkName) {
        File file = new File(inputFile);
        if (!file.exists()) {
            return false;
        }

        PdfReader reader = null;
        PdfStamper stamper = null;
        try {
            reader = new PdfReader(inputFile);
            stamper = new PdfStamper(reader, Files.newOutputStream(Paths.get(outputFile)));
            BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
            Rectangle pageRect = null;
            PdfGState gs = new PdfGState();
            //这里是透明度设置
            gs.setFillOpacity(opacity);
            //这里是条纹不透明度
            gs.setStrokeOpacity(0.2f);
            int total = reader.getNumberOfPages() + 1;
            System.out.println("Pdf页数:" + reader.getNumberOfPages());
            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(waterMarkName);
            metrics = label.getFontMetrics(label.getFont());
            //字符串的高,   只和字体有关
            textH = metrics.getHeight();
            //字符串的宽
            textW = metrics.stringWidth(label.getText());
            PdfContentByte under;
            //循环PDF,每页添加水印
            for (int i = 1; i < total; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                //在内容上方添加水印
                under = stamper.getOverContent(i);
                under.saveState();
                under.setGState(gs);
                under.beginText();
                //这里是水印字体大小
                under.setFontAndSize(base, fontsize);
                for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
                    for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
                        // rotation:倾斜角度
                        under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
                    }
                }
                //添加水印文字
                under.endText();
            }
            System.out.println("添加水印成功!");
            return true;
        } catch (IOException e) {
            System.out.println("添加水印失败!错误信息为: " + e);
            return false;
        } catch (DocumentException e) {
            System.out.println("添加水印失败!错误信息为: " + e);
            return false;
        } finally {
            //关闭流
            if (stamper != null) {
                try {
                    stamper.close();
                } catch (DocumentException e) {
                    System.out.println("文件流关闭失败");
                } catch (IOException e) {
                    System.out.println("文件流关闭失败");
                }
            }
            if (reader != null) {
                reader.close();
            }
        }
    }
    
第四步、创建LICENCE.XML文件 因为使用的是aspose 需要购买,这里仅供学习使用,请勿商用!

<License>
    <Data>
        <Products>
            <Product>Aspose.Total for Java</Product>
            <Product>Aspose.Words for Java</Product>
        </Products>
        <EditionType>Enterprise</EditionType>
        <SubscriptionExpiry>20991231</SubscriptionExpiry>
        <LicenseExpiry>20991231</LicenseExpiry>
        <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
    </Data>
    <Signature>
        sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=
    </Signature>
</License>

最后说明:这里用的是aspose-words-15.8.0-jdk16.jar 请勿商用


    
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值