某w*s圖片轉(zhuǎn)PDF還要收費,簡直不講武德!我啪的一下,很快啊,一段代碼搞定!
引入pom依賴文章來源:http://www.zghlxwxcb.cn/news/detail-791555.html
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
工具類文章來源地址http://www.zghlxwxcb.cn/news/detail-791555.html
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 圖片轉(zhuǎn)PDF
*/
@Slf4j
public class ImageToPdfConverter {
public static void main(String[] args) throws IOException {
String imgFilePath = "E:\\STUDY\\1111.jpg";
String pdfFilePath = "E:\\STUDY\\1111.pdf";
downloadPdf(imgFilePath, pdfFilePath);
}
/**
* 下載
*
* @param imgFilePath img文件路徑
* @param filePath 文件路徑
* @throws IOException ioexception
*/
private static void downloadPdf(String imgFilePath, String filePath) {
try {
// 1.將本地的圖片轉(zhuǎn)成流形式
File imgFile = new File(imgFilePath);
byte[] imageBytes = readBytesFromFile(imgFile);
// 2. 生成一頁 PDF document
PDDocument document = new PDDocument();
PDImageXObject image = PDImageXObject.createFromByteArray(document, imageBytes, "image");
// 這里是你生成PDF自適應(yīng)圖片大小,不設(shè)置會默認(rèn)為A4
PDRectangle pageSize = new PDRectangle(image.getWidth(), image.getHeight());
PDPage page = new PDPage(pageSize);
document.addPage(page);
// 3.將 圖片 添加進(jìn)PDF document
PDPageContentStream contentStream = new PDPageContentStream(document, page);
float pageWidth = pageSize.getWidth();
float pageHeight = pageSize.getHeight();
float imageWidth = image.getWidth();
float imageHeight = image.getHeight();
float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);
float scaledWidth = imageWidth * scale;
float scaledHeight = imageHeight * scale;
float x = (pageWidth - scaledWidth) / 2;
float y = (pageHeight - scaledHeight) / 2;
// 這里是將你的圖片填充入pdf頁
contentStream.drawImage(image, x, y, scaledWidth, scaledHeight);
contentStream.close();
// 4. 保存PDF
File outputFile = new File(filePath);
File parentFolder = outputFile.getParentFile();
if (parentFolder != null && !parentFolder.exists()) {
parentFolder.mkdirs();
}
document.save(outputFile);
document.close();
} catch (Exception e) {
log.error("pdf下載失敗,imgFilePath:{},filePath:{}", imgFilePath, filePath, e);
}
}
/**
* 從文件讀取字節(jié)
*
* @param file 文件
* @return {@link byte[]}
* @throws IOException ioexception
*/
private static byte[] readBytesFromFile(File file) throws IOException {
FileInputStream inputStream = new FileInputStream(file);
byte[] bytes = IOUtils.toByteArray(inputStream);
inputStream.close();
return bytes;
}
private static byte[] downloadImage(String imageUrl) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet(imageUrl);
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
byte[] imageBytes = IOUtils.toByteArray(inputStream);
inputStream.close();
return imageBytes;
}
/**
* 得到img字節(jié)列表
*
* @param filePath 文件路徑
* @return {@link List}<{@link byte[]}>
*/
private static List<byte[]> getImgByteList(String filePath) throws IOException {
// 轉(zhuǎn)換
List<byte[]> imageBytesList = new ArrayList<>();
File folder = new File(filePath);
File[] files = folder.listFiles();
for (File file : files) {
if (file.isFile() && isImage(file)) {
byte[] imageBytes = convertImageToBytes(file);
imageBytesList.add(imageBytes);
}
}
return imageBytesList;
}
private static boolean isImage(File file) {
String fileName = file.getName().toLowerCase();
return fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") ||
fileName.endsWith(".png") || fileName.endsWith(".gif") ||
fileName.endsWith(".bmp");
}
private static byte[] convertImageToBytes(File file) throws IOException {
BufferedImage image = ImageIO.read(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", outputStream);
return outputStream.toByteArray();
}
}
到了這里,關(guān)于Java實現(xiàn)圖片轉(zhuǎn)PDF的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!