java PD4ML PDF生成 demo

本文详细介绍了如何在Java项目中使用PD4ML库来生成PDF文件,包括必要的jar包引入和核心代码示例,帮助开发者快速掌握PDF文档创建技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import org.zefer.pd4ml.PD4Constants;
import org.zefer.pd4ml.PD4ML;

import java.awt.*;
import java.io.*;

public class test {
    public static void main(String[] args) {
        String f = "D:/4.html";
       generatePDF(f);

    }

    public static void generatePDF(String filePath) {
        try {
            File output = new File("D:/pd4ml.pdf");
            java.io.FileOutputStream fos = new java.io.FileOutputStream(output);
            String html = readFile(filePath);
            StringReader strReader = new StringReader(html);
            PD4ML pd4ml = new PD4ML();
            pd4ml.setPageInsets(new Insets(5, 5, 5, 5));
            pd4ml.setHtmlWidth(900);
            pd4ml.setPageSize(PD4Constants.A4);  // A4竖向显示  pd4ml.changePageOrientation(PD4Constants.A4)横向显示
            pd4ml.useTTF("java:fonts", true);
            pd4ml.setDefaultTTFs("SimHei", "YouYuan", "SimSun");  //fonts.jar的配置文件中的值,用于中文乱码
            pd4ml.enableDebugInfo();
            pd4ml.render(strReader, fos);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static String readFile(String filePathAndName) {
        String fileContent = "";
        try {
            File f = new File(filePathAndName);
            if(f.isFile()&&f.exists()){
                InputStreamReader read = new InputStreamReader(new FileInputStream(f),"UTF-8");
                BufferedReader reader=new BufferedReader(read);
                String line;
                while ((line = reader.readLine()) != null) {
                    //将读取到的字符拼接
                    fileContent += line;
                }
                read.close();
            }
        } catch (Exception e) {
            System.out.println("读取文件内容操作出错");
            e.printStackTrace();
        }
        return fileContent;
    }
}

相关jar包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值