Aspose pdf文件操作工具类

实现功能:Excel转pdf,Word转pdf,多个pdf文件合并,给pdf文件添加文字水印,给pdf添加图片水印

import com.aspose.cells.Workbook;
import com.aspose.words.Document;
import com.lowagie.text.Image;
import com.lowagie.text.pdf.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FilesToPdf {

    /**
     * 项目发布的跟路径,区分Windows平台、Linux平台
     * @return 项目的跟路径
     */
    public static String getProRootPath() {
        String rootPath = FilesToPdf.class.getResource("/").getPath();
        // windows平台
        if (rootPath.startsWith("/") && rootPath.indexOf(":") == 2) {
            rootPath = rootPath.substring(1);
        }
        return rootPath.substring(0, rootPath.indexOf("WEB-INF"));
    }

    /**
     * 获取license
     * (去除aspose的水印)
     * @return
     */
    public static boolean getLicense() {
        boolean result = false;
        try {
            InputStream is = new FileInputStream(getProRootPath() + "WEB-INF/classes/template/license/license_doc.xml");
            // 因为word和excel的License使用的是不同包下的同名类,所以加上了包名
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);

            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取license Excel
     *
     * @return
     */
    public static boolean getLicenseCells() {
        boolean result = false;
        try {
            InputStream is = new FileInputStream(getProRootPath() + "WEB-INF/classes/template/license/license_cells.xml");
            // 因为word和excel的License使用的是不同包下的同名类,所以加上了包名
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);

            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF等类型
     * @param docxFilePath
     * @param pdfFilePath
     */
    public static void convertPdfByAspose(String docxFilePath, String pdfFilePath) {
        if (!getLicense()) {
            return;
        }
        try {
            // 全面支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            Document doc = new Document(docxFilePath);
            doc.save(pdfFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Excel文件转换
     * @param inputPath 需要被转换的excel全路径带文件名
     * @param outPath 转换之后pdf的全路径带文件名
     * @Return void
     */
    public static void excelToPdf(String inputPath, String outPath) {
        if (!getLicenseCells()) {
            return;
        }
        try {
            //Excel文件数据
            Workbook wb = new Workbook(inputPath);
            FileOutputStream fileOS = new FileOutputStream(new File(outPath));
            //保存为pdf文件,saveFormat取的是cells包下的,值为:13
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * pdf 文件合并
     * @param files 要合并的文件名(带路径)的数组
     * @param newfile 合并完成的pdf文件名(带路径)
     * @return
     */
    public static String mergePdfFiles(String[] files, String newfile) {
        com.lowagie.text.Document document = null;
        try {
            document = new com.lowagie.text.Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return newfile;
    }

    /**
     * 给pdf文件添加图片水印
     * @param InPdfFile   要加水印的原pdf文件路径
     * @param outPdfFile  加了水印后要输出的路径
     * @param markImagePath  水印图片路径
     * @throws Exception
     */
    public static void addPdfImgMark(String InPdfFile, String outPdfFile, String markImagePath) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;

        PdfGState gs1 = new PdfGState();
        gs1.setFillOpacity(0.07f);// 透明度设置

        Image img = Image.getInstance(markImagePath);// 插入图片水印

        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数
        for (int i = 1; i <= pageSize; i++) {
            img.setAbsolutePosition(50, 150); // 坐标
            // img.setRotation(-20);// 旋转 弧度
            img.setRotationDegrees(45);// 旋转 角度
            // img.scaleAbsolute(200,100);//自定义大小

            img.scalePercent(70,65);

            under = stamp.getUnderContent(i);// 水印在之前文本下
            // under = stamp.getOverContent(i);//水印在之前文本上
            under.setGState(gs1);// 图片水印 透明度
            under.addImage(img);// 图片水印
            
            
            // 页脚
            // ColumnText.showTextAligned(under, Element.ALIGN_LEFT, new Phrase("页脚文字"),
            //       10, 20, 0);
        }
        stamp.close();// 关闭
        reader.close();
    }
    
    /**
     * Description: 给pdf文件添加文字水印 <br>
     * @param InPdfFile
     *            要加水印的原pdf文件路径
     * @param outPdfFile
     *            加了水印后要输出的路径
     * @param textMark
     *            水印文字
     * @param textWidth
     *            文字横坐标
     * @param textHeight
     *            文字纵坐标
     * @throws Exception
     * @see void
     */
    public static void addPdfTextMark(String InPdfFile, String outPdfFile, String textMark, int textWidth, int textHeight) throws Exception {
        PdfReader reader = new PdfReader(InPdfFile, "PDF".getBytes());
        PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(new File(outPdfFile)));

        PdfContentByte under;

        BaseFont font = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", "Identity-H", true);// 使用系统字体

        int pageSize = reader.getNumberOfPages();// 原pdf文件的总页数

        for (int i = 1; i <= pageSize; i++) {
            under = stamp.getUnderContent(i);// 水印在之前文本下
            // under = stamp.getOverContent(i);//水印在之前文本上
            under.beginText();
            under.setColorFill(BaseColor.GRAY);// 文字水印 颜色
            under.setFontAndSize(font, 38);// 文字水印 字体及字号
            under.setTextMatrix(textWidth, textHeight);// 文字水印 起始位置
            under.showTextAligned(Element.ALIGN_CENTER, textMark, textWidth, textHeight, 45);
            under.endText();
        }

        stamp.close();// 关闭
    }
}


版权声明:本文为qq_35096670原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。