java 实现Word或Excel 转Pdf

1:首先需要引入相关的jar

 word转pdf需要引入 aspose-words-15.8.0-jdk16.jar

下载JAR包  Word 
http://note.youdao.com/noteshare?id=1e73ab1c91abad338271d50a881165c2

 excel转pdf需要引入aspose-cells-8.5.2.jar Excel 
http://note.youdao.com/noteshare?id=f75d87445106ea6ca6b54cfa58bc4fb2

说明:此处jar包也可以自己下载其他版本,但是其他版本 license.xml 可能不生效

maven 仓库可以查找 jar : https://mvnrepository.com/search?q=aspose-words

通过 <dependency> 引入是引入不到的,建议下载下来,上传至自己的 maven 私服,或者 放到项目中。

放到自己项目中可能遇到的坑:引入外部jar,项目启动 Class not found

2:引入license.xml文件(备注:此License文件只能破解Word版本)

<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>

3. 代码实现

import java.awt.*;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;



import com.aspose.cells.Workbook;

import com.aspose.words.*;

import com.aspose.words.Shape;



/**

 * Word或Excel 转Pdf 帮助类

 *

 * 备注:需要引入 aspose-words-15.8.0-jdk16.jar / aspose-cells-8.5.2.jar

 */

public class PdfUtil {



    private static boolean getLicense() {

        boolean result = false;

        try {

            InputStream is = PdfUtil.class.getClassLoader().getResourceAsStream("license.xml");

            License aposeLic = new License();

            aposeLic.setLicense(is);

            result = true;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return result;

    }



    /**

     * @param wordPath 需要被转换的word全路径带文件名

     * @param pdfPath  转换之后pdf的全路径带文件名

     */

    public static void doc2pdf(String wordPath, String pdfPath) {

        // 验证License 若不验证则转化出的pdf文档会有水印产生

        if (!getLicense()) {

            return;

        }

        FileOutputStream os = null;

        try {

            long old = System.currentTimeMillis();

            //新建一个pdf文档

            File file = new File(pdfPath);

            os = new FileOutputStream(file);

            //wordPath 是将要被转化的word文档

            Document doc = new Document(wordPath);



            insertWatermarkText(doc, "小灰灰");

            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换

            doc.save(os, com.aspose.words.SaveFormat.PDF);

            long now = System.currentTimeMillis();

            //转化用时

            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (os != null) {

                try {

                    os.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }



    /**

     * @param excelPath 需要被转换的excel全路径带文件名

     * @param pdfPath   转换之后pdf的全路径带文件名

     */

    public static void excel2pdf(String excelPath, String pdfPath) {

        // 验证License 若不验证则转化出的pdf文档会有水印产生

        if (!getLicense()) {

            return;

        }

        FileOutputStream fileOS = null;

        try {

            long old = System.currentTimeMillis();

            // 原始excel路径

            Workbook wb = new Workbook(excelPath);

            fileOS = new FileOutputStream(new File(pdfPath));

            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);

            fileOS.close();

            long now = System.currentTimeMillis();

            //转化用时

            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (fileOS != null) {

                try {

                    fileOS.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }



    /**

     * 添加水印

     * @param doc

     * @param watermarkText

     * @throws Exception

     */

    private static void insertWatermarkText(Document doc, String watermarkText) throws Exception

    {

        Shape watermark = new Shape(doc, ShapeType.TEXT_PLAIN_TEXT);

        //水印内容

        watermark.getTextPath().setText(watermarkText);

        //水印字体

        watermark.getTextPath().setFontFamily("宋体");

        //水印宽度

        watermark.setWidth(500);

        //水印高度

        watermark.setHeight(100);

        //旋转水印

        watermark.setRotation(-40);

        //水印颜色

        watermark.getFill().setColor(Color.lightGray);

        watermark.setStrokeColor(Color.lightGray);

        watermark.setRelativeHorizontalPosition(RelativeHorizontalPosition.PAGE);

        watermark.setRelativeVerticalPosition(RelativeVerticalPosition.PAGE);

        watermark.setWrapType(WrapType.NONE);

        watermark.setVerticalAlignment(VerticalAlignment.CENTER);

        watermark.setHorizontalAlignment(HorizontalAlignment.CENTER);

        Paragraph watermarkPara = new Paragraph(doc);

        watermarkPara.appendChild(watermark);

        for (Section sect : doc.getSections())

        {

            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_PRIMARY);

            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_FIRST);

            insertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HEADER_EVEN);

        }

        System.out.println("Watermark Set");

    }

    private static void insertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, int headerType) throws Exception {

        HeaderFooter header = sect.getHeadersFooters().getByHeaderFooterType(headerType);

        if (header == null)

        {

            header = new HeaderFooter(sect.getDocument(), headerType);

            sect.getHeadersFooters().add(header);

        }

        header.appendChild(watermarkPara.deepClone(true));

    }



    public static void main(String[] args) {



        //word 和excel 转为pdf

        String filePaths = "E:/filetest/zgssjmsfzm.doc";

        String fileName = "zgssjmsfzm";

        String pdfPath = "E:/filetest/" + fileName + ".pdf";

        doc2pdf(filePaths, pdfPath);//filePaths需要转换的文件位置 pdfPath为存储位置

        String excel2pdf = "E:/filetest/资产清包.xlsx";

        String excelPdfPath = "E:/filetest/资产清包.pdf";

        excel2pdf(excel2pdf, excelPdfPath);

    }

}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Apache POI和iText库来实现Java中的WordPDF功能。 Apache POI提供了访问和操作Microsoft Office格式文件(如WordExcel和PowerPoint)的Java API,包括读取、写入和换文件。通过使用Apache POI的XWPF组件,我们可以读取Word文档并将其换为PDF。 iText是一个流行的开源Java库,提供了创建和操作PDF文件的功能。我们可以使用iText将Apache POI生成的Word文档换为PDF格式。 以下是一个简单的Java代码示例,演示如何使用Apache POI和iText将Word文档换为PDF: ```java import java.io.*; import org.apache.poi.xwpf.usermodel.*; import com.itextpdf.text.*; import com.itextpdf.text.pdf.*; public class WordToPdfConverter { public static void convert(String inputPath, String outputPath) { try { // 读取Word文档 InputStream input = new FileInputStream(new File(inputPath)); XWPFDocument document = new XWPFDocument(input); // 创建PDF文档 OutputStream output = new FileOutputStream(new File(outputPath)); Document pdfDoc = new Document(); PdfWriter.getInstance(pdfDoc, output); // 打开PDF文档 pdfDoc.open(); // 读取Word文档中的段落并将其添加到PDF文档中 for (XWPFParagraph paragraph : document.getParagraphs()) { pdfDoc.add(new Paragraph(paragraph.getText())); } // 关闭PDF文档和输入输出流 pdfDoc.close(); input.close(); output.close(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { String inputPath = "example.docx"; String outputPath = "example.pdf"; convert(inputPath, outputPath); } } ``` 在上面的代码示例中,我们首先读取输入Word文档,然后创建一个PDF文档并打开它。接下来,我们遍历Word文档中的每个段落,并将其添加到PDF文档中。最后,我们关闭PDF文档和输入输出流。 请注意,此代码示例仅适用于简单的Word文档,不支持复杂的格式和内容,例如表格、图像和链接。对于更复杂的Word文档,您可能需要使用更高级的库或服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值