【java导出PDF】

记录一次java导出PDF的经验

每次下载导出都要到处搜索,把自己的经验记录下来以便以后使用。
主要思想就是将查询到的数据放入一个Map中调用generateTempPDF方法按照项目中存储的模板生成一个临时目录下的pdf,然后调用controller里面的导出逻辑将临时目录下的pdf导出即可,最终删除临时目录下的临时文件即可。
主要依赖:

  <dependency>
             <groupId>com.itextpdf</groupId>
             <artifactId>itextpdf</artifactId>
             <version>5.5.10</version>
    </dependency>
            <dependency>
             <groupId>com.itextpdf</groupId>
             <artifactId>itext-asian</artifactId>
             <version>5.2.0</version>
    </dependency>

1.首先要使用adobe Acrobat pro DC准备表单将参数都填入,例如:

在这里插入图片描述
临时目录及模板放入项目的resources下即可:
在这里插入图片描述

2.Controller层

@GetMapping(“/exportPersonalPdf”)
public void exportPersonalPdf(HttpServletRequest request, HttpServletResponse response, String testSn) {
BufferedInputStream bis = null;
OutputStream os = null;
String outPath = null;
try {
long userId = getUser();
// 这个地方将数据返回一个导出的pdf临时存储的绝对路径即可
String tempPath = pdfSerrvice.generatePersonalPdf(userId, testSn);
if (tempPath != null) {
// 获取项目根目录
outPath = FileUtil.getFileAbsPath(tempPath);
String fileName = “pdf文件名称.pdf”;
InputStream path = new FileInputStream(outPath);
// 判断浏览器类型
String agent = (String) request.getHeader(“USER-AGENT”);
if (agent != null && agent.indexOf(“Firefox”) != -1) {
// UTF-8编码,防止输出文件名乱码
fileName = new String(fileName.getBytes(“UTF-8”), “iso-8859-1”);
} else {
fileName = URLEncoder.encode(fileName, “UTF-8”);
}
response.reset();
response.setCharacterEncoding(“utf-8”);
response.setContentType(“application/pdf”);
response.setHeader(“Content-Disposition”, “attachment; filename=” + fileName);
bis = new BufferedInputStream(path);
byte[] b = new byte[bis.available() + 1000];
int i = 0;
// 直接下载导出
os = response.getOutputStream();
while ((i = bis.read(b)) != -1) {
os.write(b, 0, i);
}
os.flush();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 下载成功将临时目录下的文件清理
FileUtil.deleteLocationFile(outPath);
}
}

3.业务层

/**
* 生成pdf存放到临时文件夹下
*
* @param dataMap 外部输入的数据
* @param templatePath 模板路径
* @param tempPath 临时文件路径
* @throws IOException 异常
* @return 返回的是生成的pdf临时路径,用完之后需要清理
*/
public static String generateTempPDF(Map<String, Object> dataMap,
String templatePath, String tempPath) throws IOException {
PdfReader reader = null;
PdfStamper ps = null;
OutputStream fos = null;
ByteArrayOutputStream bos = null;
String outPath = null;
try {
// 模板绝对路径 “files/pdf模板.pdf”
String fileName = FileUtil.getFileAbsPath(templatePath);
reader = new PdfReader(fileName);
bos = new ByteArrayOutputStream();
ps = new PdfStamper(reader, bos);

        // 使用中文字体
        BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
        fontList.add(bf);

        AcroFields fields = ps.getAcroFields();
        fields.setSubstitutionFonts(fontList);
        fillData(fields, dataMap);//渲染

        // 必须要调用这个,否则文档不会生成的
        ps.setFormFlattening(true);
        if (ps != null) {
            ps.close();
        }
        outPath = FileUtil.getFileAbsPath(tempPath);
        // 生成pdf路径存放的路径 "temp/temp" + TimeUtil.formatDate(new Date()) + ".pdf"
        File file = new File(outPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        fos = new FileOutputStream(outPath);
        fos.write(bos.toByteArray());
    } catch (Exception exception) {
        log.error("generateTempPDF exception.", exception);
    } finally {
        if (fos != null) {
            fos.flush();
            fos.close();
        }
        if (bos != null) {
            bos.close();
        }
        if (reader != null) {
            reader.close();
        }
    }
    return outPath;
}

/**
 * 填充模板中的数据
 */
private static void fillData(AcroFields fields, Map<String, Object> data) {
    try {

        for (String key : fields.getFields().keySet()) {
            Object value = data.get(key);
            if (value == null) {
                continue;
            }
            fields.setField(key, value.toString());
        }     
    } catch (Exception e) {
        e.printStackTrace();
    }
}

4.业务中使用的几个方法

import com.google.common.io.BaseEncoding;
import com.sun.jna.Platform;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Base64.Decoder;

/**
* 获取文件绝对路径
*
* @param filePath filePath
* @return String
*/
public static String getFileAbsPath(String filePath) {
String path = null;
if (Platform.isWindows()) {
// 在win64系统的固定位置
path = (GeneratePdf.class.getResource(“/”).getPath() + filePath).substring(1).replaceAll(“/”, “\\”);

    } else if (Platform.isLinux()) {
        // 在linux64系统的固定位置
        path = "/usr/" + filePath;
    }
    System.out.println(path);
    return path;
}

/**
* 将日期date 转换成字符串
*
* @param date date
* @return String
* @throws ParseException
*/
public static String formatDate(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(“yyyy_MM_dd_HH_mm_ss”);
String str = simpleDateFormat.format(date);
return str;
}

要在Java导出PDF文件,你可以使用一些开源库和框架来实现。以下是一种常见的方法: 1. 首先,你需要添加相关的依赖项到你的项目中。一个常用的Java库是 Apache PDFBox,它提供了创建和操作PDF文件的功能。你可以在你的构建工具中添加以下依赖项: ```xml <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.26</version> </dependency> ``` 2. 创建一个PDF文档对象,并添加内容到文档中。下面是一个简单的示例代码: ```java import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.PDPageContentStream; import java.io.File; import java.io.IOException; public class PDFExporter { public static void main(String[] args) { try { // 创建一个新的PDF文档 PDDocument document = new PDDocument(); // 添加一个页面 PDPage page = new PDPage(PDRectangle.A4); document.addPage(page); // 创建页面内容流 PDPageContentStream contentStream = new PDPageContentStream(document, page); // 添加文本到页面 contentStream.beginText(); contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12); contentStream.newLineAtOffset(100, 700); contentStream.showText("Hello, World!"); contentStream.endText(); // 关闭流并保存文档 contentStream.close(); document.save(new File("output.pdf")); // 关闭文档 document.close(); System.out.println("PDF导出完成!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码将创建一个包含 "Hello, World!" 文本的PDF文件。你可以根据自己的需求修改代码来添加更多内容和样式。 3. 运行代码,你将在项目的根目录下找到名为 "output.pdf" 的PDF文件,它就是导出PDF文档。 这只是一个简单的示例,你可以根据实际需求进行更复杂的PDF操作。希望能帮到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值