PDF操作工具类

本文将详细介绍如何使用各种工具为PDF文档添加和移除水印,包括具体步骤和最佳实践,帮助你更好地管理和定制你的PDF文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /**
     * 根据word文件绝对路径得到pdf文件路径
     *
     * @param fileName
     * @return
     */

    public static String getPdfFileName(String fileName) {
        if (fileName.lastIndexOf(".doc") != -1 || fileName.lastIndexOf(".docx") != -1
                || fileName.lastIndexOf(".ftl") != -1 || fileName.lastIndexOf(".xml") != -1) {
            StringBuffer sb = new StringBuffer();
            int i = fileName.lastIndexOf(File.separator);
            int i1 = fileName.lastIndexOf(".");
            if (i != -1) {
                sb.append(fileName.substring(i + 1, i1));
            } else {
                sb.append(fileName.substring(0, i1));
            }
            sb.append(".pdf");
            return sb.toString();
        } else {
            logger.error("文件格式不支持:" + fileName);
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }

 

 /**
     * word文档转换为pdf文档
     *
     * @param docFilePath word文档路径
     * @param rootPath    webapp的根目录
     * @return 如果转换成功返回pdf文件路径,否则返回null
     */
    public static String wordToPDF(String docFilePath, String rootPath) {
        String pdfFileName = getPdfFileName(docFilePath);
        File docPath=new File(docFilePath);
        if (!docPath.exists()){
            return null;
        }
            String savaAbsolutePath = rootPath + pdfFileName;
            ActiveXComponent app = null;
            Dispatch doc = null;
            File tofile = new File(savaAbsolutePath);
            if (!tofile.getParentFile().exists()) {
                tofile.getParentFile().mkdirs();
            }
            if (!tofile.exists()) {
                try {
                    app = new ActiveXComponent("Word.Application");
                    app.setProperty("Visible", new Variant(false));
                    Dispatch docs = app.getProperty("Documents").toDispatch();
                    doc = Dispatch.call(docs, "Open", docFilePath).toDispatch();

                    Dispatch.call(doc,
                            "SaveAs",
                            savaAbsolutePath,
                            wdFormatPDF);
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Runtime.getRuntime().exec("taskkill /f /im WINWORD.EXE");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    return null;
                } finally {
                    try {
                        Dispatch.call(doc, "Close", false);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    if (app != null) {
                        app.invoke("Quit", new Variant[]{});
                    }
                    //如果没有这句话,winword.exe进程将不会关闭
                    ComThread.Release();
                }
            }
            return savaAbsolutePath;

    }

 

 /**
     * word文档转换为pdf文档
     *
     * @param docFilePath word文档路径
     * @param pdfFilePath pdf文件的地址
     * @param text        水印文字
     * @return 如果转换成功返回pdf文件路径,否则返回null
     */
    public static String wordToPDF(String docFilePath, String pdfFilePath, String text) {
        File docPath = new File(docFilePath);
        if (!docPath.exists()) {
            logger.error("文件不存在:" + docFilePath);
            return null;
        }
        String pdfFileName = getPdfFileName(docFilePath);
        try {
            if (pdfFileName != null) {
                String savaAbsolutePath = pdfFilePath + FileNameUtil.randomFilename() + ".pdf";
                ActiveXComponent app = null;
                Dispatch doc = null;
                File tofile = new File(savaAbsolutePath);
                if (!tofile.getParentFile().exists()) {
                    tofile.getParentFile().mkdirs();
                }
                if (!tofile.exists()) {
                    try {
                        app = new ActiveXComponent("Word.Application");
                        app.setProperty("Visible", new Variant(false));
                        Dispatch docs = app.getProperty("Documents").toDispatch();
                        doc = Dispatch.call(docs, "Open", docFilePath).toDispatch();

                        Dispatch.call(doc,
                                "SaveAs",
                                savaAbsolutePath,
                                wdFormatPDF);
                    } catch (Exception e) {
                        e.printStackTrace();
                        try {
                            Runtime.getRuntime().exec("taskkill /f /im WINWORD.EXE");
                            logger.error("强制关闭了office进程!!!", e);
                            System.err.println("强制关闭了office进程!!!");
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                        logger.error("生成pdf文件出错,可能是文件损坏或输入了不可预测的特殊字符", e);
                        return null;
                    } finally {
                        try {
                            Dispatch.call(doc, "Close", false);
                        } catch (Exception e) {
                            System.err.println("关闭office进程异常!!!");
                            logger.error("关闭office进程异常!!!", e);
                            e.printStackTrace();
                        }
                        if (app != null) {
                            app.invoke("Quit", new Variant[]{});
                        }
                        //如果没有这句话,winword.exe进程将不会关闭
                        ComThread.Release();
                    }
                    if (new File(savaAbsolutePath).exists()) {
                        String pdfPath = savaAbsolutePath.substring(0, savaAbsolutePath.lastIndexOf(".")) + System.currentTimeMillis() + ".pdf";
                        if (StringUtil.isNotBlank(text)) {
                            watermark(savaAbsolutePath, text, pdfPath);
                            File temporaryFiles = new File(savaAbsolutePath);
                            if (temporaryFiles.exists()) {
                                temporaryFiles.delete();
                            }
                            savaAbsolutePath = pdfPath;
                        }
                    }
                }
                int aPublic = savaAbsolutePath.indexOf("public");
                if (aPublic != -1) {
                    pdfFileName = savaAbsolutePath.substring(aPublic);
                } else {
                    pdfFileName = savaAbsolutePath;
                }
            }
            return pdfFileName;
        } catch (Throwable e) {
            logger.error("生成pdf文件出错", e);
            e.printStackTrace();
        } finally {
            ComThread.Release();
            if (pdfFileName == null) {
                try {
                    Runtime.getRuntime().exec("taskkill /f /im WINWORD.EXE");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

 

水印工具类

package com.centnet.chakra.madara.in.utils;


import com.centnet.chakra.core.base.ShiroUser;
import com.centnet.chakra.foundation.model.AreaCache;
import com.centnet.chakra.madara.common.utils.AreaUtil;
import com.centnet.chakra.service.exception.BusinessException;
import com.centnet.chakra.upms.util.ShiroUtil;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.pdf.*;
import com.lowagie.text.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 给文件添加水印
 * @author gc
 */
public class WaterMarkUtil {

    private final static Logger logger = LoggerFactory.getLogger(WaterMarkUtil.class);


    /**
     * 将一个文件字节数组保存到 目标文件中  ,并给目标文件添加水印-》 水印文件
     * @param bytes  源文件数组
     * @param sourceFilePath  源文件保存的路径
     * @param sourceFileName  源文件名
     * @param text  水印文字
     * @param waterFilePath  水印文件保存的路径
     * @param waterFileName  水印文件名
     * @return
     */
    public static void addWatermark(byte[] bytes, String sourceFilePath, String sourceFileName, String text,String waterFilePath ,String waterFileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        //保存到临时文件夹下
        try {
            File dir = new File(sourceFilePath);
            boolean isDir = dir.isDirectory();
            // 目录不存在则先建目录
            if (!isDir) {
                try {
                    dir.mkdirs();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            file = new File(sourceFilePath + File.separator + sourceFileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        try {
            //添加水印
            addWaterMark(sourceFilePath + File.separator + sourceFileName,waterFilePath + File.separator + waterFileName,text,0,0);
        }catch (Exception e){
            logger.error("添加水印失败");
            e.printStackTrace();
            throw  new BusinessException("添加水印失败");

        }
    }

    /**
     *
     * 【功能描述:添加图片和文字水印】 【功能详细描述:功能详细描述】
     * @param srcFile 待加水印文件       (全路径 : c:/XXXX/***.pdf)
     * @param destFile 加水印后存放地址  (全路径 : c:/XXXX/***.pdf)
     * @param text 加水印的文本内容
     * @param textWidth 文字横坐标
     * @param textHeight 文字纵坐标
     * @throws Exception
     */
    public static void addWaterMark(String srcFile, String destFile, String text, int textWidth, int textHeight) throws Exception
    {
        // 待加水印的文件
        PdfReader reader = new PdfReader(srcFile);
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(destFile));
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        // 设置字体
        BaseFont basefont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);


        //设置透明度
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(1f);
        gs.setStrokeOpacity(1f);
        // 循环对每页插入水印
        for (int i = 1; i < total; i++)
        {
            // 水印的起始
            content = stamper.getUnderContent(i);
            // 开始
            content.beginText();
            // 设置颜色 默认为蓝色
            content.setColorFill(BaseColor.GRAY);
            // 设置字体及字号
            content.setFontAndSize(basefont, 8);
            // 设置起始位置  从下往上  从左往右
            File file = new File(srcFile);
            content.setTextMatrix(textWidth, textHeight);
            // 开始写入水印
            //高
            for (int j = 0; j <6 ; j++) {
                //宽
                for (int k = 0; k < 6 ; k++) {
                    content.showTextAligned(Element.ALIGN_LEFT, text, textWidth+100*k, textHeight+200*j, 45);
                }
            }
            content.endText();
        }
        stamper.close();
    }




}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值