word转pdf两种方式(免费+收费)

本文介绍了两种文档转换方法:免费的使用ApachePOI和XWPFDocument处理Word到PDF,但存在字体兼容问题;收费的freemarker模板和Aspose.Words进行Word转换,后者提供更完整功能且无明显缺点。
摘要由CSDN通过智能技术生成

一、免费方式

优点:1、免费;2、在众多免费中挑选出的转换效果相对较好,并且不用像openOffice那样安装服务

缺点:1、对字体支持没有很好,需要安装字体库或者使用宋体(对宋体支持很好)2、对于使用freeMarker模板转化过来的doc无法读取转换

第一步:

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId>
            <version>2.0.1</version>
        </dependency>

第二步:

public static void main(String[] args) throws Exception {
        FileInputStream fileInputStream = new FileInputStream("D:\\test\\研判报告docx.docx");
        XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
// 将word中字体转化为宋体,防止其他字体无法正常显示
        setFontType(xwpfDocument);
        FileOutputStream fileOutputStream = new FileOutputStream("D:\\test\\研判报告11.docx");
        PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
        fileInputStream.close();
        fileOutputStream.close();
    }


    /***
     * 将文档的文字设置为宋体 防止其他字体转pdf不显示
     * @Description:
     * @param xwpfDocument
     * @return:
     */
    private static void setFontType(XWPFDocument xwpfDocument) {
        //转换文档中文字字体
        List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
        if(paragraphs != null && paragraphs.size()>0){
            for (XWPFParagraph paragraph : paragraphs) {
                List<XWPFRun> runs = paragraph.getRuns();
                if(runs !=null && runs.size()>0){
                    for (XWPFRun run : runs) {
                        run.setFontFamily("宋体");
                    }
                }
            }
        }
        //转换表格里的字体 我也不想俄罗斯套娃但是不套真不能设置字体
        List<XWPFTable> tables = xwpfDocument.getTables();
        for (XWPFTable table : tables) {
            List<XWPFTableRow> rows = table.getRows();
            for (XWPFTableRow row : rows) {
                List<XWPFTableCell> tableCells = row.getTableCells();
                for (XWPFTableCell tableCell : tableCells) {
                    List<XWPFParagraph> paragraphs1 = tableCell.getParagraphs();
                    for (XWPFParagraph xwpfParagraph : paragraphs1) {
                        List<XWPFRun> runs = xwpfParagraph.getRuns();
                        for (XWPFRun run : runs) {
                            run.setFontFamily("宋体");
                        }
                    }
                }
            }
        }
    }

二、收费方式:

除了收费没啥缺点

1、freemarker生成word模板

①、自己新建一个word文档,内容就按照需要的格式内容

②、word文档另存为,选择xml格式

③、修改xml后缀为ftl放在如图位置

 ④代码:

    public static void main(String[] args) throws Exception {
        //1.创建配置类
        Configuration configuration=new Configuration(Configuration.getVersion());
        //2.设置模板所在的目录
        configuration.setDirectoryForTemplateLoading(new File(".\\template"));
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template = configuration.getTemplate("研判报告docx.ftl");
        //5.创建数据模型
        Map map=new HashMap();
        map.put("name","姓名姓名");
        map.put("idCard","身份证号码");
        map.put("age","36");
        map.put("sex","男");
        Map<String, Object> data1 = new HashMap<>();
        data1.put("item",map);
        Writer out =new FileWriter(new File(".\\template\\研判报告docx.docx"));

        //7.输出
        template.process(data1, out);
        //8.关闭Writer对象
        out.close();
    }

2、word转pdf

①、新建asposeLicense.xml放到如图位置

 asposeLicense.xml内容:

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

②、代码

public static void main(String[] args) {
        String docPath = ".\\template\\研判报告docx.docx";
        String savePath = ".\\template\\研判报告docx4.pdf";
        word2pdf(docPath, savePath);
    }

    public static void word2pdf(String docPath, String savePath) {
        try {
            ClassPathResource resource = new ClassPathResource("asposeLicense.xml");
            InputStream inputStream = resource.getInputStream();
            License license = new License();
            license.setLicense(inputStream);
            com.aspose.words.Document document = new com.aspose.words.Document(docPath);
            document.save(new FileOutputStream(new File(savePath)), SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

可以使用Apache POI和iText库来实现该功能。首先,需要从Apache POI库导入以下类: ```java import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; ``` 然后,可以使用以下代码将XWPFDocument对象换为PDF格式并保存为新文件: ```java // Create a document converter PdfConverter converter = new PdfConverter(); // Create a new PDF document Document pdfDocument = new Document(); // Open the input Word document FileInputStream inputStream = new FileInputStream(new File("input.docx")); XWPFDocument document = new XWPFDocument(inputStream); // Loop through all paragraphs in the Word document List<XWPFParagraph> paragraphs = document.getParagraphs(); for (XWPFParagraph paragraph : paragraphs) { // Create a new paragraph in the PDF document Paragraph pdfParagraph = pdfDocument.addParagraph(); // Loop through all runs in the Word paragraph List<XWPFRun> runs = paragraph.getRuns(); for (XWPFRun run : runs) { // Add the text content of the run to the PDF paragraph pdfParagraph.addText(run.getText(0)); } } // Close the input Word document inputStream.close(); // Save the PDF document to a new file File outputFile = new File("output.pdf"); OutputStream outputStream = new FileOutputStream(outputFile); converter.convert(pdfDocument, outputStream); outputStream.close(); ``` 以上代码将逐一处理Word文档中的所有段落,将其中的文本内容添加到新的PDF段落中,并将最终生成的PDF文档保存为一个新文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值