问题需求
今天在做发送邮件功能的时候,发现邮件的附件部分,比如pdf文档,要求先把pdf转为base64,邮件才会发送。那接下来就先看看Java 如何把 pdf文档转为base64。
两种方式,一种是通过插件 jar 包的方式引入,另外一种则是 通过原生的 文件流来读取pdf 并转为 byte 字节。
jar包引入
<dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>2.0.1</version>
</dependency><dependency><groupId>org.apache.pdfbox</groupId><artifactId>pdfbox</artifactId><version>2.0.1</version>
</dependency>
代码测试
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.io.RandomAccessBuffer;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;public class PDFToBase64 {public static String convertPDFToBase64(Path pdfPath) throws IOException {try (PDDocument document = PDDocument.load(pdfPath.toFile())) {// 使用ByteArrayOutputStream来获取PDF的字节内容ByteArrayOutputStream outputStream = new ByteArrayOutputStream();document.save(outputStream);byte[] pdfBytes = outputStream.toByteArray();// 将字节转换为Base64字符串return Base64.getEncoder().encodeToString(pdfBytes);}}public static void main(String[] args) {try {Path pdfPath = Files.createTempFile("test", ".pdf");// 这里应该是你的PDF文件路径String base64String = convertPDFToBase64(pdfPath);System.out.println(base64String);} catch (IOException e) {e.printStackTrace();}}
}
原生 InputStream 实现
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;try {URL obj = new URL(url);HttpURLConnection con = (HttpURLConnection) obj.openConnection();// 添加请求头,如有必要con.setRequestMethod("GET");con.setRequestProperty("Accept", "application/pdf");int responseCode = con.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) { // 200InputStream inputStream = con.getInputStream();ByteArrayOutputStream outputStream = new ByteArrayOutputStream();byte[] buffer = new byte[4096];int n;while ((n = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, n);}byte[] pdfBytes = outputStream.toByteArray();String base64Encoded = Base64.getEncoder().encodeToString(pdfBytes);log.info("base64==" + base64Encoded);return base64Encoded;} else {System.out.println("GET request not worked");}} catch (Exception e) {e.printStackTrace();}