有关文件转pdf的代码示例

简介: 有关文件转pdf的代码示例
工作中 经常会遇到文件在线预览的问题,如果仅仅是预览的话,可以通过技术手段,将文件统一转化为pdf,然后使用浏览器针对pdf的预览功能即可。

开始看代码

1 、引入坐标依赖
<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>fr.opensagres.xdocreport</groupId>
    <artifactId>org.apache.poi.xwpf.converter.pdf</artifactId>
    <version>2.0.2</version>
</dependency>
2 、代码实现
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.tools.PDFToImage;
import org.apache.pdfbox.tools.imageio.ImageIOUtil;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PDFConverter;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class FileToPdfConverter {
    public static void main(String[] args) {
        try {
            // 读入需要转换的文件
            File inputFile = new File("input.doc");
            FileInputStream inStream = new FileInputStream(inputFile);
            // 创建pdf输出文件
            File outputFile = new File("output.pdf");
            FileOutputStream outStream = new FileOutputStream(outputFile);
            // 创建pdf文档
            PDDocument document = new PDDocument();
            // 根据文件类型选择转换方法
            if (inputFile.getName().endsWith(".doc")) {
                // 将doc文件转换为pdf文件
                HWPFDocument doc = new HWPFDocument(inStream);
                Range range = doc.getRange();
                PdfConverter.getInstance().convert(range, document);
            } else if (inputFile.getName().endsWith(".docx")) {
                // 将docx文件转换为pdf文件
                XWPFDocument doc = new XWPFDocument(inStream);
                PdfOptions options = PdfOptions.create();
                PdfConverter.getInstance().convert(doc, document, options);
            } else if (inputFile.getName().endsWith(".txt")) {
                // 将txt文件转换为pdf文件
                PDPage page = new PDPage(PDRectangle.A4);
                document.addPage(page);
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                FileInputStream inputStream = new FileInputStream(inputFile);
                int data = inputStream.read();
                while(data != -1) {
                    contentStream.beginText();
                    contentStream.showText(String.valueOf((char)data));
                    contentStream.endText();
                    contentStream.newLineAtOffset(0, -12);
                    data = inputStream.read();
                }
                inputStream.close();
                contentStream.close();
            } else if (inputFile.getName().endsWith(".jpg") || inputFile.getName().endsWith(".jpeg") || inputFile.getName().endsWith(".png")) {
                // 将图片文件转换为pdf文件
                PDPage page = new PDPage();
                document.addPage(page);
                PDFRenderer renderer = new PDFRenderer(document);
                PDFToImage pdfToImage = new PDFToImage();
                pdfToImage.setImageType("png");
                pdfToImage.setOutputPrefix("tmp");
                pdfToImage.setPdfFile(inputFile.getAbsolutePath());
                pdfToImage.startConversion(renderer, 1, 1);
                File tmpFile = new File("tmp-1.png");
                ImageIOUtil.writeImage(renderer.renderImage(0), "tmp-1.png", 300);
                PDPageContentStream contentStream = new PDPageContentStream(document, page);
                contentStream.drawImage(PDImageXObject.createFromFile(tmpFile.getAbsolutePath(), document), 0, 0, PDRectangle.A4.getWidth(), PDRectangle.A4.getHeight());
                contentStream.close();
                tmpFile.delete();
            } else {
                System.out.println("不支持的文件类型");
                return;
            }
            // 保存pdf文件并关闭输入输出流
            document.save(outStream);
            document.close();
            inStream.close();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
相关文章
|
8月前
|
存储 JSON API
如何将 Swagger 文档导出为 PDF 文件
你会发现自己可能需要将 Swagger 文档导出为 PDF 或文件,以便于共享和存档。在这篇博文中,我们将指导你完成将 Swagger 文档导出为 PDF 格式的过程。
|
5月前
|
C#
【PDF提取内容改名】批量提取PDF指定区域内容重命名PDF文件,PDF自动提取内容命名的方案和详细步骤
本工具可批量提取PDF中的合同编号、日期、发票号等关键信息,支持PDF自定义区域提取并自动重命名文件,适用于合同管理、发票处理、文档归档和数据录入场景。基于iTextSharp库实现,提供完整代码示例与百度、腾讯网盘下载链接,助力高效处理PDF文档。
707 40
|
5月前
|
编译器 Python
如何利用Python批量重命名PDF文件
本文介绍了如何使用Python提取PDF内容并用于文件重命名。通过安装Python环境、PyCharm编译器及Jupyter Notebook,结合tabula库实现PDF数据读取与处理,并提供代码示例与参考文献。
|
7月前
|
人工智能 算法 安全
使用CodeBuddy实现批量转换PPT、Excel、Word为PDF文件工具
通过 CodeBuddy 实现本地批量转换工具,让复杂的文档处理需求转化为 “需求描述→代码生成→一键运行” 的极简流程,真正实现 “技术为效率服务” 的目标。感兴趣的快来体验下把
339 10
|
6月前
|
数据采集 存储 API
Python爬虫结合API接口批量获取PDF文件
Python爬虫结合API接口批量获取PDF文件
|
8月前
|
程序员 开发者
PDF 转图片,一行代码搞定!批量支持已上线!
大家好,我是程序员晚枫!今天为大家介绍 `popdf` 的新功能:PDF 转图片,支持批量操作!只需一行代码即可完成单文件转换,批量处理也只需简单修改参数。工具简单易用,小白也能快速上手。`popdf` 是我开发的实用工具之一,旨在解决开发中的小痛点。欢迎访问 GitHub 项目地址 (&lt;https://github.com/CoderWanFeng/popdf&gt;),提出建议或加入开源小组,一起交流进步!快来体验吧,保证让你惊艳! 😄
366 16
|
8月前
|
程序员 开发者
开源项目:一行代码,批量 PDF 转 Word 轻松搞定!
程序员晚枫分享了 `popdf` 的新功能:支持批量 PDF 转 Word!只需简单代码,即可轻松实现单文件或批量转换。`input_path` 和 `output_path` 参数让操作更便捷,适合处理大量 PDF 文件。作为开发者,晚枫致力于解决技术小痛点,欢迎体验并反馈。项目地址:[https://github.com/CoderWanFeng/popdf](https://github.com/CoderWanFeng/popdf)
707 6
|
10月前
|
人工智能 编解码 文字识别
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
OCRmyPDF 是一款开源命令行工具,专为将扫描的 PDF 文件转换为可搜索、可复制的文档。支持多语言、图像优化和多核处理。
1118 17
OCRmyPDF:16.5K Star!快速将 PDF 文件转换为可搜索、可复制的文档的命令行工具
|
11月前
|
机器学习/深度学习 人工智能 文字识别
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
Zerox 是一款开源的本地化高精度OCR工具,基于GPT-4o-mini模型,支持PDF、DOCX、图片等多种格式文件,能够零样本识别复杂布局文档,输出Markdown格式结果。
1049 4
Zerox:AI驱动的万能OCR工具,精准识别复杂布局并输出Markdown格式,支持PDF、DOCX、图片等多种文件格式
|
10月前
|
文字识别 Serverless 开发工具
【全自动改PDF名】批量OCR识别提取PDF自定义指定区域内容保存到 Excel 以及根据PDF文件内容的标题来批量重命名
学校和教育机构常需处理成绩单、报名表等PDF文件。通过OCR技术,可自动提取学生信息并录入Excel,便于统计分析和存档管理。本文介绍使用阿里云服务实现批量OCR识别、内容提取、重命名及导出表格的完整步骤,包括开通相关服务、编写代码、部署函数计算和设置自动化触发器等。提供Python示例代码和详细操作指南,帮助用户高效处理PDF文件。 链接: - 百度网盘:[链接](https://pan.baidu.com/s/1mWsg7mDZq2pZ8xdKzdn5Hg?pwd=8866) - 腾讯网盘:[链接](https://share.weiyun.com/a77jklXK)
1337 5