documents4j-word excel ..转pdf格式

 官网地址:documents4j - Java 的文档格式转换器

本文中使用的是本地转换器

草率的看了一眼文档,说明使用本地转换器需要在本机有ms work、ms excel (此处部署在linux时需要安装)。

本文使用的documents4j依赖(若有其他格式的文件需要转换则需要引入其他转换器)

        
        <dependency>
			<groupId>com.documents4j</groupId>
			<artifactId>documents4j-local</artifactId>
			<version>1.1.1</version>
		</dependency>
		
        <!--word-->
        <dependency>
			<groupId>com.documents4j</groupId>
			<artifactId>documents4j-transformer-msoffice-word</artifactId>
			<version>1.1.1</version>
		</dependency>
        <!--excel-->
		<dependency>
			<groupId>com.documents4j</groupId>
			<artifactId>documents4j-transformer-msoffice-excel</artifactId>
			<version>1.1.1</version>
		</dependency>

工具类中还有jpg、png转换pdf以及纯文本格式的文件使用的是 itextpdf(有需要也可以看一下这部分)

<dependency>
   <groupId>fr.opensagres.xdocreport</groupId>
   <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
   <version>1.0.6</version>
</dependency>
<dependency>
   <groupId>com.itextpdf.tool</groupId>
   <artifactId>xmlworker</artifactId>
   <version>5.5.11</version>
</dependency>


import java.io.*;
import com.aams.base.AamsOperatingException;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;

import com.itextpdf.text.*;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileTransformUtil {
    private Logger log = LoggerFactory.getLogger(FileTransformUtil.class);

    public InputStream getPdfStream(String fileEnd, String fileName, InputStream fileInput) throws Exception {
        // 输出的PDF流
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        //纯文本和图片的采用的是itextpdf的方式  有兴趣的也可以使用documents4j完成一下(这里因为写的比较早所以就没改本人也懒的换了)
        if ("xml".equalsIgnoreCase(fileEnd) || "html".equalsIgnoreCase(fileEnd) || "txt".equalsIgnoreCase(fileEnd)) {

            // 创建PDF文档对象 页大小为A4
            Document document = new Document(PageSize.A4, 20, 20, 20, 20);
            // 创建PDF写入器
            PdfWriter.getInstance(document, output);
            // 打开文档对象
            document.open();
            //读取xml中的内容
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fileInput.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);//将读到的字节写入输出流
            }
            fileInput.close();
            String content=outputStream.toString();
            outputStream.close();
            this.createPdfContent(document,content);
            document.close();
            output.close();
            return new ByteArrayInputStream(output.toByteArray());
        }
        else if ("jpg".equalsIgnoreCase(fileEnd) || "png".equalsIgnoreCase(fileEnd)) {
            // 创建PDF文档对象 页大小为A4
            Document document = new Document(PageSize.A4, 20, 20, 20, 20);
            // 创建PDF写入器
            PdfWriter.getInstance(document, output);
            // 打开文档对象
            document.open();

            //添加图片
            this.createStreamPic(document,fileInput);

            document.close();
            fileInput.close();
            output.close();
            return new ByteArrayInputStream(output.toByteArray());
        }

        else if ("docx".equalsIgnoreCase(fileEnd) || "doc".equalsIgnoreCase(fileEnd) || "xlsx".equalsIgnoreCase(fileEnd) || "xls".equalsIgnoreCase(fileEnd)) {
            try  {
                //本地转换器转换文件
                IConverter converter = LocalConverter.builder().build();

                if(fileEnd.equals("doc")){
                    //指定要转格式的文件
                    converter.convert(fileInput)
                            //当前文件的格式
                            .as(DocumentType.DOC)
                            //输出--这里直接输出到流中 (如果是直接写在本地的可以直接 FileOutPutStream(new File("位置")))
                            .to(output)
                            //输出的格式
                            .as(DocumentType.PDF).execute();

                }
                else if(fileEnd.equals("docx")){
                    converter.convert(fileInput)
                            .as(DocumentType.DOCX)
                            .to(output)
                            .as(DocumentType.PDF).execute();
                }
                else if(fileEnd.equals("xlsx")){
                    converter.convert(fileInput)
                            .as(DocumentType.XLSX)
                            .to(output)
                            .as(DocumentType.PDF).execute();
                }
                else if(fileEnd.equals("xls")){
                    converter.convert(fileInput)
                            .as(DocumentType.XLS)
                            .to(output)
                            .as(DocumentType.PDF).execute();
                }
                output.close();
                fileInput.close();
                return new ByteArrayInputStream(output.toByteArray());
            } catch (Exception e) {
                log.error("[documents4J] word转pdf失败:{}", e.toString());
            }finally {
                if(output != null){
                    output.close();
                }
            }

        }
        return null;
    }



   
    private  void createPdfContent(Document document,String text) throws AamsOperatingException {
        try {
            Paragraph paragraph1 = new Paragraph();
            Chunk timeChunk = new Chunk(text);

            paragraph1.add(timeChunk);
            document.add(paragraph1);
        } catch (Exception e) {
            throw new AamsOperatingException(e.getMessage());
        }
    }



    private void createStreamPic(Document document, InputStream inputStream) throws AamsOperatingException {
        this.createStreamPic(document, inputStream, 0, 0);
    }

    /**
     * @param height      高
     * @param width       宽
     * @param inputStream 图片流
     *                    pdf中添加图片
     **/
    private void createStreamPic(Document document, InputStream inputStream, float height, float width) throws AamsOperatingException {

        try {
            int n;
            byte[] buffer = new byte[4096];
            ByteArrayOutputStream imgOutPut = new ByteArrayOutputStream();
            while (-1 != (n = inputStream.read(buffer))) {
                imgOutPut.write(buffer, 0, n);
            }
            Image image = Image.getInstance(imgOutPut.toByteArray());
            height = height != 0 ? height : image.getHeight();
            width = width != 0 ? width : image.getWidth();
            int percent = getPercent(height, width);
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(percent);
            document.add(image);
        }catch (Exception e){
            throw new AamsOperatingException(e.getMessage());
        }
    }


    private void createUrlPic(Document document, String path) throws AamsOperatingException {
        this.createUrlPic(document, path, 0, 0);
    }

    /**
     *@param height      高
     *@param width       宽
     *@param path        图片地址
     *             pdf中添加图片
     **/
    private void createUrlPic(Document document, String path, float height, float width) throws AamsOperatingException {
        try {
            Image image = Image.getInstance(path);
            height = height != 0 ? height : image.getHeight();
            width = width != 0 ? width : image.getWidth();
            int percent = getPercent(height, width);
            image.setAlignment(Image.MIDDLE);
            image.scalePercent(percent);
            document.add(image);
        } catch (Exception e) {
            throw new AamsOperatingException(e.getMessage());
        }
    }


    //图片比例设置
    private static int getPercent(float height, float weight) {
        float percent = 0.0F;
        if (height > weight) {
            percent = PageSize.A4.getHeight() / height * 100;
        } else {
            percent = PageSize.A4.getWidth() / weight * 100;
        }
        return Math.round(percent);
    }

    /**
     * main方法中截是测试使用
     * */

    //    public static void main(String[] args){
//        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        // 创建PDF文档对象 页大小为A4
//        Document document = new Document(PageSize.A4, 20, 20, 20, 20);
        System.err.println("123");
//        try {
//
//            // 创建PDF写入器
//            PdfWriter.getInstance(document, output);
//            // 打开文档对象
//            document.open();
//
//            InputStream is =  new FileInputStream(new File("D:\\123.xml"));
//            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//输出流
//            byte[] bytes = new byte[1024];
//            int len;
//            while ((len = is.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);//将读到的字节写入输出流
//            }
//            is.close();
//            String content=outputStream.toString();
//            outputStream.close();
//
//
//
//
//            Paragraph paragraph1 = new Paragraph();
//            Chunk timeChunk = new Chunk(content);
//
//            paragraph1.add(timeChunk);
//            document.add(paragraph1);
//            document.close();
//            output.close();
//            FileOutputStream fileOutputStream = new FileOutputStream("D:\\123.pdf");
//            fileOutputStream.write(output.toByteArray());
//        }catch (Exception e){
//            System.err.println(e);
//        }
//    }
//public static void main(String[] args) throws FileNotFoundException {
//    String fileEnd = "xlsx";
//    try  {
        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\333.pdf"));
//        ByteArrayOutputStream output = new ByteArrayOutputStream();
//        InputStream fileInput = new FileInputStream(new File("D:\\qqqq.xlsx"));
//
//        IConverter converter = LocalConverter.builder().build();
//
//        if(fileEnd.equals("doc")){
//            converter.convert(fileInput)
//                    .as(DocumentType.DOC)
//                    .to(output)
//                    .as(DocumentType.PDF).execute();
//
//        } else if(fileEnd.equals("docx")){
//            converter.convert(fileInput)
//                    .as(DocumentType.DOCX)
//                    .to(output)
//                    .as(DocumentType.PDF).execute();
//        }
//        else if(fileEnd.equals("xlsx")){
//            converter.convert(fileInput)
//                    .as(DocumentType.XLSX)
//                    .to(output)
//                    .as(DocumentType.PDF).execute();
//        }
//        else if(fileEnd.equals("xls")){
//            converter.convert(fileInput)
//                    .as(DocumentType.XLS)
//                    .to(output)
//                    .as(DocumentType.PDF).execute();
//        }
//        output.close();
//        fileInput.close();
//        FileOutputStream fileOutputStream = new FileOutputStream(new File("D:\\daqyqqqq.pdf"));
//        fileOutputStream.write(output.toByteArray());
//        fileOutputStream.close();
//    } catch (Exception e) {
//            System.err.println(e);
//    }finally {
//    }
//
//}

}

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Documents4j 是一个开源的 Java 库,用于将各种文档格式(如 WordExcel、PowerPoint 等)换为 PDF 格式。在 Linux 上使用 Documents4j 进行 Word PDF 换,需要先安装 LibreOffice,因为 Documents4j 依赖于 LibreOffice。 以下是在 Linux 上使用 Documents4j 进行 Word PDF 的步骤: 1. 安装 LibreOffice。在 Ubuntu 上可以使用以下命令进行安装: ``` sudo apt-get update sudo apt-get install libreoffice ``` 2. 在 Maven 项目中添加 Documents4j 依赖: ``` <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-api</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-util-conversion</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-transformer</artifactId> <version>1.0.3</version> </dependency> <dependency> <groupId>com.documents4j</groupId> <artifactId>documents4j-util-all</artifactId> <version>1.0.3</version> </dependency> ``` 3. 编写 Java 代码: ``` File inputFile = new File("input.docx"); File outputFile = new File("output.pdf"); try (InputStream inputStream = new FileInputStream(inputFile); OutputStream outputStream = new FileOutputStream(outputFile)) { IConverter converter = LocalConverter.builder() .baseFolder(new File(".")) .workerPool(20, 25, 2, TimeUnit.SECONDS) .processTimeout(5, TimeUnit.SECONDS) .build(); converter.convert(inputStream).as(DocumentType.DOCX) .to(outputStream).as(DocumentType.PDF) .execute(); converter.shutDown(); } catch (IOException e) { e.printStackTrace(); } ``` 以上代码将 input.docx 文件换为 output.pdf 文件。LocalConverter 是 Documents4j 的主要入口点,它负责管理换过程。以上代码中的 workerPool 方法指定了换器的线程池大小,processTimeout 方法指定了换器的超时时间。 4. 运行 Java 代码即可完成 Word PDF 换。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GreetWinter

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值