java word转pdf 完美保留样式

本来是用的Spire.Doc生成的word文件,想直接再保存pdf一份,但是Spire.Doc保存pdf商业版有水印,免费版只能保存3页。

只能找一个word转pdf的方法了

注意:这个依赖仅限安装了wps office 或者微软office的电脑

依赖

<dependency>
	<groupId>com.documents4j</groupId>
	<artifactId>documents4j-local</artifactId>
	<version>1.0.3</version>
</dependency>
<dependency>
	<groupId>com.documents4j</groupId>
	<artifactId>documents4j-transformer-msoffice-word</artifactId>
	<version>1.0.3</version>
</dependency>

代码

try (
                InputStream docxInputStream = new FileInputStream(filePath + ".docx");
                OutputStream outputStream = new FileOutputStream(filePath + ".pdf")
        ) {
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            System.out.println("word to pdf success");
        } catch (Exception e) {
            e.printStackTrace();
        }

文章出处:使用java实现word转pdf,亲测有效,完美保留样式

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,实现Word文档(.docx)换为PDF并预览,通常会涉及到两个主要步骤:使用库将Word换成PDF,以及创建PDF预览功能。这需要使用一些第三方库,如Apache POI用于处理Word文档,iText或PDFBox用于生成PDF,以及JavaFX或类似工具来显示PDF预览。 以下是一个简单的概述: 1. **Word换至PDF:** - 使用Apache POI库中的`XWPFDocument`类读取Word文件内容。 - 创建一个`Document`对象,这是iText或PDFBox中的PDF文档构造器。 - 遍历Word文档中的段落、样式和图片等元素,将它们添加到PDF文档中。 - 使用`PdfWriter`或`PDFStamper`进行写入。 ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import com.itextpdf.text.Document; import com.itextpdf.text.pdf.PdfWriter; // ... XWPFDocument doc = new XWPFDocument(new FileInputStream("input.docx")); Document pdfDoc = new Document(); try (OutputStream out = new FileOutputStream("output.pdf")) { PdfWriter.getInstance(pdfDoc, out); pdfDoc.open(); for (XWPFParagraph paragraph : doc.getParagraphs()) { // 处理并添加段落到PDF } // 处理图片等其他元素 } ``` 2. **预览PDF:** - 使用JavaFX(需要Maven或Gradle添加相关依赖)或HTML Viewer API来预览PDF。 - 如果使用JavaFX,可以创建一个`javafx.scene.web.WebView`来显示PDF。 ```java import javafx.scene.web.WebView; import javafx.application.Application; public class PDFPreview extends Application { @Override public void start(Stage primaryStage) { WebView webView = new WebView(); webView.getEngine().load("file:///path/to/output.pdf"); primaryStage.setScene(new Scene(webView)); primaryStage.show(); } public static void main(String[] args) { launch(args); } } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值