pdf转图片工具类
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;public class Pdf2Png {private final static String type = "png";public static byte[] pdfToImage(byte[] pdfBytes) {PDDocument pdDocument = null;ByteArrayOutputStream bao = null;byte[] imageBytes = null;try {int dpi = 296;pdDocument = PDDocument.load(pdfBytes);PDFRenderer renderer = new PDFRenderer(pdDocument);///int pageCount = pdDocument.getNumberOfPages();/* dpi越大转换后越清晰,相对转换速度越慢 *//// for (int i = 0; i < pageCount; i++)// 转化第一张BufferedImage image = renderer.renderImageWithDPI(0, dpi);bao = new ByteArrayOutputStream();ImageIO.write(image, type, bao);imageBytes = bao.toByteArray();} catch (Exception e) {e.printStackTrace();} finally {try {// 这里需要关闭PDDocument,不然如果想要删除pdf文件时会提示文件正在使用,无法删除的情况if (null != bao) {bao.close();}if (null != pdDocument) {pdDocument.close();}} catch (IOException e) {e.printStackTrace();}}return imageBytes;}
}
byte[]转字符串数据
适用场景:接口交互传输文件
import org.apache.commons.codec.binary.Base64;
import java.nio.file.Files;
import java.nio.file.Paths;
public class T {public static void main(String[] args) throws IOException {String fileName = "D:\\pdf.pdf";byte[] bytes = Files.readAllBytes(Paths.get(fileName));String pdfContent = Base64.encodeBase64String(bytes);byte[] byte2 = Base64.decodeBase64(pdfContent);String pdfContent2 = Base64.encodeBase64String(byte2);System.out.println(pdfContent.equals(pdfContent2));}
}